From f8377665733e7708b523bec1acba4ce17f4b1bd8 Mon Sep 17 00:00:00 2001 From: yixian Date: Wed, 5 Aug 2020 12:10:04 +1000 Subject: [PATCH 1/3] risk control: chargeback --- pom.xml | 4 +- .../manage/risk/web/RiskController.java | 16 +- .../core/RiskBusinessService.java | 6 +- .../core/impl/RiskBusinessServiceImpl.java | 414 +++++++++++------- .../web/RiskBusinessController.java | 58 ++- src/main/ui/static/analysis/risk_business.js | 293 +++++++------ .../templates/dialog_holiday_config.html | 3 + .../analysis/templates/new_riskEvent.html | 111 +++-- .../analysis/templates/riskEvent_detail.html | 15 +- 9 files changed, 551 insertions(+), 369 deletions(-) diff --git a/pom.xml b/pom.xml index 330d44d93..437cfb8df 100644 --- a/pom.xml +++ b/pom.xml @@ -5,11 +5,11 @@ au.com.royalpay.payment payment-parent - 2.2.9 + 2.2.10 4.0.0 manage - 2.3.48 + 2.3.49 UTF-8 2.4.0 diff --git a/src/main/java/au/com/royalpay/payment/manage/risk/web/RiskController.java b/src/main/java/au/com/royalpay/payment/manage/risk/web/RiskController.java index 654d65328..517becf17 100644 --- a/src/main/java/au/com/royalpay/payment/manage/risk/web/RiskController.java +++ b/src/main/java/au/com/royalpay/payment/manage/risk/web/RiskController.java @@ -5,9 +5,7 @@ import au.com.royalpay.payment.manage.risk.bean.*; import au.com.royalpay.payment.manage.risk.core.RiskMerchantService; import au.com.royalpay.payment.tools.CommonConsts; import au.com.royalpay.payment.tools.permission.enums.ManagerRole; - import com.alibaba.fastjson.JSONObject; - import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; @@ -16,7 +14,7 @@ import javax.annotation.Resource; * Created by wangning on 08/12/2016. */ @RestController -@ManagerMapping(value = "/sys/risk",role = {ManagerRole.ADMIN,ManagerRole.OPERATOR}) +@ManagerMapping(value = "/sys/risk", role = {ManagerRole.ADMIN, ManagerRole.OPERATOR}) public class RiskController { @Resource @@ -47,17 +45,15 @@ public class RiskController { riskMerchantService.dealRiskRecordDirectly(manager, record_id); } - @RequestMapping(value = "/records/{record_id}/deal",method = RequestMethod.PUT) - public void dealRecord(@ModelAttribute(CommonConsts.MANAGER_STATUS) JSONObject manager, @PathVariable String record_id, @RequestBody DealRiskRecord dealRiskRecord){ + @PutMapping("/records/{record_id}/deal") + public void dealRecord(@ModelAttribute(CommonConsts.MANAGER_STATUS) JSONObject manager, @PathVariable String record_id, @RequestBody DealRiskRecord dealRiskRecord) { dealRiskRecord.setRecordId(record_id); - riskMerchantService.dealRiskRecord(manager,dealRiskRecord); + riskMerchantService.dealRiskRecord(manager, dealRiskRecord); } @GetMapping("/orders") public JSONObject getRiskOrders(QueryRiskOrder queryRiskOrder) { return riskMerchantService.getRiskOrders(queryRiskOrder); - - } @PostMapping("/white/{clientMoniker}") @@ -71,13 +67,13 @@ public class RiskController { } @PostMapping("/records/uploadFiles") - public void addRecordLog(@ModelAttribute(CommonConsts.MANAGER_STATUS) JSONObject manager,@RequestBody AddRiskDetailLog addRiskDetailLog) { + public void addRecordLog(@ModelAttribute(CommonConsts.MANAGER_STATUS) JSONObject manager, @RequestBody AddRiskDetailLog addRiskDetailLog) { // riskMerchantService.addDetailLog(addRiskDetailLog,manager); } @GetMapping("/details") public JSONObject listDetails(QueryRiskDetail queryRiskDetail) { - return riskMerchantService.getRiskDetails(queryRiskDetail); + return riskMerchantService.getRiskDetails(queryRiskDetail); } @PostMapping("/details/remark") diff --git a/src/main/java/au/com/royalpay/payment/manage/riskbusiness/core/RiskBusinessService.java b/src/main/java/au/com/royalpay/payment/manage/riskbusiness/core/RiskBusinessService.java index 920111634..fffbedaec 100644 --- a/src/main/java/au/com/royalpay/payment/manage/riskbusiness/core/RiskBusinessService.java +++ b/src/main/java/au/com/royalpay/payment/manage/riskbusiness/core/RiskBusinessService.java @@ -1,7 +1,7 @@ package au.com.royalpay.payment.manage.riskbusiness.core; +import au.com.royalpay.payment.core.beans.ChargebackStatus; import com.alibaba.fastjson.JSONObject; -import com.github.miemiedev.mybatis.paginator.domain.PageBounds; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @@ -143,5 +143,7 @@ public interface RiskBusinessService { void completeOrderAmount(); - void UpdateRiskEventRemark(String riskId, String remark); + void updateRiskEventRemark(String riskId, String remark); + + void markChargebackStatus(String riskId, JSONObject manager, ChargebackStatus status); } diff --git a/src/main/java/au/com/royalpay/payment/manage/riskbusiness/core/impl/RiskBusinessServiceImpl.java b/src/main/java/au/com/royalpay/payment/manage/riskbusiness/core/impl/RiskBusinessServiceImpl.java index b911619f4..48e3186b6 100644 --- a/src/main/java/au/com/royalpay/payment/manage/riskbusiness/core/impl/RiskBusinessServiceImpl.java +++ b/src/main/java/au/com/royalpay/payment/manage/riskbusiness/core/impl/RiskBusinessServiceImpl.java @@ -1,8 +1,9 @@ package au.com.royalpay.payment.manage.riskbusiness.core.impl; +import au.com.royalpay.payment.core.CardSecureService; +import au.com.royalpay.payment.core.beans.ChargebackStatus; import au.com.royalpay.payment.core.exceptions.EmailException; import au.com.royalpay.payment.core.exceptions.InvalidShortIdException; -import au.com.royalpay.payment.core.exceptions.OrderNotExistsException; import au.com.royalpay.payment.core.exceptions.OrderNotMatchException; import au.com.royalpay.payment.manage.mappers.log.AppMessageLogMapper; import au.com.royalpay.payment.manage.mappers.payment.OrderMapper; @@ -20,11 +21,11 @@ import au.com.royalpay.payment.manage.riskbusiness.core.RiskMaterialService; import au.com.royalpay.payment.manage.riskbusiness.core.RiskProcessLogService; import au.com.royalpay.payment.manage.riskbusiness.core.RiskUploadService; import au.com.royalpay.payment.manage.riskbusiness.enums.RiskEmailStatusEnum; +import au.com.royalpay.payment.manage.riskbusiness.enums.RiskOrderTypeEnum; import au.com.royalpay.payment.manage.riskbusiness.enums.RiskResultTypeEnum; import au.com.royalpay.payment.manage.signin.beans.TodoNotice; import au.com.royalpay.payment.manage.signin.core.ManagerTodoNoticeProvider; import au.com.royalpay.payment.manage.tradelog.core.TradeLogService; -import au.com.royalpay.payment.manage.riskbusiness.enums.RiskOrderTypeEnum; import au.com.royalpay.payment.tools.connections.mpsupport.MpWechatApi; import au.com.royalpay.payment.tools.connections.mpsupport.MpWechatApiProvider; import au.com.royalpay.payment.tools.connections.mpsupport.beans.TemplateMessage; @@ -34,23 +35,28 @@ import au.com.royalpay.payment.tools.device.message.AppMsgSender; import au.com.royalpay.payment.tools.env.PlatformEnvironment; import au.com.royalpay.payment.tools.env.SysConfigManager; import au.com.royalpay.payment.tools.exceptions.BadRequestException; +import au.com.royalpay.payment.tools.exceptions.NotFoundException; +import au.com.royalpay.payment.tools.exceptions.ServerErrorException; import au.com.royalpay.payment.tools.exceptions.event.WechatExceptionEvent; import au.com.royalpay.payment.tools.locale.LocaleSupport; +import au.com.royalpay.payment.tools.mappers.CommonRiskEventMapper; +import au.com.royalpay.payment.tools.mappers.RiskEventDAO; import au.com.royalpay.payment.tools.permission.enums.ManagerRole; -import au.com.royalpay.payment.tools.exceptions.ServerErrorException; +import au.com.royalpay.payment.tools.risk.RiskEvent; import au.com.royalpay.payment.tools.threadpool.RoyalThreadPoolExecutor; import au.com.royalpay.payment.tools.utils.PageListUtils; -import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.github.miemiedev.mybatis.paginator.domain.Order; import com.github.miemiedev.mybatis.paginator.domain.PageBounds; import com.github.miemiedev.mybatis.paginator.domain.PageList; -import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.time.DateFormatUtils; import org.apache.commons.lang3.time.DateUtils; -import org.apache.poi.ss.usermodel.*; +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -62,17 +68,19 @@ import org.springframework.transaction.annotation.Transactional; import org.thymeleaf.context.Context; import org.thymeleaf.spring5.SpringTemplateEngine; +import javax.annotation.Resource; import javax.servlet.http.HttpServletResponse; -import java.io.*; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; import java.net.URL; import java.text.ParseException; import java.util.*; -import javax.annotation.Resource; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; -import java.util.concurrent.TimeUnit; /** * @Author lvjian @@ -80,12 +88,20 @@ import java.util.concurrent.TimeUnit; */ @Service public class RiskBusinessServiceImpl implements RiskBusinessService, ManagerTodoNoticeProvider, ApplicationEventPublisherAware { + public static final int RISK_ORDER_TYPE_WX = 1; + public static final int RISK_ORDER_TYPE_ALIPAY = 2; + public static final int RISK_ORDER_TYPE_RP = 3; + public static final int RISK_ORDER_TYPE_WARN = 4; + public static final int RISK_ORDER_TYPE_COMMON_MID = 5; + public static final int RISK_ORDER_TYPE_CHARGEBACK = 6; private Logger logger = LoggerFactory.getLogger(RiskBusinessServiceImpl.class); @Resource private RiskEventMapper riskEventMapper; @Resource + private CommonRiskEventMapper commonRiskEventMapper; + @Resource private ClientMapper clientMapper; @Resource private ClientBDMapper clientBDMapper; @@ -123,11 +139,13 @@ public class RiskBusinessServiceImpl implements RiskBusinessService, ManagerTodo @Resource private AppMessageLogMapper appMessageLogMapper; - private Map senderMap = new HashMap<>(); + private final Map senderMap = new HashMap<>(); @Resource private APNSMessageHelper apnsMessageHelper; @Resource + private CardSecureService cardSecureService; + @Resource private ManagerMapper managerMapper; @Resource private ClientAccountMapper clientAccountMapper; @@ -144,7 +162,7 @@ public class RiskBusinessServiceImpl implements RiskBusinessService, ManagerTodo Arrays.stream(senders).forEach(appMsgSender -> senderMap.put(appMsgSender.devType(), appMsgSender)); } - private ThreadPoolExecutor sendingAppleMsgPool = new ThreadPoolExecutor(10, 30, 5, TimeUnit.SECONDS, new LinkedBlockingQueue()); + private final ThreadPoolExecutor sendingAppleMsgPool = new ThreadPoolExecutor(10, 30, 5, TimeUnit.SECONDS, new LinkedBlockingQueue()); @Override public List getRiskEvents(JSONObject params) { @@ -158,7 +176,7 @@ public class RiskBusinessServiceImpl implements RiskBusinessService, ManagerTodo if (manager != null && ManagerRole.BD_USER.hasRole(manager.getIntValue("role"))) { params.put("bd_id", manager.getString("manager_id")); List orderTypes = Arrays.asList(RiskOrderTypeEnum.WECHAT_ORDER.getOrderType(), - RiskOrderTypeEnum.ALIPAY_ORDER.getOrderType(),RiskOrderTypeEnum.ROYALPAY_ORDER.getOrderType()); + RiskOrderTypeEnum.ALIPAY_ORDER.getOrderType(), RiskOrderTypeEnum.ROYALPAY_ORDER.getOrderType()); params.put("order_types", orderTypes); List resultTypes = Arrays.asList(RiskResultTypeEnum.SEND_EMAIL_TO_BD.getResultType(), @@ -176,8 +194,10 @@ public class RiskBusinessServiceImpl implements RiskBusinessService, ManagerTodo * 微信调单、支付宝调单、royalpay调单 * 未处理、已发送、待审核、打回 */ - Date currentDate = new Date(), replyDate; - Integer resultType, orderType; + Date currentDate = new Date(); + Date replyDate; + Integer resultType; + Integer orderType; boolean isPassTimeout = false; for (JSONObject riskEvent : riskEvents) { try { @@ -206,15 +226,15 @@ public class RiskBusinessServiceImpl implements RiskBusinessService, ManagerTodo @Override public List analysisByIndustry(JSONObject params, JSONObject manager) { List industryAnalysis = riskEventMapper.analysisByIndustry(params); - for(JSONObject industry:industryAnalysis){ - if(StringUtils.isBlank(industry.getString("industry"))){ - industry.put("industry","未知行业"); + for (JSONObject industry : industryAnalysis) { + if (StringUtils.isBlank(industry.getString("industry"))) { + industry.put("industry", "未知行业"); } } return industryAnalysis; } - private List industryArray(){ + private List industryArray() { List industryArray = new ArrayList<>(); industryArray.add("鞋包服饰"); industryArray.add("机票行业"); @@ -278,13 +298,13 @@ public class RiskBusinessServiceImpl implements RiskBusinessService, ManagerTodo * 通用号调单与其他类型的调单,订单格式不一样,所以区分 */ if (riskEvent.getIntValue("order_type") == 3) { - for (int i = 0; i < orderIdArray.length; i++) { - orderInfo = tradeLogService.getOrderDetail(new JSONObject(), riskEvent.getString("client_moniker"), orderIdArray[i], null); + for (String orderId : orderIdArray) { + orderInfo = tradeLogService.getOrderDetail(new JSONObject(), riskEvent.getString("client_moniker"), orderId, null); tradeLogs.add(orderInfo); } } else { - for (int i = 0; i < orderIdArray.length; i++) { - orderInfo = orderMapper.findOrderById(orderIdArray[i],client.getIntValue("client_id")); + for (String orderId : orderIdArray) { + orderInfo = orderMapper.findOrderById(orderId, client.getIntValue("client_id")); tradeLogs.add(orderInfo); } } @@ -298,7 +318,7 @@ public class RiskBusinessServiceImpl implements RiskBusinessService, ManagerTodo String clientMoniker = params.getString("client_moniker"); if (clientMoniker != null) { client = clientMapper.findClientByMonikerAll(clientMoniker); - if(client == null){ + if (client == null) { throw new InvalidShortIdException(); } } @@ -322,7 +342,7 @@ public class RiskBusinessServiceImpl implements RiskBusinessService, ManagerTodo PageList transactionList = transactionMapper.findByClientIdAndSystemTransactionId(client.getIntValue("client_id"), orderIdArray[i], new PageBounds(Order.formString("transaction_time.desc"))); // 判断该笔订单是否存在,是否属于该商户 // 由于查询订单时已经关联商户了,所以只会抛出订单不匹配的异常 - if (transactionList == null || transactionList.size() <= 0) + if (transactionList == null || transactionList.isEmpty()) throw new OrderNotMatchException(); /* else { @@ -349,6 +369,7 @@ public class RiskBusinessServiceImpl implements RiskBusinessService, ManagerTodo * 添加风控事件 * 更新risk_orders表 * 记录风控日志 + * * @param params * @param manager */ @@ -364,38 +385,51 @@ public class RiskBusinessServiceImpl implements RiskBusinessService, ManagerTodo RiskResultTypeEnum.NOT_HANDLED.getRemark(), RiskResultTypeEnum.NOT_HANDLED.getResultType(), RiskResultTypeEnum.NOT_HANDLED.getResultType()); + int orderType = params.getIntValue("order_type"); + if (orderType == RISK_ORDER_TYPE_CHARGEBACK) { + logger.info("Chargeback event"); + RiskEvent evt = getRiskEvent(params.getString("risk_id")); + if (evt == null) { + return; + } + cardSecureService.submitChargeBackReport(evt); + } + } + + private RiskEvent getRiskEvent(String riskId) { + return Optional.ofNullable(commonRiskEventMapper.findById(riskId)).map(RiskEventDAO::convert).orElse(null); } - private void setRiskOrders(JSONObject params){ - if(StringUtils.isNotBlank(params.getString("real_order_ids"))){ + private void setRiskOrders(JSONObject params) { + if (StringUtils.isNotBlank(params.getString("real_order_ids"))) { String riskId = params.getString("risk_id"); String orderIds = params.getString("real_order_ids"); - for(String orderId : orderIds.split(",")){ + for (String orderId : orderIds.split(",")) { JSONObject order = transactionMapper.findByOrderId(orderId); JSONObject riskOrder = new JSONObject(); - riskOrder.put("risk_id",riskId); - riskOrder.put("order_id",orderId); - riskOrder.put("clearing_amount",order.getString("clearing_amount")); + riskOrder.put("risk_id", riskId); + riskOrder.put("order_id", orderId); + riskOrder.put("clearing_amount", order.getString("clearing_amount")); riskOrdersMapper.save(riskOrder); } } } @Override - public void updateRiskEvent(JSONObject params,JSONObject manager) { - if(StringUtils.isNotBlank(params.getString("channel_result"))){ + public void updateRiskEvent(JSONObject params, JSONObject manager) { + if (StringUtils.isNotBlank(params.getString("channel_result"))) { JSONObject risk = riskEventMapper.findById(params.getString("risk_id")); //填写渠道处理结果时候,支付宝、微信和内部调单在材料审核通过前无法填写渠道处理结果 - if(params.getIntValue("result_type") < RiskResultTypeEnum.MATERIAL_AUDIT_PASS.getResultType() && params.getIntValue("order_type") < RiskOrderTypeEnum.WARNING_ORDER.getOrderType()){ + if (params.getIntValue("result_type") < RiskResultTypeEnum.MATERIAL_AUDIT_PASS.getResultType() && params.getIntValue("order_type") < RiskOrderTypeEnum.WARNING_ORDER.getOrderType()) { throw new BadRequestException("请先提交渠道方材料进行审核!"); } //渠道处理结果不一样,才会记录操作并更改事件单状态为渠道方处理结果 - if(risk.getString("channel_result")==null || !risk.getString("channel_result").equals(params.getString("channel_result"))){ - params.put("result_type",RiskResultTypeEnum.ALREADY_HANDLED.getResultType()); + if (risk.getString("channel_result") == null || !risk.getString("channel_result").equals(params.getString("channel_result"))) { + params.put("result_type", RiskResultTypeEnum.ALREADY_HANDLED.getResultType()); riskProcessLogService.addRiskProcessLog(params.getString("risk_id"), manager.getString("manager_id"), manager.getString("display_name"), - RiskResultTypeEnum.ALREADY_HANDLED.getRemark() + ":"+ params.getString("channel_result"), + RiskResultTypeEnum.ALREADY_HANDLED.getRemark() + ":" + params.getString("channel_result"), params.getIntValue("result_type"), RiskResultTypeEnum.ALREADY_HANDLED.getResultType()); } @@ -411,12 +445,12 @@ public class RiskBusinessServiceImpl implements RiskBusinessService, ManagerTodo public void sendWxMess(JSONObject params, String channel, int result_type) { String type = "禁用"; if (params.get("temporary_close_merchant") != null) { - if (params.getBoolean("temporary_close_merchant")) { + if (params.getBooleanValue("temporary_close_merchant")) { type = "临时禁用"; } } if (params.get("temporary_close_channel") != null) { - if (params.getBoolean("temporary_close_channel")) { + if (params.getBooleanValue("temporary_close_channel")) { type = "临时禁用"; } } @@ -437,14 +471,14 @@ public class RiskBusinessServiceImpl implements RiskBusinessService, ManagerTodo for (String bdId : bdIdArray) { JSONObject bd = managerMapper.findById(bdId); if (bd != null) { - if (bd.get("wx_openid")!=null){ + if (bd.get("wx_openid") != null) { if (StringUtils.isNotBlank(bd.getString("wx_openid"))) { try { MpWechatApi paymentApi = mpWechatApiProvider.getNewPaymentApi(); - TemplateMessage msg = initSendBDCloseChannelAndPartnerTemplate(bd.getString("wx_openid"), paymentApi.getTemplateId("risk-forbidden-channelAndPartner"),client); + TemplateMessage msg = initSendBDCloseChannelAndPartnerTemplate(bd.getString("wx_openid"), paymentApi.getTemplateId("risk-forbidden-channelAndPartner"), client); paymentApi.sendTemplateMessage(msg); } catch (WechatException e) { - logger.error("Wechat Message Error,风控关闭通道" + e.getMessage()); + logger.error("Wechat Message Error,风控关闭通道{}", e.getMessage()); publisher.publishEvent(new WechatExceptionEvent(this, e, "风控关闭通道")); } } @@ -455,14 +489,14 @@ public class RiskBusinessServiceImpl implements RiskBusinessService, ManagerTodo List accounts = clientAccountMapper.listRiskNoticeAccounts(client.getIntValue("client_id")); if (accounts != null) { for (JSONObject account : accounts) { - if (account.get("wechat_openid")!=null){ + if (account.get("wechat_openid") != null) { if (StringUtils.isNotBlank(account.getString("wechat_openid"))) { try { MpWechatApi paymentApi = mpWechatApiProvider.getNewPaymentApi(); - TemplateMessage msg = initSendPartnerCloseChannelAndPartnerTemplate(account.getString("wechat_openid"), paymentApi.getTemplateId("risk-forbidden-channelAndPartner"),client); + TemplateMessage msg = initSendPartnerCloseChannelAndPartnerTemplate(account.getString("wechat_openid"), paymentApi.getTemplateId("risk-forbidden-channelAndPartner"), client); paymentApi.sendTemplateMessage(msg); } catch (WechatException e) { - logger.error("Wechat Message Error,风控关闭通道" + e.getMessage()); + logger.error("Wechat Message Error,风控关闭通道,{}", e.getMessage()); publisher.publishEvent(new WechatExceptionEvent(this, e, "风控关闭通道")); } } @@ -473,26 +507,27 @@ public class RiskBusinessServiceImpl implements RiskBusinessService, ManagerTodo } - private TemplateMessage initSendBDCloseChannelAndPartnerTemplate(String wxopenid, String templateId,JSONObject client) { - TemplateMessage msg = new TemplateMessage(wxopenid, templateId,null); + private TemplateMessage initSendBDCloseChannelAndPartnerTemplate(String wxopenid, String templateId, JSONObject client) { + TemplateMessage msg = new TemplateMessage(wxopenid, templateId, null); //1:关闭渠道;2:关闭商户 if (client.getIntValue("result_type") == 1) { - msg.put("first", "您的商户("+client.getString("client_moniker")+")" + client.getString("channel") + "支付渠道已"+client.getString("close_type"), "#000000"); - }else { - msg.put("first", "您的商户("+client.getString("client_moniker")+")已"+client.getString("close_type"), "#000000"); + msg.put("first", "您的商户(" + client.getString("client_moniker") + ")" + client.getString("channel") + "支付渠道已" + client.getString("close_type"), "#000000"); + } else { + msg.put("first", "您的商户(" + client.getString("client_moniker") + ")已" + client.getString("close_type"), "#000000"); } msg.put("keyword1", client.getString("channel") + "风控调单", "#0000ff"); msg.put("keyword2", DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"), "#000000"); msg.put("remark", "请联系商户尽快配合风控部门上传相应资料,以免影响支付", "#0000FF"); return msg; } - private TemplateMessage initSendPartnerCloseChannelAndPartnerTemplate(String wxopenid, String templateId,JSONObject client) { - TemplateMessage msg = new TemplateMessage(wxopenid, templateId,null); + + private TemplateMessage initSendPartnerCloseChannelAndPartnerTemplate(String wxopenid, String templateId, JSONObject client) { + TemplateMessage msg = new TemplateMessage(wxopenid, templateId, null); //1:关闭渠道;2:关闭商户 if (client.getIntValue("result_type") == 1) { - msg.put("first", "您的商户" + client.getString("channel") + "支付渠道已"+client.getString("close_type"), "#000000"); - }else { - msg.put("first", "您的商户("+client.getString("client_moniker")+")已"+client.getString("close_type"), "#000000"); + msg.put("first", "您的商户" + client.getString("channel") + "支付渠道已" + client.getString("close_type"), "#000000"); + } else { + msg.put("first", "您的商户(" + client.getString("client_moniker") + ")已" + client.getString("close_type"), "#000000"); } msg.put("keyword1", client.getString("channel") + "风控调单", "#0000ff"); msg.put("keyword2", DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"), "#000000"); @@ -507,6 +542,7 @@ public class RiskBusinessServiceImpl implements RiskBusinessService, ManagerTodo /** * 下载审核材料 + * * @param riskId * @param response */ @@ -524,11 +560,11 @@ public class RiskBusinessServiceImpl implements RiskBusinessService, ManagerTodo response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=" + downloadFilename); ZipOutputStream zos = new ZipOutputStream(response.getOutputStream()); - for(int i = 1; i <= 6; i++){ - if(riskMaterial.containsKey("file" + i)){ - List fileList= (List) riskMaterial.get("file"+i); - for(String fileUrl : fileList){ - zos.putNextEntry(new ZipEntry("file" + i+fileUrl.substring(fileUrl.lastIndexOf("/")))); + for (int i = 1; i <= 6; i++) { + if (riskMaterial.containsKey("file" + i)) { + List fileList = (List) riskMaterial.get("file" + i); + for (String fileUrl : fileList) { + zos.putNextEntry(new ZipEntry("file" + i + fileUrl.substring(fileUrl.lastIndexOf("/")))); InputStream inputStream = new URL(fileUrl).openConnection().getInputStream(); byte[] buffer = new byte[1024]; int result = 0; @@ -551,6 +587,7 @@ public class RiskBusinessServiceImpl implements RiskBusinessService, ManagerTodo * 更新事件信息 * 记录风控日志 * App推送消息 + * * @param riskId * @throws IOException */ @@ -558,22 +595,22 @@ public class RiskBusinessServiceImpl implements RiskBusinessService, ManagerTodo public void sendUploadEmail(String riskId) throws IOException { JSONObject event = getRiskEventDetail(riskId); Context ctx = getMailContext(event); - final List emailsTos = (List)ctx.getVariable("emailsTos"); - final List emailsCcs = ctx.getVariable("emailsCcs")==null?new ArrayList<>():(List)ctx.getVariable("emailsCcs"); + final List emailsTos = (List) ctx.getVariable("emailsTos"); + final List emailsCcs = ctx.getVariable("emailsCcs") == null ? new ArrayList<>() : (List) ctx.getVariable("emailsCcs"); final List emailsBccs = ctx.getVariable("emailsBccs") == null ? new ArrayList<>() : (List) ctx.getVariable("emailsBccs"); - final String title = (String)ctx.getVariable("title"); + final String title = (String) ctx.getVariable("title"); final String content = thymeleaf.process("mail/risk_upload_mail.html", ctx); - final String uploadUrl = (String)ctx.getVariable("uploadUrl"); + final String uploadUrl = (String) ctx.getVariable("uploadUrl"); royalThreadPoolExecutor.execute(() -> { try { String emailId = mailService.sendRiskEmail(title, emailsTos.isEmpty() ? "" : StringUtils.join(emailsTos, ","), emailsCcs.isEmpty() ? "" : StringUtils.join(emailsCcs, ","), emailsBccs.isEmpty() ? "" : StringUtils.join(emailsBccs, ","), - content, null,event.getIntValue("order_type")); + content, null, event.getIntValue("order_type")); event.put("email_status", RiskEmailStatusEnum.ALREADY_SEND.getEmailStatus()); event.put("result_type", RiskResultTypeEnum.SEND_EMAIL_TO_BD.getResultType()); - event.put("submit_url",uploadUrl); + event.put("submit_url", uploadUrl); Integer orderType = event.getInteger("order_type"); if (orderType.equals(RiskOrderTypeEnum.WARNING_ORDER.getOrderType())) { event.put("result_type", RiskResultTypeEnum.ALREADY_HANDLED.getResultType()); @@ -585,7 +622,7 @@ public class RiskBusinessServiceImpl implements RiskBusinessService, ManagerTodo RiskResultTypeEnum.SEND_EMAIL_TO_BD.getRemark(), RiskResultTypeEnum.NOT_HANDLED.getResultType(), RiskResultTypeEnum.SEND_EMAIL_TO_BD.getResultType()); - if(event.getIntValue("is_send_client") == 1){ + if (event.getIntValue("is_send_client") == 1) { sendAppRiskMessage(event); } } catch (Exception e) { @@ -597,11 +634,12 @@ public class RiskBusinessServiceImpl implements RiskBusinessService, ManagerTodo /** * App推送消息 * 推送类型risk + * * @param event */ - private void sendAppRiskMessage(JSONObject event){ + private void sendAppRiskMessage(JSONObject event) { JSONObject client = clientMapper.findClientByMoniker(event.getString("client_moniker")); - logger.debug("sendRiskAppMessage-" + client.getString("client_moniker") + "-" + "risk_id:"+event.getString("risk_id")); + logger.debug("sendRiskAppMessage-{}-risk_id:{}", client.getString("client_moniker"), event.getString("risk_id")); List tokens = clientDeviceTokenMapper.listTokensByClient_id(client.getIntValue("client_id")); for (JSONObject devToken : tokens) { Runnable task = () -> { @@ -634,7 +672,7 @@ public class RiskBusinessServiceImpl implements RiskBusinessService, ManagerTodo log.put("status", 2); appMessageLogMapper.update(log); } catch (Exception e) { - logger.error("出错了:" + e.getMessage()); + logger.error("出错了:{}", e.getMessage()); appMessageLogMapper.updateStatus(log.getString("send_id"), 1, e.getMessage()); throw new ServerErrorException("Send App " + devToken.getString("client_type") + " Failed" + ",token" + token, e); } @@ -645,6 +683,7 @@ public class RiskBusinessServiceImpl implements RiskBusinessService, ManagerTodo /** * 记录消息推送日志 + * * @param dev_id * @param client_id * @param messageType @@ -670,6 +709,7 @@ public class RiskBusinessServiceImpl implements RiskBusinessService, ManagerTodo * 判断当前事件处理状态是否合理 * 更新事件 * 记录风控日志 + * * @param riskId * @param refuseDescription 拒绝说明 * @throws IOException @@ -683,29 +723,29 @@ public class RiskBusinessServiceImpl implements RiskBusinessService, ManagerTodo throw new BadRequestException("Refused Already!"); } else if (RiskResultTypeEnum.MATERIAL_AUDIT_PASS.getResultType().intValue() == resultType) { throw new BadRequestException("Passed Already!"); - } else if (RiskResultTypeEnum.WAIT_FOR_AUDIT.getResultType().intValue() != resultType){ + } else if (RiskResultTypeEnum.WAIT_FOR_AUDIT.getResultType().intValue() != resultType) { throw new BadRequestException(); } riskMaterialService.updateRiskMaterial(riskId, refuseDescription); Context ctx = getMailContext(event); - ctx.setVariable("refuse",true); + ctx.setVariable("refuse", true); List findAllMaterials = riskMaterialMapper.findAllMaterials(riskId); if (findAllMaterials == null || findAllMaterials.size() == 0) { ctx.setVariable("refuse_description", ""); - }else { + } else { ctx.setVariable("refuse_description", findAllMaterials.get(0).getString("refuse_description")); } - final List emailsTos = (List)ctx.getVariable("emailsTos"); - final List emailsCcs = ctx.getVariable("emailsCcs")==null?new ArrayList<>():(List)ctx.getVariable("emailsCcs"); - final String uploadUrl = (String)ctx.getVariable("uploadUrl"); + final List emailsTos = (List) ctx.getVariable("emailsTos"); + final List emailsCcs = ctx.getVariable("emailsCcs") == null ? new ArrayList<>() : (List) ctx.getVariable("emailsCcs"); + final String uploadUrl = (String) ctx.getVariable("uploadUrl"); final String content = thymeleaf.process("mail/risk_upload_mail.html", ctx); royalThreadPoolExecutor.execute(() -> { try { String emailId = mailService.sendRiskEmail("You need to resubmit risk materials", emailsTos.isEmpty() ? "" : StringUtils.join(emailsTos, ","), - emailsCcs.isEmpty() ? "" : StringUtils.join(emailsCcs, ","), "",content, null,event.getIntValue("order_type")); - event.put("email_status",RiskEmailStatusEnum.BACK_AND_SEND.getEmailStatus()); - event.put("result_type",RiskResultTypeEnum.MATERIAL_NOT_PASS.getResultType()); - event.put("submit_url",uploadUrl); + emailsCcs.isEmpty() ? "" : StringUtils.join(emailsCcs, ","), "", content, null, event.getIntValue("order_type")); + event.put("email_status", RiskEmailStatusEnum.BACK_AND_SEND.getEmailStatus()); + event.put("result_type", RiskResultTypeEnum.MATERIAL_NOT_PASS.getResultType()); + event.put("submit_url", uploadUrl); riskEventMapper.update(event); riskProcessLogService.addRiskProcessLog(riskId, event.getString("fillin_id"), @@ -721,6 +761,7 @@ public class RiskBusinessServiceImpl implements RiskBusinessService, ManagerTodo /** * 发送催促邮件 + * * @param riskId * @throws IOException */ @@ -728,14 +769,14 @@ public class RiskBusinessServiceImpl implements RiskBusinessService, ManagerTodo public void sendUrgeEmail(String riskId) throws IOException { JSONObject event = getRiskEventDetail(riskId); Context ctx = getMailContext(event); - final List emailsTos = (List)ctx.getVariable("emailsTos"); - final List emailsCcs = ctx.getVariable("emailsCcs")==null?new ArrayList<>():(List)ctx.getVariable("emailsCcs"); + final List emailsTos = (List) ctx.getVariable("emailsTos"); + final List emailsCcs = ctx.getVariable("emailsCcs") == null ? new ArrayList<>() : (List) ctx.getVariable("emailsCcs"); final String content = thymeleaf.process("mail/risk_urge_mail.html", ctx); royalThreadPoolExecutor.execute(() -> { try { String emailId = mailService.sendRiskEmail("Please submit risk materials as soon as possible", emailsTos.isEmpty() ? "" : StringUtils.join(emailsTos, ","), - emailsCcs.isEmpty() ? "" : StringUtils.join(emailsCcs, ","),"", content, null,event.getIntValue("order_type")); - event.put("email_status",3); + emailsCcs.isEmpty() ? "" : StringUtils.join(emailsCcs, ","), "", content, null, event.getIntValue("order_type")); + event.put("email_status", 3); riskEventMapper.update(event); } catch (Exception e) { throw new EmailException("Email Sending Failed", e); @@ -750,20 +791,14 @@ public class RiskBusinessServiceImpl implements RiskBusinessService, ManagerTodo throw new InvalidShortIdException(); } String codeKey = RandomStringUtils.random(20, true, true); - while(stringRedisTemplate.boundValueOps(getRiskUploadKey(codeKey)).get()!=null ){ + while (stringRedisTemplate.boundValueOps(getRiskUploadKey(codeKey)).get() != null) { codeKey = RandomStringUtils.random(20, true, true); } String codeKeyValue = RandomStringUtils.random(10, true, true); - /* - String expireDay = "7"; - if(event.getIntValue("order_type")>2){ - expireDay = "3"; - } - )*/ // 原来设定的过期时间是7天 String expireDay = "3650"; stringRedisTemplate.boundValueOps(getRiskUploadKey(codeKey)).set(codeKeyValue, Long.parseLong(expireDay), TimeUnit.DAYS); - String uploadUrl = PlatformEnvironment.getEnv().concatUrl("/risk/upload/") + event.getString("risk_id") + "/" + codeKey; + String uploadUrl = PlatformEnvironment.getEnv().concatUrl("/risk/upload/") + event.getString("risk_id") + "/" + codeKey; int orderType = event.getIntValue("order_type"); if (orderType == 1 || orderType == 2) uploadUrl = PlatformEnvironment.getEnv().concatUrl("/manage.html#/analysis/monitoring/") + event.getString("risk_id") + "/bd/detail?codeKey=" + codeKey; @@ -782,10 +817,10 @@ public class RiskBusinessServiceImpl implements RiskBusinessService, ManagerTodo } List clientEmails = new ArrayList<>(); clientEmails.add(client.getString("contact_email")); - client.put("is_resend",new Date().compareTo(event.getDate("reply_email_date"))); + client.put("is_resend", new Date().compareTo(event.getDate("reply_email_date"))); String bdNamesStr = bdNames.isEmpty() ? "" : StringUtils.join(bdNames, ","); - String reply_date = DateFormatUtils.format(DateUtils.addDays(event.getDate("reply_email_date"),-1),"yyyy年MM月dd日"); - String reply_date_english = DateFormatUtils.format(DateUtils.addDays(event.getDate("reply_email_date"),-1),"dd/MM/yyyy"); + String reply_date = DateFormatUtils.format(DateUtils.addDays(event.getDate("reply_email_date"), -1), "yyyy年MM月dd日"); + String reply_date_english = DateFormatUtils.format(DateUtils.addDays(event.getDate("reply_email_date"), -1), "dd/MM/yyyy"); GregorianCalendar gregorianCalendar = new GregorianCalendar(); String hello = gregorianCalendar.get(GregorianCalendar.AM_PM) == 0 ? "上午好" : "下午好"; Context ctx = new Context(); @@ -799,9 +834,9 @@ public class RiskBusinessServiceImpl implements RiskBusinessService, ManagerTodo ctx.setVariable("royalpay_order_type", event.getIntValue("royalpay_order_type")); ctx.setVariable("warning_order_type", event.getIntValue("warning_order_type")); ctx.setVariable("description", event.getString("description")); - ctx.setVariable("is_send_client",event.getIntValue("is_send_client")); - ctx.setVariable("mail_template",event.get("mail_template")==null?0:event.getIntValue("mail_template")); - ctx.setVariable("send_clean_days",event.getIntValue("send_clean_days")); + ctx.setVariable("is_send_client", event.getIntValue("is_send_client")); + ctx.setVariable("mail_template", event.get("mail_template") == null ? 0 : event.getIntValue("mail_template")); + ctx.setVariable("send_clean_days", event.getIntValue("send_clean_days")); String realOrderIdsStr = event.getString("real_order_ids"); String[] realOrderIds = {}; if (StringUtils.isNotBlank(realOrderIdsStr)) { @@ -857,24 +892,24 @@ public class RiskBusinessServiceImpl implements RiskBusinessService, ManagerTodo } } - switch (event.getIntValue("order_type")){ + switch (event.getIntValue("order_type")) { case 1: case 2: - for(String orderId : realOrderIds){ - JSONObject order = orderMapper.findOrderById(orderId,client.getIntValue("client_id")); - if(order==null){ + for (String orderId : realOrderIds) { + JSONObject order = orderMapper.findOrderById(orderId, client.getIntValue("client_id")); + if (order == null) { throw new BadRequestException("Order: " + orderId + " not exists"); } orders.add(order); } ctx.setVariable("orders", orders); - ctx.setVariable("title","Your merchants needs to submit risk materials"); + ctx.setVariable("title", "Your merchants needs to submit risk materials"); break; case 3: - for(String orderId : realOrderIds){ + for (String orderId : realOrderIds) { JSONObject order = tradeLogService.getOrderDetail(new JSONObject(), clientMoniker, orderId, null); - if(order==null){ - throw new BadRequestException("Order: "+orderId+" not exists"); + if (order == null) { + throw new BadRequestException("Order: " + orderId + " not exists"); } order.put("order_description", StringUtils.defaultString(order.getString("order_description"))); order.put("gateway", getGateWay(order.getIntValue("gateway"))); @@ -883,45 +918,41 @@ public class RiskBusinessServiceImpl implements RiskBusinessService, ManagerTodo order.put("total_amount", order.getString("currency") + " " + order.getString("total_amount")); order.put("display_amount", order.getString("currency") + " " + order.getString("display_amount")); order.put("customer_payment_amount", order.getString("currency") + " " + order.getString("customer_payment_amount")); - order.put("clearing_amount", "AUD "+ order.getString("clearing_amount")); + order.put("clearing_amount", "AUD " + order.getString("clearing_amount")); orders.add(order); } ctx.setVariable("orders", orders); -// List attachList = new ArrayList<>(); -// JSONObject file = new JSONObject(); -// file.put("name", client.getString("short_name")+ "被查单号相关信息.xlsx"); -// file.put("content", Base64.encodeBase64String(generateRiskOrders(event))); -// attachList.add(file); -// ctx.setVariable("files",attachList); case 4: - ctx.setVariable("title","RoyalPay风控调查 — " + client.getString("short_name")); + ctx.setVariable("title", "RoyalPay风控调查 — " + client.getString("short_name")); break; } return ctx; } - private String getRiskUploadKey(String codeKey){ + + private String getRiskUploadKey(String codeKey) { return UPLOAD_MAIL_PREFIX + codeKey; } /** * 获取风控事件上传的材料 + * * @param param * @return */ @Override public JSONObject getRiskMaterial(JSONObject param) { List riskMaterialList = riskMaterialMapper.findAllMaterials(param.getString("risk_id")); - if (riskMaterialList != null && riskMaterialList.size() > 0){ + if (riskMaterialList != null && riskMaterialList.size() > 0) { JSONObject fileNew = riskMaterialList.get(0); List files = riskFileMapper.findAllFiles(fileNew.getString("material_id")); - for(JSONObject file : files){ + for (JSONObject file : files) { int fileType = file.getIntValue("file_type"); - if(!fileNew.containsKey("file" + fileType)){ - List fileList = new ArrayList<>(); - fileList.add(file.getString("file_url")); - fileNew.put("file" + fileType, fileList); - }else{ - List fileList = (List) fileNew.get("file"+fileType); + if (!fileNew.containsKey("file" + fileType)) { + List fileList = new ArrayList<>(); + fileList.add(file.getString("file_url")); + fileNew.put("file" + fileType, fileList); + } else { + List fileList = (List) fileNew.get("file" + fileType); fileList.add(file.getString("file_url")); fileNew.put("file" + fileType, fileList); } @@ -973,7 +1004,7 @@ public class RiskBusinessServiceImpl implements RiskBusinessService, ManagerTodo String[] orderIds = event.getString("order_ids").split(","); JSONObject client = clientMapper.findClientByMonikerAll(event.getString("client_moniker")); Workbook wb = new XSSFWorkbook(); - for(String orderId : orderIds){ + for (String orderId : orderIds) { JSONObject orderDetail = tradeLogService.getOrderDetail(new JSONObject(), event.getString("client_moniker"), orderId, null); Sheet sheet = wb.createSheet(orderId); sheet.setDefaultColumnWidth((short) 40); @@ -993,45 +1024,46 @@ public class RiskBusinessServiceImpl implements RiskBusinessService, ManagerTodo Row row13 = sheet.createRow(13); Row row14 = sheet.createRow(14); Row row15 = sheet.createRow(15); - row0.createCell(0,Cell.CELL_TYPE_STRING).setCellValue("Partner"); - row0.createCell(1,Cell.CELL_TYPE_STRING).setCellValue(orderDetail.getJSONObject("client").getString("short_name")+"("+orderDetail.getJSONObject("client").getString("client_moniker")+")"); - row1.createCell(0,Cell.CELL_TYPE_STRING).setCellValue("Order ID"); - row1.createCell(1,Cell.CELL_TYPE_STRING).setCellValue(orderDetail.getString("order_id")); - row2.createCell(0,Cell.CELL_TYPE_STRING).setCellValue("Platform Transaction ID"); - row2.createCell(1,Cell.CELL_TYPE_STRING).setCellValue(orderDetail.getString("system_transaction_id")); - row3.createCell(0,Cell.CELL_TYPE_STRING).setCellValue("Order Description"); - row3.createCell(1,Cell.CELL_TYPE_STRING).setCellValue(StringUtils.defaultString(orderDetail.getString("order_description"))); - row4.createCell(0,Cell.CELL_TYPE_STRING).setCellValue("Customer ID"); - row4.createCell(1,Cell.CELL_TYPE_STRING).setCellValue(orderDetail.getString("customer_id")); - row5.createCell(0,Cell.CELL_TYPE_STRING).setCellValue("IP"); - row5.createCell(1,Cell.CELL_TYPE_STRING).setCellValue(orderDetail.getString("customer_ip")); - row6.createCell(0,Cell.CELL_TYPE_STRING).setCellValue("Total Amount"); - row6.createCell(1,Cell.CELL_TYPE_STRING).setCellValue(orderDetail.getString("currency")+" "+orderDetail.getString("total_amount")); - row7.createCell(0,Cell.CELL_TYPE_STRING).setCellValue("Input Amount"); - row7.createCell(1,Cell.CELL_TYPE_STRING).setCellValue(orderDetail.getString("currency")+" "+orderDetail.getString("display_amount")); - row8.createCell(0,Cell.CELL_TYPE_STRING).setCellValue("Pay Amount"); - row8.createCell(1,Cell.CELL_TYPE_STRING).setCellValue(orderDetail.getString("currency")+" "+orderDetail.getString("customer_payment_amount")); - row9.createCell(0,Cell.CELL_TYPE_STRING).setCellValue("Exchange Rate"); - row9.createCell(1,Cell.CELL_TYPE_STRING).setCellValue(orderDetail.getString("exchange_rate")); - row10.createCell(0,Cell.CELL_TYPE_STRING).setCellValue("Clearing Amount"); - row10.createCell(1,Cell.CELL_TYPE_STRING).setCellValue("AUD "+ orderDetail.getString("clearing_amount")); - row11.createCell(0,Cell.CELL_TYPE_STRING).setCellValue("Gateway"); - row11.createCell(1,Cell.CELL_TYPE_STRING).setCellValue(getGateWay(orderDetail.getIntValue("gateway"))); - row12.createCell(0,Cell.CELL_TYPE_STRING).setCellValue("Create Time"); - row12.createCell(1,Cell.CELL_TYPE_STRING).setCellValue(orderDetail.getString("create_time")); - row13.createCell(0,Cell.CELL_TYPE_STRING).setCellValue("Status"); - row13.createCell(1,Cell.CELL_TYPE_STRING).setCellValue(getStatus(orderDetail.getIntValue("status"))); - row14.createCell(0,Cell.CELL_TYPE_STRING).setCellValue("Pay Time"); - row14.createCell(1,Cell.CELL_TYPE_STRING).setCellValue(orderDetail.getString("transaction_time")); - row15.createCell(0,Cell.CELL_TYPE_STRING).setCellValue("Order Detail"); - row15.createCell(1,Cell.CELL_TYPE_STRING).setCellValue(StringUtils.defaultString(orderDetail.getString("order_detail"))); + row0.createCell(0, Cell.CELL_TYPE_STRING).setCellValue("Partner"); + row0.createCell(1, Cell.CELL_TYPE_STRING).setCellValue(orderDetail.getJSONObject("client").getString("short_name") + "(" + orderDetail.getJSONObject("client").getString("client_moniker") + ")"); + row1.createCell(0, Cell.CELL_TYPE_STRING).setCellValue("Order ID"); + row1.createCell(1, Cell.CELL_TYPE_STRING).setCellValue(orderDetail.getString("order_id")); + row2.createCell(0, Cell.CELL_TYPE_STRING).setCellValue("Platform Transaction ID"); + row2.createCell(1, Cell.CELL_TYPE_STRING).setCellValue(orderDetail.getString("system_transaction_id")); + row3.createCell(0, Cell.CELL_TYPE_STRING).setCellValue("Order Description"); + row3.createCell(1, Cell.CELL_TYPE_STRING).setCellValue(StringUtils.defaultString(orderDetail.getString("order_description"))); + row4.createCell(0, Cell.CELL_TYPE_STRING).setCellValue("Customer ID"); + row4.createCell(1, Cell.CELL_TYPE_STRING).setCellValue(orderDetail.getString("customer_id")); + row5.createCell(0, Cell.CELL_TYPE_STRING).setCellValue("IP"); + row5.createCell(1, Cell.CELL_TYPE_STRING).setCellValue(orderDetail.getString("customer_ip")); + row6.createCell(0, Cell.CELL_TYPE_STRING).setCellValue("Total Amount"); + row6.createCell(1, Cell.CELL_TYPE_STRING).setCellValue(orderDetail.getString("currency") + " " + orderDetail.getString("total_amount")); + row7.createCell(0, Cell.CELL_TYPE_STRING).setCellValue("Input Amount"); + row7.createCell(1, Cell.CELL_TYPE_STRING).setCellValue(orderDetail.getString("currency") + " " + orderDetail.getString("display_amount")); + row8.createCell(0, Cell.CELL_TYPE_STRING).setCellValue("Pay Amount"); + row8.createCell(1, Cell.CELL_TYPE_STRING).setCellValue(orderDetail.getString("currency") + " " + orderDetail.getString("customer_payment_amount")); + row9.createCell(0, Cell.CELL_TYPE_STRING).setCellValue("Exchange Rate"); + row9.createCell(1, Cell.CELL_TYPE_STRING).setCellValue(orderDetail.getString("exchange_rate")); + row10.createCell(0, Cell.CELL_TYPE_STRING).setCellValue("Clearing Amount"); + row10.createCell(1, Cell.CELL_TYPE_STRING).setCellValue("AUD " + orderDetail.getString("clearing_amount")); + row11.createCell(0, Cell.CELL_TYPE_STRING).setCellValue("Gateway"); + row11.createCell(1, Cell.CELL_TYPE_STRING).setCellValue(getGateWay(orderDetail.getIntValue("gateway"))); + row12.createCell(0, Cell.CELL_TYPE_STRING).setCellValue("Create Time"); + row12.createCell(1, Cell.CELL_TYPE_STRING).setCellValue(orderDetail.getString("create_time")); + row13.createCell(0, Cell.CELL_TYPE_STRING).setCellValue("Status"); + row13.createCell(1, Cell.CELL_TYPE_STRING).setCellValue(getStatus(orderDetail.getIntValue("status"))); + row14.createCell(0, Cell.CELL_TYPE_STRING).setCellValue("Pay Time"); + row14.createCell(1, Cell.CELL_TYPE_STRING).setCellValue(orderDetail.getString("transaction_time")); + row15.createCell(0, Cell.CELL_TYPE_STRING).setCellValue("Order Detail"); + row15.createCell(1, Cell.CELL_TYPE_STRING).setCellValue(StringUtils.defaultString(orderDetail.getString("order_detail"))); } ByteArrayOutputStream bos = new ByteArrayOutputStream(); wb.write(bos); bos.flush(); return bos.toByteArray(); } - private String getGateWay(int gateWay){ + + private String getGateWay(int gateWay) { switch (gateWay) { case 0: return "线下扫码"; @@ -1067,7 +1099,7 @@ public class RiskBusinessServiceImpl implements RiskBusinessService, ManagerTodo return ""; } - private String getStatus(int status){ + private String getStatus(int status) { switch (status) { case 0: return "Creating"; @@ -1091,6 +1123,7 @@ public class RiskBusinessServiceImpl implements RiskBusinessService, ManagerTodo /** * 检查是否有需要的调单事件待处理,由前端弹框提醒 + * * @param manager * @param notices */ @@ -1138,6 +1171,7 @@ public class RiskBusinessServiceImpl implements RiskBusinessService, ManagerTodo /** * 某个商户是否存在调单事件 + * * @param clientId * @return */ @@ -1145,7 +1179,7 @@ public class RiskBusinessServiceImpl implements RiskBusinessService, ManagerTodo public JSONObject getNoticeInfo(int clientId) { JSONObject client = clientMapper.findClient(clientId); - if(client == null){ + if (client == null) { throw new InvalidShortIdException(); } JSONObject params = new JSONObject(); @@ -1168,6 +1202,7 @@ public class RiskBusinessServiceImpl implements RiskBusinessService, ManagerTodo * 调单事件需要上传的材料说明 * 微信调单与内部调单是固定的 * 支付宝调单由风控人员录入 + * * @param riskId * @return */ @@ -1230,6 +1265,9 @@ public class RiskBusinessServiceImpl implements RiskBusinessService, ManagerTodo case 3: materialsRemark = getStudyTemplate(); break; + case 4: + materialsRemark = getChargebackTemplate(); + break; default: break; } @@ -1257,18 +1295,18 @@ public class RiskBusinessServiceImpl implements RiskBusinessService, ManagerTodo @Override public void banRiskEvent(String riskId) { JSONObject params = new JSONObject(); - params.put("risk_id",riskId); - params.put("is_valid",0); + params.put("risk_id", riskId); + params.put("is_valid", 0); riskEventMapper.update(params); } @Override public void commitWaitRiskStatus(String riskId, String codeKey, JSONObject manager) { JSONObject event = riskEventMapper.findById(riskId); - if (event.getIntValue("result_type") != RiskResultTypeEnum.SEND_EMAIL_TO_BD.getResultType() &&event.getIntValue("result_type") != RiskResultTypeEnum.MATERIAL_NOT_PASS.getResultType()) { + if (event.getIntValue("result_type") != RiskResultTypeEnum.SEND_EMAIL_TO_BD.getResultType() && event.getIntValue("result_type") != RiskResultTypeEnum.MATERIAL_NOT_PASS.getResultType()) { throw new BadRequestException("风控调单不存在或资料已补全"); } - if(event.getIntValue("result_type")!= RiskResultTypeEnum.MATERIAL_AUDIT_PASS.getResultType()){ + if (event.getIntValue("result_type") != RiskResultTypeEnum.MATERIAL_AUDIT_PASS.getResultType()) { event.put("result_type", RiskResultTypeEnum.WAIT_FOR_AUDIT.getResultType()); riskEventMapper.update(event); } @@ -1315,29 +1353,50 @@ public class RiskBusinessServiceImpl implements RiskBusinessService, ManagerTodo @Override public void completeOrderAmount() { List riskEventList = getRiskEvents(null); - for(JSONObject riskEvent:riskEventList){ - if(riskEvent.getIntValue("order_type") == 4 || StringUtils.isBlank(riskEvent.getString("real_order_ids"))){ + for (JSONObject riskEvent : riskEventList) { + if (riskEvent.getIntValue("order_type") == 4 || StringUtils.isBlank(riskEvent.getString("real_order_ids"))) { continue; } - String[] order_ids=riskEvent.getString("real_order_ids").split(","); - for(String orderId : order_ids){ + String[] orderIds = riskEvent.getString("real_order_ids").split(","); + for (String orderId : orderIds) { JSONObject transaction = transactionMapper.findByOrderId(orderId); JSONObject riskOrder = new JSONObject(); - riskOrder.put("risk_id",riskEvent.getString("risk_id")); - riskOrder.put("order_id",transaction.getString("order_id")); - riskOrder.put("clearing_amount",transaction.getString("clearing_amount")); + riskOrder.put("risk_id", riskEvent.getString("risk_id")); + riskOrder.put("order_id", transaction.getString("order_id")); + riskOrder.put("clearing_amount", transaction.getString("clearing_amount")); riskOrdersMapper.save(riskOrder); } } } @Override - public void UpdateRiskEventRemark(String riskId, String remark) { + public void updateRiskEventRemark(String riskId, String remark) { JSONObject event = riskEventMapper.findById(riskId); event.put("remark", remark); riskEventMapper.update(event); } + @Override + public void markChargebackStatus(String riskId, JSONObject manager, ChargebackStatus status) { + RiskEvent risk = getRiskEvent(riskId); + if (risk == null) { + throw new NotFoundException("Risk Event not found"); + } + if (risk.getOrderType() != RISK_ORDER_TYPE_CHARGEBACK) { + throw new BadRequestException("Not Chargeback event"); + } + if (status == null || status == ChargebackStatus.PROCESSING) { + throw new BadRequestException("Invalid status"); + } + riskProcessLogService.addRiskProcessLog(riskId, + manager.getString("manager_id"), + manager.getString("display_name"), + RiskResultTypeEnum.ALREADY_HANDLED.getRemark(), + RiskResultTypeEnum.ALREADY_HANDLED.getResultType(), + RiskResultTypeEnum.ALREADY_HANDLED.getResultType()); + cardSecureService.changeChargebackReportStatus(riskId, status); + } + private List getShopTemplate() { return Arrays.asList("1.与调查交易金额对应的购物小票/发票存根照片 要求:照片应清晰,必须显示商户名称、商户地址、购物时间、物品名称、购物金额等;\n" + "Photos of shopping receipts/ invoice stubs Requirement corresponding with the investigated orders Requirement: The photos should be clear and must show Merchant name, Business address, Transaction time, Product information, Quantity purchased, etc;", @@ -1375,4 +1434,19 @@ public class RiskBusinessServiceImpl implements RiskBusinessService, ManagerTodo "Other materials including onboarding materials as task description required;Explanation of business model for your merchant including actual selling-goods or services, per customer transaction, business hours, etc;" ); } + + private List getChargebackTemplate() { + return Arrays.asList("1.A legible copy of the signed authority and/or receipts from the Cardholder. \n" + + "持卡人签名授权书和/或收据的清晰副本。", + "2.Copy of any tax invoice/s and/or signed disclosure of cancellation policy. \n" + + "任何税务发票和/或签署的披露取消政策的副本。", + "3.Any transaction Information relating to the sale of any digital goods purchased online.\n" + + "与在线购买的任何数字商品的销售有关的任何交易信息。", + "4.Description of the goods/services supplied and/or proof of delivery/collection of goods.\n" + + "提供的商品/服务的说明和/或交付/收货的证明。(消费者买了什么,商家卖了什么,消费者收没收到货,如何收到的)", + "5.Copy of Mail Order/telephone order transaction receipt.\n" + + "邮件订单/电话订单交易收据的副本。", + "6.Cardholder identification or any form of communication with the Cardholder, including email correspondence. \n" + + "持卡人身份或与持卡人的任何形式的通信,包括电子邮件通信。"); + } } diff --git a/src/main/java/au/com/royalpay/payment/manage/riskbusiness/web/RiskBusinessController.java b/src/main/java/au/com/royalpay/payment/manage/riskbusiness/web/RiskBusinessController.java index 224e3bfda..9791a534b 100644 --- a/src/main/java/au/com/royalpay/payment/manage/riskbusiness/web/RiskBusinessController.java +++ b/src/main/java/au/com/royalpay/payment/manage/riskbusiness/web/RiskBusinessController.java @@ -1,5 +1,8 @@ package au.com.royalpay.payment.manage.riskbusiness.web; +import au.com.royalpay.payment.core.CardSecureService; +import au.com.royalpay.payment.core.beans.ChargebackStatus; +import au.com.royalpay.payment.core.beans.ChargebackTransaction; import au.com.royalpay.payment.manage.merchants.beans.PartnerQuery; import au.com.royalpay.payment.manage.merchants.core.ClientManager; import au.com.royalpay.payment.manage.permission.manager.ManagerMapping; @@ -14,13 +17,14 @@ import com.alibaba.fastjson.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; +import javax.annotation.Resource; import javax.servlet.http.HttpServletResponse; import java.io.IOException; - import java.util.List; /** * 风控业务 + * * @Author lvjian * @Date 2018/10/10 1:12 */ @@ -33,7 +37,8 @@ public class RiskBusinessController { @Autowired private RiskMaterialService riskMaterialService; - + @Resource + private CardSecureService cardSecureService; @Autowired private ClientManager clientManager; @@ -41,7 +46,6 @@ public class RiskBusinessController { private RiskProcessLogService riskProcessLogService; - @GetMapping(value = "events") public JSONObject getRiskEvents(RiskEventQuery riskEventQuery, @ModelAttribute(CommonConsts.MANAGER_STATUS) JSONObject manager) { JSONObject params = riskEventQuery.toJSON(); @@ -72,13 +76,18 @@ public class RiskBusinessController { @GetMapping(value = "events/{risk_id}/detail") public JSONObject getRiskEventDetailWithoutTradelogs(@PathVariable("risk_id") String riskId, - @ModelAttribute(CommonConsts.MANAGER_STATUS) JSONObject manager) { - JSONObject riskEvent = riskBusinessService.getRiskEventDetail(riskId); - return riskEvent; + @ModelAttribute(CommonConsts.MANAGER_STATUS) JSONObject manager) { + return riskBusinessService.getRiskEventDetail(riskId); + } + + + @GetMapping("/chargeback_orders") + public List searchForChargeback(@RequestParam("channel_order_id") String channelOrderId) { + return cardSecureService.queryOrdersForChargeBack(channelOrderId); } @PostMapping(value = "events") - public void RegisterRiskEvent(@RequestBody JSONObject params, + public void registerRiskEvent(@RequestBody JSONObject params, @ModelAttribute(CommonConsts.MANAGER_STATUS) JSONObject manager) { params.put("fillin_id", manager.getString("manager_id")); params.put("fillin_person", manager.getString("display_name")); @@ -86,8 +95,8 @@ public class RiskBusinessController { } @PutMapping(value = "events") - public void UpdateRiskEvent(@RequestBody JSONObject params,@ModelAttribute(CommonConsts.MANAGER_STATUS) JSONObject manager) { - riskBusinessService.updateRiskEvent(params,manager); + public void updateRiskEvent(@RequestBody JSONObject params, @ModelAttribute(CommonConsts.MANAGER_STATUS) JSONObject manager) { + riskBusinessService.updateRiskEvent(params, manager); } @PutMapping(value = "events/pass") @@ -97,17 +106,17 @@ public class RiskBusinessController { } @GetMapping(value = "/{risk_id}/download/materialsAsZIP") - public void downloadComplianceZip(@PathVariable("risk_id") String riskId, HttpServletResponse response) throws Exception { + public void downloadComplianceZip(@PathVariable("risk_id") String riskId, HttpServletResponse response) { riskBusinessService.downloadAuditMaterialZiP(riskId, response); } - @RequestMapping(value = "/{risk_id}/upload_mail",method = RequestMethod.PUT) + @RequestMapping(value = "/{risk_id}/upload_mail", method = RequestMethod.PUT) public void uploadEmail(@PathVariable String risk_id) throws IOException { riskBusinessService.sendUploadEmail(risk_id); } - @RequestMapping(value = "/{risk_id}/refuse",method = RequestMethod.PUT) + @RequestMapping(value = "/{risk_id}/refuse", method = RequestMethod.PUT) public void refuseEmail(@PathVariable("risk_id") String riskId, @RequestBody JSONObject otherParams) throws IOException { riskBusinessService.sendRefuseEmail(riskId, otherParams.getString("refuse_description")); } @@ -137,7 +146,7 @@ public class RiskBusinessController { //1:禁用渠道;2:禁用商户 riskBusinessService.sendWxMess(params, channel, 1); } - riskBusinessService.updateRiskEvent(params,manager); + riskBusinessService.updateRiskEvent(params, manager); } @PutMapping(value = "/partner/{isValid}") @@ -152,26 +161,31 @@ public class RiskBusinessController { if (temporaryCloseMerchant != 1) { params.put("result_type", RiskResultTypeEnum.ALREADY_HANDLED.getResultType()); } - } - else { + } else { clientManager.revertClient(clientMoniker, manager); params.put("result_type", RiskResultTypeEnum.ALREADY_HANDLED.getResultType()); } - riskBusinessService.updateRiskEvent(params,manager); + riskBusinessService.updateRiskEvent(params, manager); } - @RequestMapping(value = "/{risk_id}/urge",method = RequestMethod.PUT) + @PutMapping("/{risk_id}/urge") public void urgeEmail(@PathVariable String risk_id) throws IOException { riskBusinessService.sendUrgeEmail(risk_id); } - @RequestMapping(value = "/ban/{risk_id}",method = RequestMethod.DELETE) - public void banEvent(@PathVariable String risk_id){ + @PutMapping("/chargebacks/{riskId}/mark_status") + public void markChargebackStatus(@PathVariable String riskId, @ModelAttribute(CommonConsts.MANAGER_STATUS) JSONObject manager, + @RequestBody JSONObject status) { + riskBusinessService.markChargebackStatus(riskId, manager, status.getObject("status", ChargebackStatus.class)); + } + + @DeleteMapping("/ban/{risk_id}") + public void banEvent(@PathVariable String risk_id) { riskBusinessService.banRiskEvent(risk_id); } @PutMapping("/commitWaitRiskStatus/{risk_id}/{codeKey}") - public void commitWaitRiskStatus(@PathVariable String risk_id,@PathVariable String codeKey,@ModelAttribute(CommonConsts.MANAGER_STATUS) JSONObject manager) { + public void commitWaitRiskStatus(@PathVariable String risk_id, @PathVariable String codeKey, @ModelAttribute(CommonConsts.MANAGER_STATUS) JSONObject manager) { riskBusinessService.commitWaitRiskStatus(risk_id, codeKey, manager); } @@ -205,8 +219,8 @@ public class RiskBusinessController { @PutMapping(value = "{risk_id}/remark") @ResponseBody - public void UpdateRiskEventRemark(@PathVariable("risk_id") String riskId, @RequestBody JSONObject remark) { - riskBusinessService.UpdateRiskEventRemark(riskId, remark.getString("remark")); + public void updateRiskEventRemark(@PathVariable("risk_id") String riskId, @RequestBody JSONObject remark) { + riskBusinessService.updateRiskEventRemark(riskId, remark.getString("remark")); } } diff --git a/src/main/ui/static/analysis/risk_business.js b/src/main/ui/static/analysis/risk_business.js index c09ed9973..31c4f86d6 100644 --- a/src/main/ui/static/analysis/risk_business.js +++ b/src/main/ui/static/analysis/risk_business.js @@ -5,38 +5,40 @@ define(['angular', 'jquery', 'uiRouter', './monitoring/analysis-monitoring'], function (angular, $) { 'use strict'; - var mailTemplate = { + let mailTemplate = { "1": "代购、综合商城类", "2": "飞机票、旅行社类", - "3": "教育类、中介类" + "3": "教育类、中介类", + "4": "Chargeback" }; - var orderTypesMap = { + let orderTypesMap = { "1": "微信调单", "2": "支付宝调单", "3": "RoyalPay调单", "4": "警告", - "5": "通用号调单" + "5": "通用号调单", + "6": "卡支付ChargeBack" }; - var orderTypesMapForBD = { + let orderTypesMapForBD = { "1": "微信调单", "2": "支付宝调单", "3": "RoyalPay调单" }; - var royalpayOrderTypesMap = { + let royalpayOrderTypesMap = { "0": "正常调单", "1": "单纯大金额频繁刷单" }; - var warningOrderTypesMap = { + let warningOrderTypesMap = { "0": "单人多次大金额交易", "1": "退款频繁" }; - var resultTypesMap = { + let resultTypesMap = { "0": "未处理", "1": "已发送邮件", "2": "已提交材料,等待审核", @@ -45,7 +47,7 @@ define(['angular', 'jquery', 'uiRouter', './monitoring/analysis-monitoring'], "5": "已处理" }; - var resultTypeSearchMap = { + let resultTypeSearchMap = { "0": "未处理", "1": "资料完善中", "2": "等待风控", @@ -54,7 +56,7 @@ define(['angular', 'jquery', 'uiRouter', './monitoring/analysis-monitoring'], "5": "已处理" }; - var resultTypeSearchMapForBD = { + let resultTypeSearchMapForBD = { "1": "材料待上传", "2": "材料已提交", "3": "风控初审完成,渠道方审核中", @@ -62,14 +64,14 @@ define(['angular', 'jquery', 'uiRouter', './monitoring/analysis-monitoring'], "5": "已处理" }; - var emailStatusMap = { + let emailStatusMap = { "0": "未发送", "1": "已发送", "2": "打回并已发送", "3": "已发送催促邮件" }; - var amountSectionMap = { + let amountSectionMap = { "0-500": "0-500", "500-1000": "500-1000", "1000-1500": "1000-1500", @@ -81,7 +83,7 @@ define(['angular', 'jquery', 'uiRouter', './monitoring/analysis-monitoring'], "4000-4500": "4000-4500" }; - var channelResultArray = [ + let channelResultArray = [ "关闭支付", "恢复支付", "单日10", @@ -95,7 +97,7 @@ define(['angular', 'jquery', 'uiRouter', './monitoring/analysis-monitoring'], "其他" ]; - var app = angular.module('riskBusinessApp', ['ui.router']); + let app = angular.module('riskBusinessApp', ['ui.router']); app.config(['$stateProvider', function ($stateProvider) { $stateProvider.state('analysis_monitoring.risk_business', { url: '/risk_business', @@ -137,7 +139,7 @@ define(['angular', 'jquery', 'uiRouter', './monitoring/analysis-monitoring'], }]); - app.controller('riskBusinessCtrl', ['$scope', '$state', '$http', '$uibModal', '$filter', 'commonDialog', 'industryMap','chartParser', + app.controller('riskBusinessCtrl', ['$scope', '$state', '$http', '$uibModal', '$filter', 'commonDialog', 'industryMap', 'chartParser', function ($scope, $state, $http, $uibModal, $filter, commonDialog, industryMap, chartParser) { $scope.orderTypes = orderTypesMap; $scope.orderTypesForBD = orderTypesMapForBD; @@ -148,26 +150,26 @@ define(['angular', 'jquery', 'uiRouter', './monitoring/analysis-monitoring'], $scope.amountSection = amountSectionMap; $scope.pagination = {}; $scope.params = {}; - var industries = new Array(); + let industries = []; angular.forEach($scope.industries, function (industry) { industries.push(industry.label); }); industries.push('未知行业'); - $scope.$watch('params',function (newVal) { - console.log('params changed--->',newVal) + $scope.$watch('params', function (newVal) { + console.log('params changed--->', newVal) }); console.log('riskBusinessCtrl loaded') // console.log(industries); // 加载风险注册事件 $scope.loadRiskEvents = function (page) { - var params = angular.copy($scope.params); + let params = angular.copy($scope.params); params.page = page || $scope.pagination.page || 1; params.replyEmailDateBegin = $filter('date')(params.replyEmailDateBegin, 'yyyy-MM-dd'); params.replyEmailDateEnd = $filter('date')(params.replyEmailDateEnd, 'yyyy-MM-dd'); params.receiveEmailDateBegin = $filter('date')(params.receiveEmailDateBegin, 'yyyy-MM-dd'); params.receiveEmailDateEnd = $filter('date')(params.receiveEmailDateEnd, 'yyyy-MM-dd'); if (params.section != null) { - var sectionArray = params.section.split('-'); + let sectionArray = params.section.split('-'); params.startAmount = sectionArray[0]; params.endAmount = sectionArray[1]; } @@ -177,16 +179,16 @@ define(['angular', 'jquery', 'uiRouter', './monitoring/analysis-monitoring'], }); $http.get('/risk/business/events/analysis/industry', {params: params}).then(function (resp) { $scope.riskEventsByIndustry = resp.data; - $scope.risk_industry_chart = chartParser.parse(industryAmount(industries),$scope.riskEventsByIndustry); + $scope.risk_industry_chart = chartParser.parse(industryAmount(industries), $scope.riskEventsByIndustry); }); $http.get('/risk/business/events/analysis/amount', {params: params}).then(function (resp) { $scope.riskEventsByAmount = resp.data; - $scope.risk_amount_chart = chartParser.parse(intervalsAmount(),$scope.riskEventsByAmount); + $scope.risk_amount_chart = chartParser.parse(intervalsAmount(), $scope.riskEventsByAmount); }); }; - var industryAmount = function (industries) { + let industryAmount = function (industries) { return { chart: { tooltip: { @@ -205,15 +207,15 @@ define(['angular', 'jquery', 'uiRouter', './monitoring/analysis-monitoring'], name: '风控事件单量', type: 'pie', radius: '80%', center: ['50%', '58%'], - label:{ //饼图图形上的文本标签 - normal:{ - show:true, - position:'outer', //标签的位置 - textStyle : { - fontWeight : 300 , - fontSize : 16 //文字的字体大小 + label: { //饼图图形上的文本标签 + normal: { + show: true, + position: 'outer', //标签的位置 + textStyle: { + fontWeight: 300, + fontSize: 16 //文字的字体大小 }, - formatter:'{d}%' + formatter: '{d}%' } }, itemStyle: { @@ -229,7 +231,7 @@ define(['angular', 'jquery', 'uiRouter', './monitoring/analysis-monitoring'], } }; - var intervalsAmount = function () { + let intervalsAmount = function () { return { chart: { tooltip: { @@ -240,8 +242,8 @@ define(['angular', 'jquery', 'uiRouter', './monitoring/analysis-monitoring'], legend: { orient: 'vertical', left: 'right', - data: [ '0-500','500-1000','1000-1500','1500-2000','2000-2500','2500-3000','3000-3500','3500-4000','4000-4500','4500-5000','5000-5500','5500-6000', - '6000-6500','6500-7000','7000-7500','7500-8000','8000-8500','8500-9000','>9000'] + data: ['0-500', '500-1000', '1000-1500', '1500-2000', '2000-2500', '2500-3000', '3000-3500', '3500-4000', '4000-4500', '4500-5000', '5000-5500', '5500-6000', + '6000-6500', '6500-7000', '7000-7500', '7500-8000', '8000-8500', '8500-9000', '>9000'] } }, series: [{ @@ -249,15 +251,15 @@ define(['angular', 'jquery', 'uiRouter', './monitoring/analysis-monitoring'], name: '风控事件单量', type: 'pie', radius: '80%', center: ['50%', '58%'], - label:{ //饼图图形上的文本标签 - normal:{ - show:true, - position:'outer', //标签的位置 - textStyle : { - fontWeight : 300 , - fontSize : 16 //文字的字体大小 + label: { //饼图图形上的文本标签 + normal: { + show: true, + position: 'outer', //标签的位置 + textStyle: { + fontWeight: 300, + fontSize: 16 //文字的字体大小 }, - formatter:'{d}%' + formatter: '{d}%' } }, itemStyle: { @@ -286,7 +288,7 @@ define(['angular', 'jquery', 'uiRouter', './monitoring/analysis-monitoring'], $scope.mailTemplate = mailTemplate; $scope.resultTypes = resultTypesMap; $scope.channelResults = channelResultArray; - if (riskEvent.data.is_send_client == 1) + if (riskEvent.data.is_send_client === 1) riskEvent.data.is_send_client = true; $scope.riskEvent = riskEvent.data; @@ -299,7 +301,7 @@ define(['angular', 'jquery', 'uiRouter', './monitoring/analysis-monitoring'], }; $scope.checkTemplate = function () { - var url = ""; + let url = ""; switch ($scope.riskEvent.mail_template) { case "1": url = "https://file.royalpay.com.au/open/2019/03/27/1553658222567_BzfAtsEgsBdMQLl3jGOAlfcYmFUL1F.png"; @@ -323,13 +325,13 @@ define(['angular', 'jquery', 'uiRouter', './monitoring/analysis-monitoring'], // 编辑表格的数据保存对象,重新从源数据复制,从而取消保存操作时不会更新视图 $scope.riskEventEdit = angular.copy(riskEvent.data); - //var index = $scope.riskEvent.order_ids.lastIndexOf(","); + //let index = $scope.riskEvent.order_ids.lastIndexOf(","); //$scope.riskEvent.order_ids = $scope.riskEvent.order_ids.substring(0, index) + "," + $scope.riskEvent.order_ids.substring(index + 1); // 获取数据库中对应的渠道字段 - var orderChannel = 'enable_'; - if ($scope.riskEvent.order_type == 1) { + let orderChannel = 'enable_'; + if ($scope.riskEvent.order_type === 1) { orderChannel += 'wechat'; - } else if ($scope.riskEvent.order_type == 2) { + } else if ($scope.riskEvent.order_type === 2) { orderChannel += 'alipay'; } else { orderChannel = null; @@ -342,7 +344,11 @@ define(['angular', 'jquery', 'uiRouter', './monitoring/analysis-monitoring'], }).then(function () { $http.delete('/risk/business/ban/' + $scope.riskEvent.risk_id).then(function () { $state.go('analysis_monitoring.risk_business'); - commonDialog.alert({title: 'Delete', content: 'Risk Event Already Disabled', type: 'error'}); + commonDialog.alert({ + title: 'Delete', + content: 'Risk Event Already Disabled', + type: 'error' + }); }, function (resp) { commonDialog.alert({title: 'Error', content: resp.data.message, type: 'error'}); }) @@ -350,10 +356,10 @@ define(['angular', 'jquery', 'uiRouter', './monitoring/analysis-monitoring'], }; $scope.commitWaitRiskStatus = function () { - var index = $scope.riskEvent.submit_url.lastIndexOf('='); + let index = $scope.riskEvent.submit_url.lastIndexOf('='); if (index < 0) index = $scope.riskEvent.submit_url.lastIndexOf('/'); - var codeKey = $scope.riskEvent.submit_url.substring(index + 1); + let codeKey = $scope.riskEvent.submit_url.substring(index + 1); commonDialog.confirm({ title: '确认已提交资料', content: '确认已收到商户资料,更新风控状态为等待风控审核?' @@ -368,6 +374,18 @@ define(['angular', 'jquery', 'uiRouter', './monitoring/analysis-monitoring'], }) }; + $scope.commitChargebackStatus = function (std) { + commonDialog.confirm({title: '确认操作', content: '当前操作不可逆,并会将风控项标记为办结状态,确认操作?'}).then(function () { + $http.put('/risk/business/chargebacks/' + $scope.riskEvent.risk_id + '/status', {status: std}).then(function () { + $state.reload(); + commonDialog.alert({title: 'Success', content: '修改成功', type: success}) + }, function (res) { + commonDialog.alert({title: 'Error', content: resp.data.message, type: 'error'}) + }) + }) + + } + /** * order_ids在指定位置换行 * @param str @@ -375,15 +393,15 @@ define(['angular', 'jquery', 'uiRouter', './monitoring/analysis-monitoring'], * @returns {*} */ $scope.splitStr = function (str, position) { - if (str == null || str == '') + if (str == null || str === '') return; - var strArr = str.split(","); - var resultStr = ''; - for (var i = 0; i < strArr.length; i++) { + let strArr = str.split(","); + let resultStr = ''; + for (let i = 0; i < strArr.length; i++) { resultStr += strArr[i]; - if (i == (strArr.length - 1)) + if (i === (strArr.length - 1)) break; - if ((i + 1) % position == 0) + if ((i + 1) % position === 0) resultStr += ", "; else resultStr += ","; @@ -405,7 +423,7 @@ define(['angular', 'jquery', 'uiRouter', './monitoring/analysis-monitoring'], // 控制编辑表格的显示 $scope.editFlag = false; - $scope.changeEditFlag = function(editFlag) { + $scope.changeEditFlag = function (editFlag) { $scope.editFlag = !editFlag; // 如果是在编辑状态,需要将日期转换为date类型(前端控件需要) // 如果是在非编辑状态,需要将日期转换为yyyy-MM-dd格式 @@ -418,7 +436,7 @@ define(['angular', 'jquery', 'uiRouter', './monitoring/analysis-monitoring'], } }; - $scope.save = function(form) { + $scope.save = function (form) { if (form.$invalid) { angular.forEach(form, function (item, key) { if (key.indexOf('$') < 0) { @@ -454,10 +472,10 @@ define(['angular', 'jquery', 'uiRouter', './monitoring/analysis-monitoring'], * @param temporaryFlag 是否临时关停 */ $scope.updateChannel = function (orderType, channelFlag, temporaryFlag) { - var channel; - if (orderType == "1") + let channel; + if (orderType === "1") channel = 'wechat'; - else if (orderType == "2") + else if (orderType === "2") channel = 'alipay'; $scope.riskEvent.temporary_close_channel = temporaryFlag; commonDialog.confirm({ @@ -477,7 +495,7 @@ define(['angular', 'jquery', 'uiRouter', './monitoring/analysis-monitoring'], }; // 关停商户 - $scope.updateClient = function(isValid, temporaryFlag) { + $scope.updateClient = function (isValid, temporaryFlag) { $scope.riskEvent.temporary_close_merchant = temporaryFlag; commonDialog.confirm({ title: 'Warning', @@ -497,8 +515,8 @@ define(['angular', 'jquery', 'uiRouter', './monitoring/analysis-monitoring'], title: 'Warning', content: 'Please confirm sending mail.' }).then(function () { - var url = '/risk/business/' + $scope.riskEvent.risk_id + '/upload_mail'; - if ($scope.riskEvent.result_type == 1) + let url = '/risk/business/' + $scope.riskEvent.risk_id + '/upload_mail'; + if ($scope.riskEvent.result_type === 1) url = '/risk/business/' + $scope.riskEvent.risk_id + '/urge'; $http.put(url).then(function () { $state.reload(); @@ -514,14 +532,14 @@ define(['angular', 'jquery', 'uiRouter', './monitoring/analysis-monitoring'], }; // 以下为BD上传材料相关 - $scope.material={}; - $scope.uploadFile = function(files, index) { + $scope.material = {}; + $scope.uploadFile = function (files, index) { if (files && files.length) { - var urls = new Array(); - var value = 0; + let urls = []; + let value = 0; $scope.allMaterialInfo.material[index].fileProgressValue = 0; - for (var i = 0; i < files.length; i++) { - var file = files[i]; + for (let i = 0; i < files.length; i++) { + let file = files[i]; Upload.upload({ url: '/attachment/riskFiles', data: {file: file} @@ -531,8 +549,8 @@ define(['angular', 'jquery', 'uiRouter', './monitoring/analysis-monitoring'], delete $scope.allMaterialInfo.material[index].fileProgressValue; alert('Upload Failed'); }, function (evt) { - value += parseInt(100 * evt.loaded / evt.total ); - $scope.allMaterialInfo.material[index].fileProgressValue = value/(files.length*2); + value += parseInt(100 * evt.loaded / evt.total); + $scope.allMaterialInfo.material[index].fileProgressValue = value / (files.length * 2); }) } $scope.allMaterialInfo.material[index].uploadFile = urls; @@ -540,11 +558,11 @@ define(['angular', 'jquery', 'uiRouter', './monitoring/analysis-monitoring'], }; $scope.submit = function (form) { - var codeKey = $scope.riskEvent.submit_url.substring($scope.riskEvent.submit_url.lastIndexOf('=') + 1) || $scope.riskEvent.submit_url.substring($scope.riskEvent.submit_url.lastIndexOf('/') + 1); - $scope.material.update_time=$filter('date')(new Date(), 'yyyy-MM-dd HH:mm:ss'); + let codeKey = $scope.riskEvent.submit_url.substring($scope.riskEvent.submit_url.lastIndexOf('=') + 1) || $scope.riskEvent.submit_url.substring($scope.riskEvent.submit_url.lastIndexOf('/') + 1); + $scope.material.update_time = $filter('date')(new Date(), 'yyyy-MM-dd HH:mm:ss'); $scope.material.risk_id = $scope.riskEvent.risk_id; - for (var i = 0; i < $scope.allMaterialInfo.material.length; i++) { - var key = 'file' + (i + 1) + "_url"; + for (let i = 0; i < $scope.allMaterialInfo.material.length; i++) { + let key = 'file' + (i + 1) + "_url"; $scope.material[key] = $scope.allMaterialInfo.material[i].uploadFile; } $scope.material.description = $scope.allMaterialInfo.description; @@ -565,12 +583,12 @@ define(['angular', 'jquery', 'uiRouter', './monitoring/analysis-monitoring'], }; // 加载提交材料 - $scope.loadRiskMaterial = function() { + $scope.loadRiskMaterial = function () { // $http.get('/risk/business/' + $scope.riskEvent.risk_id + '/material').then(function(resp) { // $scope.material = resp.data; // }); - $http.get('/risk/business/' + $scope.riskEvent.risk_id + '/all_material_info').then(function(resp) { + $http.get('/risk/business/' + $scope.riskEvent.risk_id + '/all_material_info').then(function (resp) { $scope.allMaterialInfo = resp.data; if ($scope.uploadShowFlag) { $scope.allMaterialInfo.description = ''; @@ -579,7 +597,7 @@ define(['angular', 'jquery', 'uiRouter', './monitoring/analysis-monitoring'], }; // BD是否可上传 - $scope.uploadShowFlag = ($scope.riskEvent.result_type == 1 || $scope.riskEvent.result_type == 3 || $scope.riskEvent.result_type == 4) ? true : false; + $scope.uploadShowFlag = ($scope.riskEvent.result_type === 1 || $scope.riskEvent.result_type === 3 || $scope.riskEvent.result_type === 4); //if (!$scope.uploadShowFlag) $scope.loadRiskMaterial(); } @@ -595,7 +613,7 @@ define(['angular', 'jquery', 'uiRouter', './monitoring/analysis-monitoring'], // 加载提交材料 // $scope.fileObject = {}; - $scope.loadRiskMaterial = function() { + $scope.loadRiskMaterial = function () { // $http.get('/risk/business/' + $scope.riskEvent.risk_id + '/material').then(function(resp) { // $scope.riskMaterial = resp.data; // $scope.file1 = resp.data.file1; @@ -605,31 +623,31 @@ define(['angular', 'jquery', 'uiRouter', './monitoring/analysis-monitoring'], // $scope.file5 = resp.data.file5; // $scope.file6 = resp.data.file6; // - // // for (var i = 1; i <= 10; i++) { - // // var key = "file" + i; + // // for (let i = 1; i <= 10; i++) { + // // let key = "file" + i; // // if (riskMaterial[key + '_url'] != null) // // $scope.fileObject[key] = riskMaterial[key + '_url']; // // } // // $scope.fileLength = Object.keys($scope.fileObject).length; // }) - $http.get('/risk/business/' + $scope.riskEvent.risk_id + '/all_material_info').then(function(resp) { + $http.get('/risk/business/' + $scope.riskEvent.risk_id + '/all_material_info').then(function (resp) { $scope.riskMaterial = resp.data; }); }; $scope.loadRiskMaterial(); //审核通过也要可以传图片 - $scope.uploadShowFlag = ($scope.riskEvent.result_type == 1 || $scope.riskEvent.result_type == 3 || $scope.riskEvent.result_type == 4) ? true : false; + $scope.uploadShowFlag = ($scope.riskEvent.result_type === 1 || $scope.riskEvent.result_type === 3 || $scope.riskEvent.result_type === 4); // 材料上传 - $scope.uploadFile = function(files, index) { + $scope.uploadFile = function (files, index) { if (files && files.length) { - var urls = new Array(); - var value = 0; + let urls = []; + let value = 0; $scope.riskMaterial.material[index].fileProgressValue = 0; - for (var i = 0; i < files.length; i++) { - var file = files[i]; + for (let i = 0; i < files.length; i++) { + let file = files[i]; Upload.upload({ url: '/attachment/riskFiles', data: {file: file} @@ -640,8 +658,8 @@ define(['angular', 'jquery', 'uiRouter', './monitoring/analysis-monitoring'], delete $scope.riskMaterial.material[index].fileProgressValue; alert('Upload Failed'); }, function (evt) { - value += parseInt(100 * evt.loaded / evt.total ); - $scope.riskMaterial.material[index].fileProgressValue = value/(files.length*2); + value += parseInt(100 * evt.loaded / evt.total); + $scope.riskMaterial.material[index].fileProgressValue = value / (files.length * 2); }) } $scope.riskMaterial.material[index].file = urls; @@ -649,14 +667,14 @@ define(['angular', 'jquery', 'uiRouter', './monitoring/analysis-monitoring'], }; $scope.submit = function (form) { - var index = $scope.riskEvent.submit_url.lastIndexOf('='); + let index = $scope.riskEvent.submit_url.lastIndexOf('='); if (index < 0) index = $scope.riskEvent.submit_url.lastIndexOf('/'); - var codeKey = $scope.riskEvent.submit_url.substring(index + 1); - $scope.material.update_time=$filter('date')(new Date(), 'yyyy-MM-dd HH:mm:ss'); + let codeKey = $scope.riskEvent.submit_url.substring(index + 1); + $scope.material.update_time = $filter('date')(new Date(), 'yyyy-MM-dd HH:mm:ss'); $scope.material.risk_id = $scope.riskEvent.risk_id; - for (var i = 0; i < $scope.riskMaterial.material.length; i++) { - var key = 'file' + (i + 1) + "_url"; + for (let i = 0; i < $scope.riskMaterial.material.length; i++) { + let key = 'file' + (i + 1) + "_url"; $scope.material[key] = $scope.riskMaterial.material[i].file; } $scope.material.description = $scope.riskMaterial.description; @@ -677,11 +695,11 @@ define(['angular', 'jquery', 'uiRouter', './monitoring/analysis-monitoring'], }; // 材料审核 - $scope.auditMaterial = function(auditType) { + $scope.auditMaterial = function (auditType) { - var url = '/risk/business/events/pass'; - var warningMessageHTML = '是否确定通过该材料?'; - if (auditType == 3) { + let url = '/risk/business/events/pass'; + let warningMessageHTML = '是否确定通过该材料?'; + if (auditType === 3) { commonDialog.confirm({ title: 'Warning', contentHtml: $sce.trustAsHtml(warningMessageHTML) @@ -698,8 +716,7 @@ define(['angular', 'jquery', 'uiRouter', './monitoring/analysis-monitoring'], }); }); }); - } - else if (auditType == 4) { + } else if (auditType === 4) { url = '/risk/business/' + $scope.riskEvent.risk_id + '/refuse'; //warningMessageHTML = '是否确定拒绝该材料?' commonDialog.inputText({title: 'Input Refuse Description', size: 'lg'}).then(function (text) { @@ -732,8 +749,21 @@ define(['angular', 'jquery', 'uiRouter', './monitoring/analysis-monitoring'], $scope.materials = [{key: 0, value: ""}]; $scope.canMinus = false; $scope.riskEvent = {}; + $scope.searchForChargeback = function () { + $scope.riskEvent.order_ids = null; + let channelOrderId = $scope.riskEvent.channel_order_id; + $http.get('/risk/business/chargeback_orders', {channel_order_id: channelOrderId}).then(function (res) { + $scope.channel_orders = res.data; + }, function (res) { + commonDialog.alert({type: 'error', title: 'Error', content: res.data.message}) + }); + }; + $scope.chooseOrderForChargeback = function (chargebackOrder) { + $scope.riskEvent.order_ids = chargebackOrder.channel_order_id; + $scope.riskEvent.client_moniker = chargebackOrder.client_moniker; + } $scope.checkTemplate = function () { - var url = ""; + let url = ""; switch ($scope.riskEvent.mail_template) { case "1": url = "https://file.royalpay.com.au/open/2019/03/27/1553658222567_BzfAtsEgsBdMQLl3jGOAlfcYmFUL1F.png"; @@ -757,35 +787,35 @@ define(['angular', 'jquery', 'uiRouter', './monitoring/analysis-monitoring'], $scope.canMinus = true; }; - $scope.decrease = function($index) { + $scope.decrease = function ($index) { // 如果input大于1,删除 if ($scope.materials.length > 1) { $scope.materials.splice($index, 1); } // 如果回复数为1,不允许删除 - if ($scope.materials.length == 1) { + if ($scope.materials.length === 1) { $scope.canMinus = false; } }; - var array=new Array(); - var validIndex = 0; - $scope.combineMaterials = function() { - for (var i = 0; i < $scope.materials.length; i++) { - var value = $scope.materials[i].value; - if (value == '') + let array = []; + let validIndex = 0; + $scope.combineMaterials = function () { + for (let i = 0; i < $scope.materials.length; i++) { + let value = $scope.materials[i].value; + if (value === '') continue; - var cr = {}; + let cr = {}; cr['question' + (validIndex + 1)] = $scope.materials[i].value; array[validIndex] = cr; validIndex++; } - if (array.length == 0) + if (array.length === 0) return null; return JSON.stringify(array); }; $scope.is_send_client = false; - $scope.changeIsSendClient = function(flag) { + $scope.changeIsSendClient = function (flag) { $scope.is_send_client = flag $scope.send_clean_days = flag }; @@ -803,7 +833,7 @@ define(['angular', 'jquery', 'uiRouter', './monitoring/analysis-monitoring'], if ($scope.riskEvent.receive_email_date == null) $scope.riskEvent.receive_email_date = new Date(); // 默认设置邮件回复截止日期为收到邮件的七天后,如果是内部调单,设置三天后 - var replyDeadline = angular.copy($scope.riskEvent.receive_email_date); + let replyDeadline = angular.copy($scope.riskEvent.receive_email_date); if ($scope.riskEvent.order_type > 2) replyDeadline.setDate(replyDeadline.getDate() + 3); else @@ -818,8 +848,8 @@ define(['angular', 'jquery', 'uiRouter', './monitoring/analysis-monitoring'], $scope.riskEvent.send_clean_days = $scope.send_clean_days; - var saveRiskBtn = document.getElementById('save-risk-btn'); - var saveRiskBtnInnerHtmlBak = saveRiskBtn.innerHTML; + let saveRiskBtn = document.getElementById('save-risk-btn'); + let saveRiskBtnInnerHtmlBak = saveRiskBtn.innerHTML; saveRiskBtn.disabled = true; saveRiskBtn.innerHTML = " Processing"; $http.post('/risk/business/events', $scope.riskEvent).then(function (resp) { @@ -830,7 +860,7 @@ define(['angular', 'jquery', 'uiRouter', './monitoring/analysis-monitoring'], content: 'Register new riskEvent successfully', type: 'success' }); - $state.go('^',{}, {reload: true}); + $state.go('^', {}, {reload: true}); }, function (resp) { saveRiskBtn.innerHTML = saveRiskBtnInnerHtmlBak; saveRiskBtn.disabled = false; @@ -842,16 +872,15 @@ define(['angular', 'jquery', 'uiRouter', './monitoring/analysis-monitoring'], }); }; $scope.partnerParam = {}; - $scope.loadParnters = function() { + $scope.loadParnters = function () { $scope.partnerParam.sub_merchant_id = $scope.riskEvent.sub_merchant_id; $http.get('/risk/business/partners', {params: $scope.partnerParam}).then(function (resp) { $scope.partners = resp.data; if ($scope.partners != null && $scope.partners.length > 0) { // 由于通用号调单可能无法提供商户client_moniker,所以后台无法查询到订单 - if ($scope.partners.length == 1 || $scope.riskEvent.order_type != 5) + if ($scope.partners.length === 1 || $scope.riskEvent.order_type !== 5) $scope.riskEvent.client_moniker = $scope.partners[0].client_moniker; - } - else { + } else { commonDialog.confirm({ title: 'Warning', content: '该微信子商户号下暂时没有商户或者商户被禁用,是否继续?' @@ -863,7 +892,7 @@ define(['angular', 'jquery', 'uiRouter', './monitoring/analysis-monitoring'], $scope.riskEvent.sub_merchant_id = ''; }); } - if ($scope.partners != null && $scope.partners.length > 1 && $scope.riskEvent.order_type != 5) + if ($scope.partners != null && $scope.partners.length > 1 && $scope.riskEvent.order_type !== 5) commonDialog.confirm({ title: 'Warning', content: '该微信子商户号下有多个商户,是否将调单类型改为通用号调单?' @@ -877,8 +906,8 @@ define(['angular', 'jquery', 'uiRouter', './monitoring/analysis-monitoring'], ]); // 调单类型过滤器 - app.filter('orderType', function() { - return function(type) { + app.filter('orderType', function () { + return function (type) { return orderTypesMap[type]; } }); @@ -895,22 +924,22 @@ define(['angular', 'jquery', 'uiRouter', './monitoring/analysis-monitoring'], } }); - app.filter('warningOrderType', function() { - return function(type) { + app.filter('warningOrderType', function () { + return function (type) { return warningOrderTypesMap[type]; } }); // 处理结果过滤器 - app.filter('resultType', function() { - return function(type, resultTypesMap) { + app.filter('resultType', function () { + return function (type, resultTypesMap) { return resultTypesMap[type]; } }); // 邮件发送状态过滤器 - app.filter('emailStatus', function() { - return function(status) { + app.filter('emailStatus', function () { + return function (status) { return emailStatusMap[status]; } }); diff --git a/src/main/ui/static/analysis/templates/dialog_holiday_config.html b/src/main/ui/static/analysis/templates/dialog_holiday_config.html index baae0d44a..991e03d13 100644 --- a/src/main/ui/static/analysis/templates/dialog_holiday_config.html +++ b/src/main/ui/static/analysis/templates/dialog_holiday_config.html @@ -25,6 +25,9 @@
  • AU NSW
  • +
  • AU QLD +
  • diff --git a/src/main/ui/static/analysis/templates/new_riskEvent.html b/src/main/ui/static/analysis/templates/new_riskEvent.html index 629c2ed5c..7ac541a95 100644 --- a/src/main/ui/static/analysis/templates/new_riskEvent.html +++ b/src/main/ui/static/analysis/templates/new_riskEvent.html @@ -1,4 +1,3 @@ -

    New RiskEvent

    @@ -56,7 +55,8 @@ -
    +
    -
    +
    @@ -134,7 +135,7 @@
    @@ -187,11 +188,59 @@
    +
    + +
    +
    + +
    + +
    +
    +
    +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + + +
    MerchantOrder IDChannelChannel Order IDAmountTransaction TimeOperation
    + +
    +
    +
    @@ -223,21 +272,23 @@
    - -
    - -
    -
    - - -
    + +
    + +
    +
    + + +
    重新启用渠道 + ng-click="updateChannel(riskEvent.order_type, true, false)"> + 重新启用渠道
    @@ -262,6 +263,18 @@ ng-if="'10000000000'|withRole">重新启用商户
    +
    + +
    +
    + +
    From 78aa62f892f62446810f720c22bee93604a0e4cd Mon Sep 17 00:00:00 2001 From: yixian Date: Wed, 5 Aug 2020 12:11:52 +1000 Subject: [PATCH 2/3] risk control: chargeback --- .../core/impls/OrgAnalysisServiceImp.java | 34 ++++++++----------- 1 file changed, 15 insertions(+), 19 deletions(-) diff --git a/src/main/java/au/com/royalpay/payment/manage/analysis/core/impls/OrgAnalysisServiceImp.java b/src/main/java/au/com/royalpay/payment/manage/analysis/core/impls/OrgAnalysisServiceImp.java index 39c91dcae..20f6985ed 100644 --- a/src/main/java/au/com/royalpay/payment/manage/analysis/core/impls/OrgAnalysisServiceImp.java +++ b/src/main/java/au/com/royalpay/payment/manage/analysis/core/impls/OrgAnalysisServiceImp.java @@ -1,10 +1,10 @@ package au.com.royalpay.payment.manage.analysis.core.impls; import au.com.royalpay.payment.manage.analysis.core.OrgAnalysisService; -import au.com.royalpay.payment.manage.analysis.mappers.CustomerAndOrdersStatisticsMapper; import au.com.royalpay.payment.manage.analysis.mappers.TransactionAnalysisMapper; import au.com.royalpay.payment.manage.mappers.log.StatisticsBDSalesReportMapper; import au.com.royalpay.payment.manage.organizations.core.OrgManager; +import au.com.royalpay.payment.tools.utils.JsonHelper; import com.alibaba.fastjson.JSONObject; import org.apache.commons.lang3.time.DateUtils; import org.springframework.stereotype.Service; @@ -30,30 +30,26 @@ public class OrgAnalysisServiceImp implements OrgAnalysisService { @Resource private OrgManager orgManager; - @Resource - private CustomerAndOrdersStatisticsMapper customerAndOrdersStatisticsMapper; @Override - public List getSalesAnalysis(JSONObject params,JSONObject manager) { - orgManager.checkOrgIds(manager,params); - params.put("org_type",0); - List OrgTransaction = statisticsBDSalesReportMapper.getPartnerAmountList(params); - List newOrgTransaction = new ArrayList<>(); - OrgTransaction.forEach(item->{ - newOrgTransaction.add(new JSONObject(){{ - put("org_id",item.getString("org_id")); - put("org_name",item.getString("org_name")); - put("amount",item.getString("clearing_amount")); - }} - ); - }); + public List getSalesAnalysis(JSONObject params, JSONObject manager) { + orgManager.checkOrgIds(manager, params); + params.put("org_type", 0); + List orgTransactions = statisticsBDSalesReportMapper.getPartnerAmountList(params); + List newOrgTransaction = new ArrayList<>(); + orgTransactions.forEach(item -> newOrgTransaction.add(JsonHelper.newJson(json -> { + json.put("org_id", item.getString("org_id")); + json.put("org_name", item.getString("org_name")); + json.put("amount", item.getString("clearing_amount")); + }) + )); //判断查询的最后一天是否是当日,若是当日,将当日数据添加至结果集内 SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd"); if (sd.format(params.getDate("end")).equals(sd.format(DateUtils.addDays(new Date(), 1)))) { params.put("begin", DateUtils.addDays(params.getDate("end"), -1)); - params.put("end",params.getDate("end")); + params.put("end", params.getDate("end")); List todayOrgTransaction = transactionAnalysisMapper.getOneDayOrgMerchantSaleList(params); - if(todayOrgTransaction.size()!=0){ + if (!todayOrgTransaction.isEmpty()) { for (JSONObject todayOrgTransactionItem : todayOrgTransaction) { boolean flag = false; for (JSONObject orgTransaction : newOrgTransaction) { @@ -64,7 +60,7 @@ public class OrgAnalysisServiceImp implements OrgAnalysisService { } } if (!flag) { - todayOrgTransactionItem.put("amount",todayOrgTransactionItem.getString("clearing_amount")); + todayOrgTransactionItem.put("amount", todayOrgTransactionItem.getString("clearing_amount")); newOrgTransaction.add(todayOrgTransactionItem); } } From 639b861495c0c24b71e194c9ee01a0abe3009931 Mon Sep 17 00:00:00 2001 From: yixian Date: Wed, 5 Aug 2020 12:50:52 +1000 Subject: [PATCH 3/3] optimise code --- .../core/impls/ActChairtyServiceImp.java | 19 +- .../OneDollarDayActivitySupportImpl.java | 18 +- .../web/OneDollarDayAnalysisController.java | 8 +- .../ActMonDelaySettleManagerServiceImpl.java | 4 +- .../core/impls/AmountAnalysisServiceImp.java | 6 +- .../core/impls/BDAnalysisServiceImpl.java | 7 +- .../impls/CustomersAnalysisServiceImp.java | 8 +- .../analysis/core/impls/DailyReportImp.java | 102 +++---- .../core/impls/DashboardServiceImpl.java | 25 +- .../impls/EstimateAnalysisServiceImpl.java | 16 +- .../impls/PartnerCardDashboardServiceImp.java | 6 +- .../PlatformClearAnalysisServiceImpl.java | 4 +- .../analysis/core/impls/WeekReporterImpl.java | 8 +- .../manage/appclient/beans/AppQueryBean.java | 9 +- .../core/impls/RetailAppServiceImp.java | 26 +- .../core/impls/RetailRSvcServiceImpl.java | 62 ++--- .../appclient/web/RetailClientController.java | 20 +- .../impls/SimpleClientApplyServiceImpl.java | 12 +- .../web/SimpleClientApplyController.java | 3 +- .../impls/CustomerImpressionServiceImpl.java | 8 +- .../apps/core/impls/SSOSupportImpl.java | 5 +- .../CtripAfterPaymentFinishListener.java | 9 +- .../CtripRefundFinishedEventListener.java | 9 +- .../core/impls/BDPrizeServiceImpl.java | 13 +- .../impls/BDPrizeCalculatorDefaultImpl.java | 32 +-- .../bill/core/impl/BillServiceImpl.java | 23 +- .../core/impls/CashierServiceImp.java | 4 +- .../impls/CityPartnerPrizeServiceImpl.java | 10 +- .../core/impl/ClientComplianceApplyImpl.java | 4 +- .../core/impls/CouponValidateServiceImpl.java | 12 +- .../core/impls/EncourageUseProcessor.java | 14 +- .../dev/core/impl/AliforexcelServiceImpl.java | 2 +- .../PaymentAmountCheatMonitor.java | 5 +- .../manage/dev/web/TestController.java | 12 +- .../manage/fund/beans/XPlanFundConfig.java | 5 +- .../core/impls/FundsConfigServiceImpl.java | 4 +- .../impls/XPlanFundConfigServiceImpl.java | 7 +- .../manage/gateway/advice/Gtw2SignAspect.java | 5 +- .../core/impls/GatewayMerchantApplyImpl.java | 2 +- .../manage/kyc/core/impls/KycServiceImpl.java | 6 +- .../clearing/core/impl/CleanServiceImpl.java | 36 +-- .../impl/MerchantIdManageServiceImpl.java | 6 +- .../core/impls/ClientManagerImpl.java | 261 +++++++----------- .../manage/notice/beans/NoticeInfo.java | 8 +- .../notice/core/impls/MailServiceImp.java | 2 +- .../notice/core/impls/NoticeManageImpl.java | 9 +- .../notice/core/impls/NoticePartnerImpl.java | 15 +- .../manage/openim/core/OpenimClient.java | 13 +- .../core/impl/CustomerServiceServiceImpl.java | 14 +- .../core/impls/OrgManagerImpl.java | 16 +- .../CtripCouponOnlyLogProcessor.java | 13 +- .../CtripCouponProvideProcessor.java | 9 +- .../core/impls/ActRedPackServiceImpl.java | 7 +- .../core/impls/PartnerLMServiceImp.java | 38 +-- .../core/impls/RedpackServiceImpl.java | 37 +-- .../core/impl/RiskBusinessServiceImpl.java | 12 +- .../core/impls/SignInAccountServiceImpl.java | 16 +- .../core/impls/SignInStatusManagerImpl.java | 21 +- .../system/core/impl/MailGunServiceImpl.java | 17 +- .../manage/tradelog/beans/TradeLogQuery.java | 2 +- .../core/impls/ReportConfigServiceImp.java | 4 +- .../core/impls/TradeLogServiceImpl.java | 20 +- .../refund/impls/RefundServiceImpl.java | 2 +- .../RefundSendTemplateMessageSender.java | 6 +- .../manage/process/alipay/FixAlipayData.java | 6 +- 65 files changed, 514 insertions(+), 630 deletions(-) diff --git a/src/main/java/au/com/royalpay/payment/manage/actchairty/core/impls/ActChairtyServiceImp.java b/src/main/java/au/com/royalpay/payment/manage/actchairty/core/impls/ActChairtyServiceImp.java index 494d041c8..5bc61f09a 100644 --- a/src/main/java/au/com/royalpay/payment/manage/actchairty/core/impls/ActChairtyServiceImp.java +++ b/src/main/java/au/com/royalpay/payment/manage/actchairty/core/impls/ActChairtyServiceImp.java @@ -17,8 +17,7 @@ import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.math.BigDecimal; -import java.text.DateFormat; -import java.text.SimpleDateFormat; +import java.math.RoundingMode; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; @@ -57,7 +56,7 @@ public class ActChairtyServiceImp implements ActChairtyService { client.put("client_moniker", client.getString("client_moniker")); client.put("active_time", DateFormatUtils.format(client.getDate("active_time"), "yyyy/MM/dd")); BigDecimal bg = new BigDecimal(client.getIntValue("count_ordernum") * 0.01); - double f1 = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); + double f1 = bg.setScale(2, RoundingMode.HALF_UP).doubleValue(); client.put("chairty_num", f1); } return PageListUtils.buildPageListResult(clients); @@ -98,12 +97,12 @@ public class ActChairtyServiceImp implements ActChairtyService { } BigDecimal chairty = new BigDecimal(0.01); BigDecimal chairty_amount = count_ordernum.multiply(chairty); - BigDecimal f1 = sum_ordernum.setScale(2, BigDecimal.ROUND_HALF_UP); - BigDecimal f2 = chairty_amount.setScale(2, BigDecimal.ROUND_HALF_UP); + BigDecimal f1 = sum_ordernum.setScale(2, RoundingMode.HALF_UP); + BigDecimal f2 = chairty_amount.setScale(2, RoundingMode.HALF_UP); weekDay.put("weekstart", weekStart.get(i)); weekDay.put("count_ordernum", count_ordernum); weekDay.put("sum_ordernum", f1); - weekDay.put("chairty_amount",f2 ); + weekDay.put("chairty_amount", f2); result.add(weekDay); } catch (Exception e) { logger.info("Act_Chairty Error:",e); @@ -123,15 +122,15 @@ public class ActChairtyServiceImp implements ActChairtyService { @Override public JSONObject gettotal() { List gettotalnum = actChairtyMapper.chairtyClientNum(); - BigDecimal amount= new BigDecimal(0) ; - double chairty=0.00; + BigDecimal amount = new BigDecimal(0); + double chairty = 0.00; for (JSONObject gettotals : gettotalnum) { amount = amount.add(gettotals.getBigDecimal("sum_ordernum")); chairty += gettotals.getIntValue("count_ordernum") * 0.01; } BigDecimal bg = new BigDecimal(chairty); - double f1 = amount.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); - double f2 = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); + double f1 = amount.setScale(2, RoundingMode.HALF_UP).doubleValue(); + double f2 = bg.setScale(2, RoundingMode.HALF_UP).doubleValue(); JSONObject gettotal = new JSONObject(); gettotal.put("amount", f1); gettotal.put("chairty", f2); diff --git a/src/main/java/au/com/royalpay/payment/manage/activities/diet/core/impls/OneDollarDayActivitySupportImpl.java b/src/main/java/au/com/royalpay/payment/manage/activities/diet/core/impls/OneDollarDayActivitySupportImpl.java index 455897b09..638bb9133 100644 --- a/src/main/java/au/com/royalpay/payment/manage/activities/diet/core/impls/OneDollarDayActivitySupportImpl.java +++ b/src/main/java/au/com/royalpay/payment/manage/activities/diet/core/impls/OneDollarDayActivitySupportImpl.java @@ -20,26 +20,24 @@ import au.com.royalpay.payment.tools.connections.attachment.core.AttachmentClien import au.com.royalpay.payment.tools.env.SysConfigManager; import au.com.royalpay.payment.tools.exceptions.NotFoundException; import au.com.royalpay.payment.tools.utils.PageListUtils; - import com.alibaba.fastjson.JSONObject; import com.github.miemiedev.mybatis.paginator.domain.Order; import com.github.miemiedev.mybatis.paginator.domain.PageBounds; import com.github.miemiedev.mybatis.paginator.domain.PageList; - import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.time.DateUtils; import org.joda.time.DateTime; import org.springframework.stereotype.Service; +import javax.annotation.Resource; import java.math.BigDecimal; +import java.math.RoundingMode; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.TimeZone; -import javax.annotation.Resource; - /** * Created by yixian on 2017-03-21. */ @@ -86,20 +84,20 @@ public class OneDollarDayActivitySupportImpl implements OneDollarDayActivity, Pa String currency = paymentInfo.getCurrency(); dietOrderInfo.put("order_currency", currency); BigDecimal totalFee = paymentInfo.getTotalFee(); - BigDecimal payAmount = totalFee.divide(CommonConsts.HUNDRED, 2, BigDecimal.ROUND_DOWN); - BigDecimal payLocalCurrency = paymentInfo.getDisplayAmount().divide(CommonConsts.HUNDRED, 2, BigDecimal.ROUND_DOWN); + BigDecimal payAmount = totalFee.divide(CommonConsts.HUNDRED, 2, RoundingMode.DOWN); + BigDecimal payLocalCurrency = paymentInfo.getDisplayAmount().divide(CommonConsts.HUNDRED, 2, RoundingMode.DOWN); if (!"AUD".equals(currency)) { BigDecimal exchange = mpPaymentApi.queryExchangeRateDecimal(clientId); - payLocalCurrency = payLocalCurrency.divide(exchange, 2, BigDecimal.ROUND_DOWN); + payLocalCurrency = payLocalCurrency.divide(exchange, 2, RoundingMode.DOWN); } if (payLocalCurrency.compareTo(MIN_PAY) <= 0) { return; } BigDecimal discount; - dietOrderInfo.put("order_amount", totalFee.divide(CommonConsts.HUNDRED, 2, BigDecimal.ROUND_DOWN)); + dietOrderInfo.put("order_amount", totalFee.divide(CommonConsts.HUNDRED, 2, RoundingMode.DOWN)); if (!"AUD".equals(currency)) { BigDecimal exchange = mpPaymentApi.queryExchangeRateDecimal(clientId); - discount = DISCOUNT_AMOUNT.multiply(exchange).setScale(2, BigDecimal.ROUND_DOWN); + discount = DISCOUNT_AMOUNT.multiply(exchange).setScale(2, RoundingMode.DOWN); } else { discount = DISCOUNT_AMOUNT; } @@ -109,7 +107,7 @@ public class OneDollarDayActivitySupportImpl implements OneDollarDayActivity, Pa BigDecimal discountOrigin = paymentInfo.getDiscount(); paymentInfo.setDiscount(discountOrigin.add(discount)); JSONObject updateOrder = new JSONObject(); - BigDecimal customerPay = payAmount.subtract(discount).setScale(2, BigDecimal.ROUND_DOWN); + BigDecimal customerPay = payAmount.subtract(discount).setScale(2, RoundingMode.DOWN); updateOrder.put("customer_payment_amount", customerPay); updateOrder.put("coupon_payment_amount", discount); updateOrder.put("order_id", orderId); diff --git a/src/main/java/au/com/royalpay/payment/manage/activities/diet/web/OneDollarDayAnalysisController.java b/src/main/java/au/com/royalpay/payment/manage/activities/diet/web/OneDollarDayAnalysisController.java index e06f44023..38a325329 100644 --- a/src/main/java/au/com/royalpay/payment/manage/activities/diet/web/OneDollarDayAnalysisController.java +++ b/src/main/java/au/com/royalpay/payment/manage/activities/diet/web/OneDollarDayAnalysisController.java @@ -4,7 +4,9 @@ import au.com.royalpay.payment.manage.activities.diet.core.OneDollarDayActivity; import au.com.royalpay.payment.manage.permission.manager.ManagerMapping; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; -import org.springframework.web.bind.annotation.*; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; import java.util.List; @@ -31,13 +33,13 @@ public class OneDollarDayAnalysisController { */ @GetMapping("/transaction_analysis") public List transaction_analysis(@RequestParam Map map) { - JSONObject params = JSONObject.parseObject(JSON.toJSONString(map)); + JSONObject params = JSON.parseObject(JSON.toJSONString(map)); return oneDollarDayActivity.getTransactionAnalysis(params); } @GetMapping("/subsidy") public List transaction_subsidy(@RequestParam Map map) { - JSONObject params = JSONObject.parseObject(JSON.toJSONString(map)); + JSONObject params = JSON.parseObject(JSON.toJSONString(map)); return oneDollarDayActivity.getSubsidyInDays(params); } diff --git a/src/main/java/au/com/royalpay/payment/manage/activities/monsettledelay/core/impls/ActMonDelaySettleManagerServiceImpl.java b/src/main/java/au/com/royalpay/payment/manage/activities/monsettledelay/core/impls/ActMonDelaySettleManagerServiceImpl.java index b6ad30bc7..d424dfca6 100644 --- a/src/main/java/au/com/royalpay/payment/manage/activities/monsettledelay/core/impls/ActMonDelaySettleManagerServiceImpl.java +++ b/src/main/java/au/com/royalpay/payment/manage/activities/monsettledelay/core/impls/ActMonDelaySettleManagerServiceImpl.java @@ -5,7 +5,6 @@ import au.com.royalpay.payment.manage.activities.monsettledelay.core.ActMonDelay import au.com.royalpay.payment.manage.mappers.act.ActMonDelaySettleMapper; import au.com.royalpay.payment.manage.mappers.act.ActMonDelaySettleRedPackMapper; import au.com.royalpay.payment.manage.mappers.system.ClientMapper; -import au.com.royalpay.payment.tools.exceptions.BadRequestException; import au.com.royalpay.payment.tools.utils.PageListUtils; import com.alibaba.fastjson.JSONObject; import com.github.miemiedev.mybatis.paginator.domain.Order; @@ -15,7 +14,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.annotation.Resource; -import java.util.Date; import java.util.List; /** @@ -43,7 +41,7 @@ public class ActMonDelaySettleManagerServiceImpl implements ActMonDelaySettleMan public void disableClient(String clientMoniker) { JSONObject client = clientMapper.findClientByMoniker(clientMoniker); List clientLogs = actMonDelaySettleMapper.clientLog(client.getInteger("client_id")); - if (clientLogs.isEmpty() || clientLogs.size()==0){ + if (clientLogs.isEmpty() || clientLogs.isEmpty()){ throw new BadRequestException("您未参加活动,不可取消"); } JSONObject clientLog = clientLogs.get(0); diff --git a/src/main/java/au/com/royalpay/payment/manage/analysis/core/impls/AmountAnalysisServiceImp.java b/src/main/java/au/com/royalpay/payment/manage/analysis/core/impls/AmountAnalysisServiceImp.java index 30fc800d5..68a4f8627 100644 --- a/src/main/java/au/com/royalpay/payment/manage/analysis/core/impls/AmountAnalysisServiceImp.java +++ b/src/main/java/au/com/royalpay/payment/manage/analysis/core/impls/AmountAnalysisServiceImp.java @@ -40,13 +40,13 @@ public class AmountAnalysisServiceImp implements AmountAnalysisService { // for (Map.Entry entry :amountData.entrySet()){ // // } - if (ar.size() == 0) { + if (ar.isEmpty()) { return res; } PageList logs = transactionAnalysisMapper.listAmountRangeOrders(params, new PageBounds(Order.formString("transaction_time.desc"))); for (JSONObject log : logs) { - if (ar.size() > 0) { + if (!ar.isEmpty()) { for (int i = 0; i < ar.size(); i++) { JSONObject amountObj = ar.getJSONObject(i); // params.put("amount_from",amountObj.getString("from").length()>0?amountObj.getBigDecimal("from"):null); @@ -72,7 +72,7 @@ public class AmountAnalysisServiceImp implements AmountAnalysisService { } } } - if (ar.size() > 0) { + if (!ar.isEmpty()) { for (int i = 0; i < ar.size(); i++) { JSONObject amountObj = ar.getJSONObject(i); res.add(amountObj); diff --git a/src/main/java/au/com/royalpay/payment/manage/analysis/core/impls/BDAnalysisServiceImpl.java b/src/main/java/au/com/royalpay/payment/manage/analysis/core/impls/BDAnalysisServiceImpl.java index a60237c60..9048c3695 100644 --- a/src/main/java/au/com/royalpay/payment/manage/analysis/core/impls/BDAnalysisServiceImpl.java +++ b/src/main/java/au/com/royalpay/payment/manage/analysis/core/impls/BDAnalysisServiceImpl.java @@ -22,6 +22,7 @@ import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.OutputStream; import java.math.BigDecimal; +import java.math.RoundingMode; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; @@ -412,7 +413,7 @@ public class BDAnalysisServiceImpl implements BDAnalysisService { } else if (lastTotal.compareTo(new BigDecimal(0)) == 0 && total.compareTo(new BigDecimal(0)) == 0) { rate = 0; } else { - rate = total.subtract(lastTotal).multiply(new BigDecimal(100)).divide(lastTotal, 2, BigDecimal.ROUND_DOWN).doubleValue(); + rate = total.subtract(lastTotal).multiply(new BigDecimal(100)).divide(lastTotal, 2, RoundingMode.DOWN).doubleValue(); } } HSSFRichTextString text23 = i == 0 ? new HSSFRichTextString("-") : new HSSFRichTextString(String.valueOf(rate)); @@ -451,7 +452,7 @@ public class BDAnalysisServiceImpl implements BDAnalysisService { } else if (lastTotal.compareTo(new BigDecimal(0)) == 0 && total.compareTo(new BigDecimal(0)) == 0) { rate = 0; } else { - rate = total.subtract(lastTotal).multiply(new BigDecimal(100)).divide(lastTotal, 2, BigDecimal.ROUND_DOWN).doubleValue(); + rate = total.subtract(lastTotal).multiply(new BigDecimal(100)).divide(lastTotal, 2, RoundingMode.DOWN).doubleValue(); } } HSSFRichTextString texti3 = new HSSFRichTextString(String.valueOf(rate)); @@ -489,7 +490,7 @@ public class BDAnalysisServiceImpl implements BDAnalysisService { // else if (lastTotal.compareTo(new BigDecimal(0))==0 && total.compareTo(new BigDecimal(0)) ==0){ // rate=0; // }else { -// rate = total.subtract(lastTotal).multiply(new BigDecimal(100)).divide(lastTotal,2,BigDecimal.ROUND_DOWN).doubleValue(); +// rate = total.subtract(lastTotal).multiply(new BigDecimal(100)).divide(lastTotal,2,RoundingMode.DOWN).doubleValue(); // } // } // HSSFRichTextString texti3 = new HSSFRichTextString(String.valueOf(rate)); diff --git a/src/main/java/au/com/royalpay/payment/manage/analysis/core/impls/CustomersAnalysisServiceImp.java b/src/main/java/au/com/royalpay/payment/manage/analysis/core/impls/CustomersAnalysisServiceImp.java index e34eee4b6..15b92f3ab 100644 --- a/src/main/java/au/com/royalpay/payment/manage/analysis/core/impls/CustomersAnalysisServiceImp.java +++ b/src/main/java/au/com/royalpay/payment/manage/analysis/core/impls/CustomersAnalysisServiceImp.java @@ -106,7 +106,7 @@ public class CustomersAnalysisServiceImp implements CustomersAnalysisService { public JSONObject getCustomersRanking(JSONObject params, int page, int limit) { PageList logs = orderAnalysisMapper.listCustomersData(params, new PageBounds(page, limit, Order.formString( params.getString("orderValue") ))); - if (logs.size() > 0) { + if (!logs.isEmpty()) { for (JSONObject log : logs) { generatorUserProfile(log, params); } @@ -351,7 +351,7 @@ public class CustomersAnalysisServiceImp implements CustomersAnalysisService { JSONObject user = new JSONObject(); user.put("id", 0); user.put("category", 0); - if (userInfo.size() > 0) { + if (!userInfo.isEmpty()) { user.put("name", userInfo.getString("nickname")); } else { user.put("name", params.getString("customer_id")); @@ -417,9 +417,9 @@ public class CustomersAnalysisServiceImp implements CustomersAnalysisService { } private String getTopInfo(List list, String key) { - if (list != null && list.size() > 0) { + if (list != null && !list.isEmpty()) { List clients = list.stream().map(e -> e.getString(key)).collect(Collectors.toList()); - return String.join(",", clients); + return String.join(",", clients); } return "None"; } diff --git a/src/main/java/au/com/royalpay/payment/manage/analysis/core/impls/DailyReportImp.java b/src/main/java/au/com/royalpay/payment/manage/analysis/core/impls/DailyReportImp.java index 2c6952f4a..fc313b389 100644 --- a/src/main/java/au/com/royalpay/payment/manage/analysis/core/impls/DailyReportImp.java +++ b/src/main/java/au/com/royalpay/payment/manage/analysis/core/impls/DailyReportImp.java @@ -19,6 +19,7 @@ import au.com.royalpay.payment.tools.exceptions.BadRequestException; import au.com.royalpay.payment.tools.exceptions.ForbiddenException; import au.com.royalpay.payment.tools.exceptions.NotFoundException; import au.com.royalpay.payment.tools.permission.enums.ManagerRole; +import au.com.royalpay.payment.tools.utils.JsonHelper; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import org.apache.commons.lang3.time.DateFormatUtils; @@ -29,6 +30,7 @@ import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.math.BigDecimal; +import java.math.RoundingMode; import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.ParseException; @@ -136,7 +138,7 @@ public class DailyReportImp implements DailyReport { kpi.put("compare_value", Math.abs(compare.doubleValue())); } } - kpi.put("kpi_percent", p.getBigDecimal("month_amount").divide(kpi_amount, 4, BigDecimal.ROUND_HALF_DOWN).multiply(BigDecimal.valueOf(100)).toString().substring(0, 5) + "%"); + kpi.put("kpi_percent", p.getBigDecimal("month_amount").divide(kpi_amount, 4, RoundingMode.HALF_DOWN).multiply(BigDecimal.valueOf(100)).toString().substring(0, 5) + "%"); for (JSONObject clientAmount : clientsAmount) { if (clientAmount.getString("bd_group").equals(kpi.getString("bd_group"))) { //查询该领队下所有BD @@ -162,11 +164,11 @@ public class DailyReportImp implements DailyReport { kpiList.add(kpi); } report.put("kpiList", kpiList); - report.put("kpi_percent_total", total_month_amount.divide(total_kpi_amount, 4, BigDecimal.ROUND_HALF_DOWN).multiply(BigDecimal.valueOf(100)).toString().substring(0, 5) + "%"); + report.put("kpi_percent_total", total_month_amount.divide(total_kpi_amount, 4, RoundingMode.HALF_DOWN).multiply(BigDecimal.valueOf(100)).toString().substring(0, 5) + "%"); report.put("total_month_amount", total_month_amount); Calendar calendar = Calendar.getInstance(); calendar.setTime(dt); - report.put("time_percent", BigDecimal.valueOf(calendar.get(Calendar.DAY_OF_MONTH)).divide(BigDecimal.valueOf(calendar.getActualMaximum(Calendar.DAY_OF_MONTH)), 4, BigDecimal.ROUND_HALF_DOWN).multiply(BigDecimal.valueOf(100)).toString().substring(0, 5) + "%"); + report.put("time_percent", BigDecimal.valueOf(calendar.get(Calendar.DAY_OF_MONTH)).divide(BigDecimal.valueOf(calendar.getActualMaximum(Calendar.DAY_OF_MONTH)), 4, RoundingMode.HALF_DOWN).multiply(BigDecimal.valueOf(100)).toString().substring(0, 5) + "%"); return report; } @@ -246,38 +248,38 @@ public class DailyReportImp implements DailyReport { JSONObject percentage_yesterday_tax_amount = this.percentage(yesterday_tax_amount, last_tax_amount); report.put("channels", settles); - report.put("total_settle_amount", new JSONObject() {{ - put("amount", yesterday_settle_amount); - put("compare", percentage_yesterday_settle_amount); - }}); - report.put("total_credit_amount", new JSONObject() {{ - put("amount", yesterday_credit_amount); - put("compare", percentage_yesterday_total_credit); - }}); - report.put("total_debit_amount", new JSONObject() {{ - put("amount", yesterday_debit_amount); - put("compare", percentage_yesterday_debit_amount); - }}); - report.put("total_net_trading", new JSONObject() {{ - put("amount", yesterday_net_trading); - put("compare", percentage_yesterday_net_trading); - }}); - report.put("total_total_surcharge", new JSONObject() {{ - put("amount", yesterday_total_surcharge); - put("compare", percentage_yesterday_total_surcharge); - }}); - report.put("total_royal_surcharge", new JSONObject() {{ - put("amount", yesterday_royal_surcharge); - put("compare", percentage_yesterday_royal_surcharge); - }}); - report.put("total_channel_surcharge", new JSONObject() {{ - put("amount", yesterday_channel_surcharge); - put("compare", percentage_yesterday_channel_surcharge); - }}); - report.put("total_tax_amount", new JSONObject() {{ - put("amount", yesterday_tax_amount); - put("compare", percentage_yesterday_tax_amount); - }}); + report.put("total_settle_amount", JsonHelper.newJson(json -> { + json.put("amount", yesterday_settle_amount); + json.put("compare", percentage_yesterday_settle_amount); + })); + report.put("total_credit_amount", JsonHelper.newJson(json -> { + json.put("amount", yesterday_credit_amount); + json.put("compare", percentage_yesterday_total_credit); + })); + report.put("total_debit_amount", JsonHelper.newJson(json -> { + json.put("amount", yesterday_debit_amount); + json.put("compare", percentage_yesterday_debit_amount); + })); + report.put("total_net_trading", JsonHelper.newJson(json -> { + json.put("amount", yesterday_net_trading); + json.put("compare", percentage_yesterday_net_trading); + })); + report.put("total_total_surcharge", JsonHelper.newJson(json -> { + json.put("amount", yesterday_total_surcharge); + json.put("compare", percentage_yesterday_total_surcharge); + })); + report.put("total_royal_surcharge", JsonHelper.newJson(json -> { + json.put("amount", yesterday_royal_surcharge); + json.put("compare", percentage_yesterday_royal_surcharge); + })); + report.put("total_channel_surcharge", JsonHelper.newJson(json -> { + json.put("amount", yesterday_channel_surcharge); + json.put("compare", percentage_yesterday_channel_surcharge); + })); + report.put("total_tax_amount", JsonHelper.newJson(json -> { + json.put("amount", yesterday_tax_amount); + json.put("compare", percentage_yesterday_tax_amount); + })); return report; } @@ -337,16 +339,16 @@ public class DailyReportImp implements DailyReport { String finalTotal_royal_surcharge = df1.format(total_royal_surcharge); String finalTotal_channel_surcharge = df1.format(total_channel_surcharge); String finalTotal_tax_amount = df1.format(total_tax_amount); - return new JSONObject() {{ - put("total_settle_amount", finalTotal_settle_amount); - put("total_credit_amount", finalTotal_credit_amount); - put("total_debit_amount", finalTotal_debit_amount); - put("total_net_trading", finalTotal_net_trading); - put("total_total_surcharge", finalTotal_total_surcharge); - put("total_royal_surcharge", finalTotal_royal_surcharge); - put("total_channel_surcharge", finalTotal_channel_surcharge); - put("total_tax_amount", finalTotal_tax_amount); - }}; + return JsonHelper.newJson(json -> { + json.put("total_settle_amount", finalTotal_settle_amount); + json.put("total_credit_amount", finalTotal_credit_amount); + json.put("total_debit_amount", finalTotal_debit_amount); + json.put("total_net_trading", finalTotal_net_trading); + json.put("total_total_surcharge", finalTotal_total_surcharge); + json.put("total_royal_surcharge", finalTotal_royal_surcharge); + json.put("total_channel_surcharge", finalTotal_channel_surcharge); + json.put("total_tax_amount", finalTotal_tax_amount); + }); } private JSONObject percentage(BigDecimal num1, BigDecimal num2) { @@ -364,10 +366,10 @@ public class DailyReportImp implements DailyReport { String result = format.format(ratio < 1 ? 1 - ratio : ratio - 1); boolean finalPositive = positive; - return new JSONObject() {{ - put("compare", result); - put("positive", finalPositive); - }}; + return JsonHelper.newJson(json -> { + json.put("compare", result); + json.put("positive", finalPositive); + }); } @@ -410,7 +412,7 @@ public class DailyReportImp implements DailyReport { } } } - logger.info("DailyReportUsers" + clean_users.toString()); + logger.info("DailyReportUsers {}", clean_users.toString()); } private TemplateMessage initMsg(String range, String url, String time, String openId, String templateId) { diff --git a/src/main/java/au/com/royalpay/payment/manage/analysis/core/impls/DashboardServiceImpl.java b/src/main/java/au/com/royalpay/payment/manage/analysis/core/impls/DashboardServiceImpl.java index b250fbc5d..4e498cbb4 100644 --- a/src/main/java/au/com/royalpay/payment/manage/analysis/core/impls/DashboardServiceImpl.java +++ b/src/main/java/au/com/royalpay/payment/manage/analysis/core/impls/DashboardServiceImpl.java @@ -13,6 +13,7 @@ import au.com.royalpay.payment.manage.mappers.system.ExchangeRateMapper; import au.com.royalpay.payment.manage.merchants.core.ClientManager; import au.com.royalpay.payment.tools.defines.TradeType; import au.com.royalpay.payment.tools.merchants.core.MerchantInfoProvider; +import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.github.miemiedev.mybatis.paginator.domain.Order; import com.github.miemiedev.mybatis.paginator.domain.PageBounds; @@ -66,8 +67,8 @@ public class DashboardServiceImpl implements DashboardService,DashboardAnalysisT @Override public JSONObject getCommonAnalysis1(JSONObject params) { - String jsonStr = stringRedisTemplate.boundValueOps("org_commonAnalysis1"+ params.getString("org_id")+ params.getString("begin")).get(); - JSONObject commonAnalysis1 = JSONObject.parseObject(jsonStr); + String jsonStr = stringRedisTemplate.boundValueOps("org_commonAnalysis1" + params.getString("org_id") + params.getString("begin")).get(); + JSONObject commonAnalysis1 = JSON.parseObject(jsonStr); if(commonAnalysis1 != null){ return commonAnalysis1; } @@ -88,8 +89,8 @@ public class DashboardServiceImpl implements DashboardService,DashboardAnalysisT @Override public JSONObject getCommonAnalysis3(JSONObject params) { - String jsonStr = stringRedisTemplate.boundValueOps("org_commonAnalysis3"+ params.getString("org_id")+ params.getString("begin")).get(); - JSONObject commonAnalysis3 = JSONObject.parseObject(jsonStr); + String jsonStr = stringRedisTemplate.boundValueOps("org_commonAnalysis3" + params.getString("org_id") + params.getString("begin")).get(); + JSONObject commonAnalysis3 = JSON.parseObject(jsonStr); if(commonAnalysis3 != null){ return commonAnalysis3; } @@ -105,8 +106,8 @@ public class DashboardServiceImpl implements DashboardService,DashboardAnalysisT @Override public JSONObject getCommonAnalysis2(JSONObject params) { - String jsonStr = stringRedisTemplate.boundValueOps("org_commonAnalysis2"+ params.getString("org_id")+ params.getString("begin")).get(); - JSONObject commonAnalysis2 = JSONObject.parseObject(jsonStr); + String jsonStr = stringRedisTemplate.boundValueOps("org_commonAnalysis2" + params.getString("org_id") + params.getString("begin")).get(); + JSONObject commonAnalysis2 = JSON.parseObject(jsonStr); if(commonAnalysis2 != null){ return commonAnalysis2; } @@ -135,8 +136,8 @@ public class DashboardServiceImpl implements DashboardService,DashboardAnalysisT @Override public JSONObject getCommonAnalysis4(JSONObject params) { - String jsonStr = stringRedisTemplate.boundValueOps("org_commonAnalysis4"+ params.getString("org_id")+ params.getString("begin")).get(); - JSONObject commonAnalysis4 = JSONObject.parseObject(jsonStr); + String jsonStr = stringRedisTemplate.boundValueOps("org_commonAnalysis4" + params.getString("org_id") + params.getString("begin")).get(); + JSONObject commonAnalysis4 = JSON.parseObject(jsonStr); if(commonAnalysis4 != null){ return commonAnalysis4; } @@ -265,7 +266,7 @@ public class DashboardServiceImpl implements DashboardService,DashboardAnalysisT JSONObject retailInStore = new JSONObject(); retailInStore.put("name", "Retail In-Store"); retailInStore.put("data", retailInStore_orders); - if (!retailInStore_orders.isEmpty() && retailInStore_orders.size() > 0) { + if (!retailInStore_orders.isEmpty()) { analysis.add(retailInStore); } params.put("trade_type", "WeChat HTML5"); @@ -468,7 +469,7 @@ public class DashboardServiceImpl implements DashboardService,DashboardAnalysisT @Override public JSONObject getNewRecord() { String jsonStr = stringRedisTemplate.boundValueOps("newRecord").get(); - JSONObject newRecord = JSONObject.parseObject(jsonStr); + JSONObject newRecord = JSON.parseObject(jsonStr); if(newRecord != null){ return newRecord; } @@ -568,8 +569,8 @@ public class DashboardServiceImpl implements DashboardService,DashboardAnalysisT } @Override public JSONObject getPlatformAmount(JSONObject params) { - String jsonStr = stringRedisTemplate.boundValueOps("org_ChannelAnalysis" + params.getString("org_id")+params.getString("begin")).get(); - JSONObject channelAnalysis = JSONObject.parseObject(jsonStr); + String jsonStr = stringRedisTemplate.boundValueOps("org_ChannelAnalysis" + params.getString("org_id") + params.getString("begin")).get(); + JSONObject channelAnalysis = JSON.parseObject(jsonStr); if(channelAnalysis != null){ return channelAnalysis; }else { diff --git a/src/main/java/au/com/royalpay/payment/manage/analysis/core/impls/EstimateAnalysisServiceImpl.java b/src/main/java/au/com/royalpay/payment/manage/analysis/core/impls/EstimateAnalysisServiceImpl.java index 35cff711f..8e6d9641a 100644 --- a/src/main/java/au/com/royalpay/payment/manage/analysis/core/impls/EstimateAnalysisServiceImpl.java +++ b/src/main/java/au/com/royalpay/payment/manage/analysis/core/impls/EstimateAnalysisServiceImpl.java @@ -15,27 +15,19 @@ import au.com.royalpay.payment.manage.mappers.system.ClientMapper; import au.com.royalpay.payment.tools.exceptions.BadRequestException; import au.com.royalpay.payment.tools.exceptions.NotFoundException; import au.com.royalpay.payment.tools.utils.TimeZoneUtils; - import com.alibaba.fastjson.JSONObject; - import org.apache.commons.lang3.time.DateFormatUtils; import org.apache.commons.lang3.time.DateUtils; -import org.jsoup.helper.DataUtil; import org.slf4j.LoggerFactory; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; +import javax.annotation.Resource; import java.math.BigDecimal; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Date; -import java.util.List; -import java.util.TimeZone; - -import javax.annotation.Resource; +import java.util.*; /** * Created by Tayl0r on 2017/7/3. @@ -258,7 +250,7 @@ public class EstimateAnalysisServiceImpl implements EstimateAnalysisService { String end_date = maxDays.getString("date_str"); JSONObject cleanDays = estimateAnalysisMapper.findLastCleanDays(endStr, 1); List tencentSettle = platformSettlementMapper.findBySettleDate(new Date(maxDays.getDate("date_str").getTime() - 86400000L), "Wechat"); - if (tencentSettle != null && tencentSettle.size() > 0) { + if (tencentSettle != null && !tencentSettle.isEmpty()) { for (JSONObject logs : tencentSettle) { dayInfo.put("settlementFee_" + logs.getString("merchants"), logs.getBigDecimal("settlement_fee")); if (!dayInfo.containsKey("platformGetSettleFee")) { @@ -316,7 +308,7 @@ public class EstimateAnalysisServiceImpl implements EstimateAnalysisService { logger.info("系统开始生成[ " + report_date + " ]清算总额"); JSONObject isClearDay = estimateAnalysisMapper.checkIsClearDay(report_date); - if (isClearDay != null && isClearDay.size() > 0) { + if (isClearDay != null && !isClearDay.isEmpty()) { JSONObject estimate = getCleanDayAmount(report_date); estimate.put("log_date", report_date); estimate.put("last_update_date", new Date()); diff --git a/src/main/java/au/com/royalpay/payment/manage/analysis/core/impls/PartnerCardDashboardServiceImp.java b/src/main/java/au/com/royalpay/payment/manage/analysis/core/impls/PartnerCardDashboardServiceImp.java index f2e233884..03363b90b 100644 --- a/src/main/java/au/com/royalpay/payment/manage/analysis/core/impls/PartnerCardDashboardServiceImp.java +++ b/src/main/java/au/com/royalpay/payment/manage/analysis/core/impls/PartnerCardDashboardServiceImp.java @@ -22,7 +22,7 @@ import org.springframework.stereotype.Service; import org.springframework.util.Assert; import javax.annotation.Resource; -import java.math.BigDecimal; +import java.math.RoundingMode; import java.util.Date; import java.util.List; @@ -63,13 +63,13 @@ public class PartnerCardDashboardServiceImp implements PartnerCardDashboardServi JSONObject ali_pay = merchantInfoProvider.clientCurrentRate(client.getIntValue("client_id"), data, "Alipay"); JSONObject rate_value = new JSONObject(); if (res != null) { - rate_value.put("wechat_rate_value", res.getBigDecimal("rate_value").setScale(1, BigDecimal.ROUND_DOWN)); + rate_value.put("wechat_rate_value", res.getBigDecimal("rate_value").setScale(1, RoundingMode.DOWN)); if (res.getInteger("clean_days") != null) { client.put("clean_days", res.getIntValue("clean_days")); } } if (ali_pay != null) { - rate_value.put("ali_rate_value", ali_pay.getBigDecimal("rate_value").setScale(1, BigDecimal.ROUND_DOWN)); + rate_value.put("ali_rate_value", ali_pay.getBigDecimal("rate_value").setScale(1, RoundingMode.DOWN)); } client.put("rate_value", rate_value); return client; diff --git a/src/main/java/au/com/royalpay/payment/manage/analysis/core/impls/PlatformClearAnalysisServiceImpl.java b/src/main/java/au/com/royalpay/payment/manage/analysis/core/impls/PlatformClearAnalysisServiceImpl.java index 9cc9877a3..556e514d1 100644 --- a/src/main/java/au/com/royalpay/payment/manage/analysis/core/impls/PlatformClearAnalysisServiceImpl.java +++ b/src/main/java/au/com/royalpay/payment/manage/analysis/core/impls/PlatformClearAnalysisServiceImpl.java @@ -189,7 +189,7 @@ public class PlatformClearAnalysisServiceImpl implements PlatformClearService { params.put("channel", channel); params.put("last_update_date", new Date()); JSONObject sysClearData = getSystemClearingAmount(dateStr, aliSettleLog, channel); - if (sysClearData != null && sysClearData.size() > 0) { + if (sysClearData != null && !sysClearData.isEmpty()) { params.put("sys_pay_fee", sysClearData.getBigDecimal("sys_pay_fee")); params.put("sys_refund_fee", sysClearData.getBigDecimal("sys_refund_fee")); params.put("sys_net_fee", sysClearData.getBigDecimal("sys_net_fee")); @@ -222,7 +222,7 @@ public class PlatformClearAnalysisServiceImpl implements PlatformClearService { params.put("channel", "Wechat"); params.put("last_update_date", new Date()); JSONObject sysClearData = getSystemClearingAmount(null, settle, "Wechat"); - if (sysClearData != null && sysClearData.size() > 0) { + if (sysClearData != null && !sysClearData.isEmpty()) { params.put("sys_pay_fee", sysClearData.getBigDecimal("sys_pay_fee")); params.put("sys_refund_fee", sysClearData.getBigDecimal("sys_refund_fee")); params.put("sys_net_fee", sysClearData.getBigDecimal("sys_net_fee")); diff --git a/src/main/java/au/com/royalpay/payment/manage/analysis/core/impls/WeekReporterImpl.java b/src/main/java/au/com/royalpay/payment/manage/analysis/core/impls/WeekReporterImpl.java index 1708cb9db..034d0d399 100644 --- a/src/main/java/au/com/royalpay/payment/manage/analysis/core/impls/WeekReporterImpl.java +++ b/src/main/java/au/com/royalpay/payment/manage/analysis/core/impls/WeekReporterImpl.java @@ -22,11 +22,11 @@ import org.apache.commons.lang3.time.DateFormatUtils; import org.apache.commons.lang3.time.DateUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.math.BigDecimal; +import java.math.RoundingMode; import java.text.ParseException; import java.util.ArrayList; import java.util.Calendar; @@ -124,8 +124,8 @@ public class WeekReporterImpl implements WeekReporter { if (sendMsg) { List users = managerMapper.listRoyalPayUsers(); publishMessages(users, reportId, dateRange); - if (partnersReport!=null && partnersReport.size()>0){ - publishPartnersMessages(reportId,dateRange); + if (partnersReport != null && !partnersReport.isEmpty()) { + publishPartnersMessages(reportId, dateRange); } } } catch (ParseException e) { @@ -386,7 +386,7 @@ public class WeekReporterImpl implements WeekReporter { for (JSONObject tranaction : transactions) { JSONObject report = new JSONObject(); report.put("date", tranaction.getString("date_str")); - BigDecimal fee = tranaction.getBigDecimal("aud_fee").setScale(2, BigDecimal.ROUND_DOWN); + BigDecimal fee = tranaction.getBigDecimal("aud_fee").setScale(2, RoundingMode.DOWN); report.put("fee", fee); report.put("order_count", tranaction.getIntValue("order_count")); dailyReport.add(report); diff --git a/src/main/java/au/com/royalpay/payment/manage/appclient/beans/AppQueryBean.java b/src/main/java/au/com/royalpay/payment/manage/appclient/beans/AppQueryBean.java index 874757cdc..86bb7a7fd 100644 --- a/src/main/java/au/com/royalpay/payment/manage/appclient/beans/AppQueryBean.java +++ b/src/main/java/au/com/royalpay/payment/manage/appclient/beans/AppQueryBean.java @@ -1,20 +1,15 @@ package au.com.royalpay.payment.manage.appclient.beans; import au.com.royalpay.payment.core.beans.OrderStatus; -import au.com.royalpay.payment.core.exceptions.ParamInvalidException; import au.com.royalpay.payment.core.beans.PayChannel; import au.com.royalpay.payment.tools.defines.TradeType; -import au.com.royalpay.payment.tools.utils.TimeZoneUtils; import com.alibaba.fastjson.JSONObject; import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.time.DateUtils; -import org.castor.util.StringUtil; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.format.DateTimeFormat; import java.text.DateFormat; -import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; @@ -61,7 +56,7 @@ public class AppQueryBean { tradeTypes.add(type.getGateway()); } } - if (tradeTypes.size() > 0) { + if (!tradeTypes.isEmpty()) { params.put("trade_type", tradeTypes); } } @@ -74,7 +69,7 @@ public class AppQueryBean { tradeTypes.add(type.getGateway()); } } - if (tradeTypes.size() > 0) { + if (!tradeTypes.isEmpty()) { params.put("trade_type", tradeTypes); } } diff --git a/src/main/java/au/com/royalpay/payment/manage/appclient/core/impls/RetailAppServiceImp.java b/src/main/java/au/com/royalpay/payment/manage/appclient/core/impls/RetailAppServiceImp.java index 1f5ac643d..aec5a8be4 100644 --- a/src/main/java/au/com/royalpay/payment/manage/appclient/core/impls/RetailAppServiceImp.java +++ b/src/main/java/au/com/royalpay/payment/manage/appclient/core/impls/RetailAppServiceImp.java @@ -290,11 +290,11 @@ public class RetailAppServiceImp implements RetailAppService { res.put("alipay_rate", paymentApi.channelApi("Alipay").queryExchangeRateDecimal(clientId)); } params.put("channel", "system"); - res.put("sys_not_settled", new BigDecimal(transactionAnalysisMapper.analysisNotSettled(params)).setScale(2, BigDecimal.ROUND_DOWN).toPlainString()); + res.put("sys_not_settled", new BigDecimal(transactionAnalysisMapper.analysisNotSettled(params)).setScale(2, RoundingMode.DOWN).toPlainString()); params.put("channel", "rpaypmt_card"); - res.put("rpaypmt_card_not_settled", new BigDecimal(transactionAnalysisMapper.analysisNotSettled(params)).setScale(2, BigDecimal.ROUND_DOWN).toPlainString()); + res.put("rpaypmt_card_not_settled", new BigDecimal(transactionAnalysisMapper.analysisNotSettled(params)).setScale(2, RoundingMode.DOWN).toPlainString()); params.put("channel", "rpaypmt_dd"); - res.put("rpaypmt_dd_not_settled", new BigDecimal(transactionAnalysisMapper.analysisNotSettled(params)).setScale(2, BigDecimal.ROUND_DOWN).toPlainString()); + res.put("rpaypmt_dd_not_settled", new BigDecimal(transactionAnalysisMapper.analysisNotSettled(params)).setScale(2, RoundingMode.DOWN).toPlainString()); return res; } @@ -2291,7 +2291,7 @@ public class RetailAppServiceImp implements RetailAppService { throw new BadRequestException("Verification code is wrong"); } List account = clientAccountMapper.findByPhone(contactPhone, "+" + nationCode); - if (account != null && account.size() > 0) { + if (account != null && !account.isEmpty()) { throw new BadRequestException("Mobile phone number has been bound to other users, please unbind it before binding"); } @@ -2678,7 +2678,7 @@ public class RetailAppServiceImp implements RetailAppService { return params; }) .collect(Collectors.toList()); - if (clientFileUrl.size() > 0) { + if (!clientFileUrl.isEmpty()) { result.put("kyc_utility_bill_file", clientFileUrl); } } @@ -3129,14 +3129,14 @@ public class RetailAppServiceImp implements RetailAppService { int clientId = account.getIntValue("client_id"); JSONObject displayInfo = actPartnerReadMapper.displayInfo(actId, clientId, accountId); if (displayInfo == null) { - displayInfo = new JSONObject() {{ - put("display_client_id", UUID.randomUUID().toString()); - put("act_id", actId); - put("client_id", clientId); - put("account_id", accountId); - put("last_read_time", new Date()); - put("display_count", 1); - }}; + displayInfo = JsonHelper.newJson(json -> { + json.put("display_client_id", UUID.randomUUID().toString()); + json.put("act_id", actId); + json.put("client_id", clientId); + json.put("account_id", accountId); + json.put("last_read_time", new Date()); + json.put("display_count", 1); + }); actPartnerReadMapper.save(displayInfo); return false; } diff --git a/src/main/java/au/com/royalpay/payment/manage/appclient/core/impls/RetailRSvcServiceImpl.java b/src/main/java/au/com/royalpay/payment/manage/appclient/core/impls/RetailRSvcServiceImpl.java index bbc612edf..c26fdab76 100644 --- a/src/main/java/au/com/royalpay/payment/manage/appclient/core/impls/RetailRSvcServiceImpl.java +++ b/src/main/java/au/com/royalpay/payment/manage/appclient/core/impls/RetailRSvcServiceImpl.java @@ -18,10 +18,11 @@ import au.com.royalpay.payment.tools.encryptalgorithm.SignUtils; import au.com.royalpay.payment.tools.exceptions.BadRequestException; import au.com.royalpay.payment.tools.exceptions.NotFoundException; import au.com.royalpay.payment.tools.mappers.CommonIncrementalChannelMapper; -import org.apache.commons.codec.binary.Base64; +import au.com.royalpay.payment.tools.utils.JsonHelper; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.parser.Feature; +import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -37,8 +38,8 @@ import java.util.concurrent.TimeUnit; @Service public class RetailRSvcServiceImpl implements RetailRSvcService { - private Logger logger = LoggerFactory.getLogger(getClass()); - private Map senderMap = new HashMap<>(); + private final Logger logger = LoggerFactory.getLogger(getClass()); + private final Map senderMap = new HashMap<>(); @Resource private ClientManager clientManager; @Resource @@ -54,7 +55,7 @@ public class RetailRSvcServiceImpl implements RetailRSvcService { @Resource private AppMessageLogMapper appMessageLogMapper; - private ThreadPoolExecutor sendingAppleMsgPool = new ThreadPoolExecutor(10, 30, 5, TimeUnit.SECONDS, new LinkedBlockingQueue()); + private final ThreadPoolExecutor sendingAppleMsgPool = new ThreadPoolExecutor(10, 30, 5, TimeUnit.SECONDS, new LinkedBlockingQueue()); @Resource public void setAppMsgSenders(AppMsgSender[] senders) { @@ -79,23 +80,22 @@ public class RetailRSvcServiceImpl implements RetailRSvcService { RSvcMchBean svcMchBean = clientManager.findSvcMchByAccountId(device.getString("account_id")); String aesKeyStr = Base64.encodeBase64String(AESCrypt.randomKey().getEncoded()); Key key = AESCrypt.fromKeyString(Base64.decodeBase64(aesKeyStr)); - JSONObject result = (JSONObject) JSONObject.toJSON(svcMchBean); + JSONObject result = (JSONObject) JSON.toJSON(svcMchBean); result.put("sign_type", "RSA2"); - result.put("enc_data", new JSONObject() { - { - put("credentialCode", encData(svcMchBean.getCredentialCode(), key, svcInfo.getString("channel_pub_key"))); - put("payHost", encData(svcMchBean.getPayHost(), key, svcInfo.getString("channel_pub_key"))); - put("partnerCode", encData(svcMchBean.getPartnerCode(), key, svcInfo.getString("channel_pub_key"))); - put("merchantNumber", encData(svcMchBean.getMerchantNumber(), key, svcInfo.getString("channel_pub_key"))); - } - }); + result.put("enc_data", JsonHelper.newJson(json -> { + json.put("credentialCode", encData(svcMchBean.getCredentialCode(), key, svcInfo.getString("channel_pub_key"))); + json.put("payHost", encData(svcMchBean.getPayHost(), key, svcInfo.getString("channel_pub_key"))); + json.put("partnerCode", encData(svcMchBean.getPartnerCode(), key, svcInfo.getString("channel_pub_key"))); + json.put("merchantNumber", encData(svcMchBean.getMerchantNumber(), key, svcInfo.getString("channel_pub_key"))); + } + )); result.remove("credentialCode"); result.remove("payHost"); result.remove("partnerCode"); result.remove("merchantNumber"); result.put("nonce_str", aesKeyStr); result.put("timestamp", System.currentTimeMillis()); - result = JSONObject.parseObject(JSON.toJSONString(result), Feature.OrderedField); + result = JSON.parseObject(JSON.toJSONString(result), Feature.OrderedField); result.put("sign", SignUtils.buildSign(result.toJSONString(), svcInfo.getString("platform_pri_key"))); logger.info("svc [{}] info:{}", sourceCode, result.toJSONString()); return result; @@ -110,10 +110,10 @@ public class RetailRSvcServiceImpl implements RetailRSvcService { || StringUtils.isEmpty(svcInfo.getString("platform_pub_key")) || StringUtils.isEmpty("platform_pri_key")) { throw new BadRequestException("this channel config is wrong"); } - logger.debug("{} new services apply :{}", params.getString("signClient"),params.toJSONString()); + logger.debug("{} new services apply :{}", params.getString("signClient"), params.toJSONString()); String signa = params.getString("sign"); params.remove("sign"); - params = JSONObject.parseObject(JSON.toJSONString(params), Feature.OrderedField); + params = JSON.parseObject(JSON.toJSONString(params), Feature.OrderedField); boolean checkSign = SignUtils.validSign(params.toJSONString(), signa, svcInfo.getString("channel_pub_key")); if (!checkSign) { throw new BadRequestException("sign is wrong"); @@ -126,14 +126,14 @@ public class RetailRSvcServiceImpl implements RetailRSvcService { String signPrice = "0"; String signRate = "0"; if (params.get("signPrice") != null) { - logger.debug("{} new services apply amount origin:{}", params.getString("signClient"),params.getString("signPrice")); + logger.debug("{} new services apply amount origin:{}", params.getString("signClient"), params.getString("signPrice")); signPrice = decData(params.getString("signPrice"), key, svcInfo.getString("platform_pri_key")); - logger.debug("{} new services apply amount now:{}", params.getString("signClient"),signPrice); + logger.debug("{} new services apply amount now:{}", params.getString("signClient"), signPrice); } if (params.get("signRate") != null) { - logger.debug("{} new services apply rate origin:{}", params.getString("signClient"),params.getString("signRate")); + logger.debug("{} new services apply rate origin:{}", params.getString("signClient"), params.getString("signRate")); signRate = decData(params.getString("signRate"), key, svcInfo.getString("platform_pri_key")); - logger.debug("{} new services apply rate origin:{}", params.getString("signClient"),signRate); + logger.debug("{} new services apply rate origin:{}", params.getString("signClient"), signRate); } JSONObject serviceApply = new JSONObject(); serviceApply.put("apply_id", UUID.randomUUID().toString()); @@ -149,7 +149,7 @@ public class RetailRSvcServiceImpl implements RetailRSvcService { clientServicesApplyMapper.save(serviceApply); result.put("result_status", "PROCESSING"); } catch (Exception e) { - logger.error("enter R services fail:{} - {}",sourceCode,e.getMessage()); + logger.error("enter R services fail:{} - {}", sourceCode, e.getMessage()); result.put("result_status", "SYSTEMERROR"); result.put("result_msg", e.getMessage()); } @@ -168,13 +168,13 @@ public class RetailRSvcServiceImpl implements RetailRSvcService { Key key = AESCrypt.fromKeyString(Base64.decodeBase64(params.getString("nonce_str"))); String signa = params.getString("sign"); params.remove("sign"); - params = JSONObject.parseObject(JSON.toJSONString(params), Feature.OrderedField); + params = JSON.parseObject(JSON.toJSONString(params), Feature.OrderedField); boolean checkSign = SignUtils.validSign(params.toJSONString(), signa, svcInfo.getString("channel_pub_key")); if (!checkSign) { throw new BadRequestException("sign is wrong"); } String clientMoniker = decData(params.getString("partnerCode"), key, svcInfo.getString("platform_pri_key")); - logger.debug("{} new shop set up :{}", clientMoniker,params.toJSONString()); + logger.debug("{} new shop set up :{}", clientMoniker, params.toJSONString()); JSONObject client = clientManager.getClientInfoByMoniker(clientMoniker); if (client == null) { throw new InvalidShortIdException(); @@ -184,7 +184,7 @@ public class RetailRSvcServiceImpl implements RetailRSvcService { clientConfigMapper.update(clientConfig); result.put("result_status", "SUCCESS"); } catch (Exception e) { - logger.error("set up geek shop fail:{} - {}",sourceCode,e.getMessage()); + logger.error("set up geek shop fail:{} - {}", sourceCode, e.getMessage()); result.put("result_status", "SYSTEMERROR"); result.put("result_msg", e.getMessage()); } @@ -203,13 +203,13 @@ public class RetailRSvcServiceImpl implements RetailRSvcService { Key key = AESCrypt.fromKeyString(Base64.decodeBase64(params.getString("nonce_str"))); String signa = params.getString("sign"); params.remove("sign"); - params = JSONObject.parseObject(JSON.toJSONString(params), Feature.OrderedField); + params = JSON.parseObject(JSON.toJSONString(params), Feature.OrderedField); boolean checkSign = SignUtils.validSign(params.toJSONString(), signa, svcInfo.getString("channel_pub_key")); if (!checkSign) { throw new BadRequestException("sign is wrong"); } String clientMoniker = decData(params.getString("partnerCode"), key, svcInfo.getString("platform_pri_key")); - logger.debug("geek {} app notify info :{}", clientMoniker,params.toJSONString()); + logger.debug("geek {} app notify info :{}", clientMoniker, params.toJSONString()); JSONObject client = clientManager.getClientInfoByMoniker(clientMoniker); if (client == null) { throw new InvalidShortIdException(); @@ -220,7 +220,7 @@ public class RetailRSvcServiceImpl implements RetailRSvcService { sendRServiceNotifyMessage(client, title, body, url); result.put("result_status", "SUCCESS"); } catch (Exception e) { - logger.error("geek notify app fail:{} - {}",sourceCode,e.getMessage()); + logger.error("geek notify app fail:{} - {}", sourceCode, e.getMessage()); result.put("result_status", "SYSTEMERROR"); result.put("result_msg", e.getMessage()); } @@ -241,15 +241,13 @@ public class RetailRSvcServiceImpl implements RetailRSvcService { result.put("partnerCode", encData(clientMoniker, key, svcInfo.getString("channel_pub_key"))); result.put("nonce_str", aesKeyStr); result.put("timestamp", System.currentTimeMillis()); - result = JSONObject.parseObject(JSON.toJSONString(result), Feature.OrderedField); + result = JSON.parseObject(JSON.toJSONString(result), Feature.OrderedField); result.put("sign", SignUtils.buildSign(result.toJSONString(), svcInfo.getString("platform_pri_key"))); String encryptedStrInfo = JSON.toJSONString(result); String jwtResult = JWTUtil.sign(encryptedStrInfo, JWTUtil.SECRET); logger.info("clientMoniker:{} - json:{} - token:{}", clientMoniker, encryptedStrInfo, jwtResult); - return new JSONObject() {{ - put("token", jwtResult); - }}; + return JsonHelper.newJson(json -> json.put("token", jwtResult)); } private void sendRServiceNotifyMessage(JSONObject client, String title, String body, String url) { @@ -285,7 +283,7 @@ public class RetailRSvcServiceImpl implements RetailRSvcService { log.put("status", 2); appMessageLogMapper.update(log); } catch (Exception e) { - logger.error("出错了:" + e.getMessage()); + logger.error("出错了:{}", e.getMessage()); appMessageLogMapper.updateStatus(log.getString("send_id"), 1, e.getMessage()); } }; diff --git a/src/main/java/au/com/royalpay/payment/manage/appclient/web/RetailClientController.java b/src/main/java/au/com/royalpay/payment/manage/appclient/web/RetailClientController.java index c2e62a914..832409575 100644 --- a/src/main/java/au/com/royalpay/payment/manage/appclient/web/RetailClientController.java +++ b/src/main/java/au/com/royalpay/payment/manage/appclient/web/RetailClientController.java @@ -6,16 +6,14 @@ import au.com.royalpay.payment.manage.signin.core.SignInStatusManager; import au.com.royalpay.payment.manage.signin.events.ClientLoginEvent; import au.com.royalpay.payment.tools.env.RequestEnvironment; import au.com.royalpay.payment.tools.exceptions.BadRequestException; +import au.com.royalpay.payment.tools.utils.JsonHelper; import com.alibaba.fastjson.JSONObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.ApplicationEventPublisherAware; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; -import au.com.royalpay.payment.manage.permission.utils.GeekLoginDESUtil; import javax.annotation.Resource; import javax.validation.Valid; @@ -58,14 +56,14 @@ public class RetailClientController implements ApplicationEventPublisherAware { JSONObject response = new JSONObject(); response.put("status", "SUCCESS"); JSONObject industryInfo = clientManager.findByLookupCode(clientAllInfo.getString("industry")); - response.put("clientInfo", new JSONObject() {{ - put("partner_code", clientAllInfo.getString("client_moniker")); - put("company_name", clientAllInfo.getString("company_name")); - put("logo", clientAllInfo.getString("client_moniker")); - put("gateway_credential", clientAllInfo.getString("credential_code")); - put("industry_code", clientAllInfo.getString("industry")); - put("industry_value", industryInfo.getString("lookup_value")); - }}); + response.put("clientInfo", JsonHelper.newJson(json -> { + json.put("partner_code", clientAllInfo.getString("client_moniker")); + json.put("company_name", clientAllInfo.getString("company_name")); + json.put("logo", clientAllInfo.getString("client_moniker")); + json.put("gateway_credential", clientAllInfo.getString("credential_code")); + json.put("industry_code", clientAllInfo.getString("industry")); + json.put("industry_value", industryInfo.getString("lookup_value")); + })); return response; } diff --git a/src/main/java/au/com/royalpay/payment/manage/application/core/impls/SimpleClientApplyServiceImpl.java b/src/main/java/au/com/royalpay/payment/manage/application/core/impls/SimpleClientApplyServiceImpl.java index 4b65265e5..8db3798f0 100644 --- a/src/main/java/au/com/royalpay/payment/manage/application/core/impls/SimpleClientApplyServiceImpl.java +++ b/src/main/java/au/com/royalpay/payment/manage/application/core/impls/SimpleClientApplyServiceImpl.java @@ -276,7 +276,7 @@ public class SimpleClientApplyServiceImpl implements SimpleClientApplyService { nation_code = "+" + nation_code; } List account = clientAccountMapper.findByPhone(contact_phone, nation_code); - if (account != null && account.size()>0) { + if (account != null && !account.isEmpty()) { throw new ForbiddenException("用户名已被注册"); } } @@ -330,7 +330,7 @@ public class SimpleClientApplyServiceImpl implements SimpleClientApplyService { apply.put("clean", "T+" + clean_days.trim()); apply.put("clean_days", clean_days); JSONObject sysConfig = sysConfigManager.getSysConfig(); - JSONObject test = JSONObject.parseObject(sysConfig.getString("sys_apply_rates")); + JSONObject test = JSON.parseObject(sysConfig.getString("sys_apply_rates")); JSONObject rate = test.getJSONObject("t"+clean_days.trim()); @@ -498,8 +498,8 @@ public class SimpleClientApplyServiceImpl implements SimpleClientApplyService { apply.put("clean", "T+" + clean_days.trim()); apply.put("clean_days", clean_days); JSONObject sysConfig = sysConfigManager.getSysConfig(); - JSONObject test = JSONObject.parseObject(sysConfig.getString("sys_apply_rates")); - JSONObject rate = test.getJSONObject("t"+clean_days.trim()); + JSONObject test = JSON.parseObject(sysConfig.getString("sys_apply_rates")); + JSONObject rate = test.getJSONObject("t" + clean_days.trim()); apply.put("wechat_rate",rate.getString("Wechat")); apply.put("alipay_rate",rate.getString("Alipay")); apply.put("alipay_online_rate",rate.getString("AlipayOnline")); @@ -590,7 +590,7 @@ public class SimpleClientApplyServiceImpl implements SimpleClientApplyService { JSONObject apply = sysClientPreMapperMapper.findByUserName(username); List account = clientAccountMapper.findByPhone(apply.getString("contact_phone"), "+61"); - if (account != null && account.size() > 0) { + if (account != null && !account.isEmpty()) { throw new ForbiddenException("The user name has been registered"); } String clientMoniker = generateClientMoniker(); @@ -739,7 +739,7 @@ public class SimpleClientApplyServiceImpl implements SimpleClientApplyService { sysRate.put("active_time", DateFormatUtils.format(DateUtils.addDays(new Date(),-1), "yyyy-MM-dd")); sysRate.put("expiry_time", DateFormatUtils.format(DateUtils.addYears(new Date(), 1), "yyyy-MM-dd")); - JSONObject rateConfig = JSONObject.parseObject(sysConfig.getString("sys_apply_rates")); + JSONObject rateConfig = JSON.parseObject(sysConfig.getString("sys_apply_rates")); JSONObject chooseRate = new JSONObject(); if (apply.getIntValue("clean_days") == 1) { chooseRate = rateConfig.getJSONObject("t1"); diff --git a/src/main/java/au/com/royalpay/payment/manage/application/web/SimpleClientApplyController.java b/src/main/java/au/com/royalpay/payment/manage/application/web/SimpleClientApplyController.java index e0a0ef029..465f95631 100644 --- a/src/main/java/au/com/royalpay/payment/manage/application/web/SimpleClientApplyController.java +++ b/src/main/java/au/com/royalpay/payment/manage/application/web/SimpleClientApplyController.java @@ -6,6 +6,7 @@ import au.com.royalpay.payment.manage.application.core.SimpleClientApplyService; import au.com.royalpay.payment.tools.connections.attachment.core.AttachmentClient; import au.com.royalpay.payment.tools.env.RequestEnvironment; import au.com.royalpay.payment.tools.env.SysConfigManager; +import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import org.apache.commons.lang3.StringUtils; import org.springframework.web.bind.annotation.*; @@ -111,7 +112,7 @@ public class SimpleClientApplyController { @GetMapping("/config/sys_rates") public JSONObject getSysRate() { JSONObject sysConfig = sysConfigManager.getSysConfig(); - return JSONObject.parseObject(sysConfig.getString("sys_apply_rates")); + return JSON.parseObject(sysConfig.getString("sys_apply_rates")); } @GetMapping("/config/sys_rates_register") diff --git a/src/main/java/au/com/royalpay/payment/manage/apps/core/impls/CustomerImpressionServiceImpl.java b/src/main/java/au/com/royalpay/payment/manage/apps/core/impls/CustomerImpressionServiceImpl.java index c00ef1ef5..1f11568d1 100644 --- a/src/main/java/au/com/royalpay/payment/manage/apps/core/impls/CustomerImpressionServiceImpl.java +++ b/src/main/java/au/com/royalpay/payment/manage/apps/core/impls/CustomerImpressionServiceImpl.java @@ -10,13 +10,12 @@ import au.com.royalpay.payment.tools.exceptions.BadRequestException; import au.com.royalpay.payment.tools.exceptions.NotFoundException; import au.com.royalpay.payment.tools.lock.Locker; import au.com.royalpay.payment.tools.utils.PageListUtils; - +import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.github.miemiedev.mybatis.paginator.domain.Order; import com.github.miemiedev.mybatis.paginator.domain.PageBounds; import com.github.miemiedev.mybatis.paginator.domain.PageList; import com.maxmind.geoip.LookupService; - import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.time.DateFormatUtils; import org.joda.time.DateTime; @@ -28,12 +27,11 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.CollectionUtils; +import javax.annotation.Resource; import java.util.ArrayList; import java.util.Date; import java.util.List; -import javax.annotation.Resource; - /** * Created by wangning on 2017/12/28. */ @@ -137,7 +135,7 @@ public class CustomerImpressionServiceImpl implements CustomerImpressionService while (!StringUtils.isEmpty(redisValue)) { try { - JSONObject order = JSONObject.parseObject(redisValue); + JSONObject order = JSON.parseObject(redisValue); redisValue = ops.leftPop(); if (StringUtils.isEmpty(order.getString("channel"))) { continue; diff --git a/src/main/java/au/com/royalpay/payment/manage/apps/core/impls/SSOSupportImpl.java b/src/main/java/au/com/royalpay/payment/manage/apps/core/impls/SSOSupportImpl.java index fc82e9d99..6a198b0ff 100644 --- a/src/main/java/au/com/royalpay/payment/manage/apps/core/impls/SSOSupportImpl.java +++ b/src/main/java/au/com/royalpay/payment/manage/apps/core/impls/SSOSupportImpl.java @@ -1,6 +1,7 @@ package au.com.royalpay.payment.manage.apps.core.impls; import au.com.royalpay.payment.manage.apps.core.SSOSupport; +import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import org.apache.commons.lang3.RandomStringUtils; import org.slf4j.Logger; @@ -48,7 +49,7 @@ public class SSOSupportImpl implements SSOSupport { String jsonstr = stringRedisTemplate.boundValueOps(cacheKey).get(); stringRedisTemplate.delete(cacheKey); if (jsonstr != null) { - JSONObject referer = JSONObject.parseObject(jsonstr); + JSONObject referer = JSON.parseObject(jsonstr); return new RefererInfo(referer.getString("referer"), referer.getString("appid")); } return null; @@ -74,7 +75,7 @@ public class SSOSupportImpl implements SSOSupport { String jsonstr = stringRedisTemplate.boundValueOps(cacheKey).get(); stringRedisTemplate.delete(cacheKey); if (jsonstr != null) { - return JSONObject.parseObject(jsonstr); + return JSON.parseObject(jsonstr); } return null; } diff --git a/src/main/java/au/com/royalpay/payment/manage/apps/events/listeners/ctrip/CtripAfterPaymentFinishListener.java b/src/main/java/au/com/royalpay/payment/manage/apps/events/listeners/ctrip/CtripAfterPaymentFinishListener.java index 7d60245c5..0314c0f83 100644 --- a/src/main/java/au/com/royalpay/payment/manage/apps/events/listeners/ctrip/CtripAfterPaymentFinishListener.java +++ b/src/main/java/au/com/royalpay/payment/manage/apps/events/listeners/ctrip/CtripAfterPaymentFinishListener.java @@ -3,17 +3,14 @@ package au.com.royalpay.payment.manage.apps.events.listeners.ctrip; import au.com.royalpay.payment.core.events.AfterPaymentFinishEvent; import au.com.royalpay.payment.manage.customers.core.CouponValidateService; import au.com.royalpay.payment.manage.mappers.log.CouponAccuessLogMapper; - import com.alibaba.fastjson.JSONObject; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationListener; import org.springframework.stereotype.Service; -import java.util.List; - import javax.annotation.Resource; +import java.util.List; /** * Created by wangning on 17/01/2018. @@ -31,10 +28,10 @@ public class CtripAfterPaymentFinishListener implements ApplicationListener accuessCouponLogs = couponAccuessLogMapper.findCouponByOrderId(orderId); - if (accuessCouponLogs != null&&accuessCouponLogs.size()>0) { + if (accuessCouponLogs != null && !accuessCouponLogs.isEmpty()) { JSONObject accuessCouponLog = accuessCouponLogs.get(0); String couponId = accuessCouponLog.getString("coupon_id"); - couponValidateService.ctripCouponLogNotice(couponId,orderId,order.getString("customer_id"),order.getString("status")); + couponValidateService.ctripCouponLogNotice(couponId, orderId, order.getString("customer_id"), order.getString("status")); logger.info("订单 [" + orderId + "]推送支付成功Ctrip卡券=======>[" + couponId + "]"); } } diff --git a/src/main/java/au/com/royalpay/payment/manage/apps/events/listeners/ctrip/CtripRefundFinishedEventListener.java b/src/main/java/au/com/royalpay/payment/manage/apps/events/listeners/ctrip/CtripRefundFinishedEventListener.java index 08bcffb3a..07a8a604f 100644 --- a/src/main/java/au/com/royalpay/payment/manage/apps/events/listeners/ctrip/CtripRefundFinishedEventListener.java +++ b/src/main/java/au/com/royalpay/payment/manage/apps/events/listeners/ctrip/CtripRefundFinishedEventListener.java @@ -4,17 +4,14 @@ import au.com.royalpay.payment.core.events.RefundFinishedEvent; import au.com.royalpay.payment.manage.customers.core.CouponValidateService; import au.com.royalpay.payment.manage.mappers.log.CouponAccuessLogMapper; import au.com.royalpay.payment.manage.mappers.payment.OrderMapper; - import com.alibaba.fastjson.JSONObject; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationListener; import org.springframework.stereotype.Service; -import java.util.List; - import javax.annotation.Resource; +import java.util.List; /** * @author kira @@ -35,10 +32,10 @@ public class CtripRefundFinishedEventListener implements ApplicationListener accuessCouponLogs = couponAccuessLogMapper.findCouponByOrderId(orderId); - if (accuessCouponLogs != null&&accuessCouponLogs.size()>0) { + if (accuessCouponLogs != null && !accuessCouponLogs.isEmpty()) { JSONObject accuessCouponLog = accuessCouponLogs.get(0); String couponId = accuessCouponLog.getString("coupon_id"); - couponValidateService.ctripCouponLogNotice(couponId,orderId,order.getString("customer_id"),order.getString("status")); + couponValidateService.ctripCouponLogNotice(couponId, orderId, order.getString("customer_id"), order.getString("status")); logger.info("订单 [" + orderId + "]推送退款成功Ctrip卡券=======>[" + couponId + "]"); } } diff --git a/src/main/java/au/com/royalpay/payment/manage/bdprize/core/impls/BDPrizeServiceImpl.java b/src/main/java/au/com/royalpay/payment/manage/bdprize/core/impls/BDPrizeServiceImpl.java index f7e073ea1..97546526e 100644 --- a/src/main/java/au/com/royalpay/payment/manage/bdprize/core/impls/BDPrizeServiceImpl.java +++ b/src/main/java/au/com/royalpay/payment/manage/bdprize/core/impls/BDPrizeServiceImpl.java @@ -39,6 +39,7 @@ import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.OutputStream; import java.math.BigDecimal; +import java.math.RoundingMode; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; @@ -155,7 +156,7 @@ public class BDPrizeServiceImpl implements BDPrizeService { JSONObject rateJson = financialBDCommissionConfigMapper.findCurrentCommissionRate(month, groupAmount.toString(), bd_type); BigDecimal groupPrize = new BigDecimal(0); if (rateJson != null) { - groupPrize = groupAmount.multiply(new BigDecimal(rateJson.getString("commission_rate")).divide(percent)).setScale(2, BigDecimal.ROUND_DOWN); + groupPrize = groupAmount.multiply(new BigDecimal(rateJson.getString("commission_rate")).divide(percent)).setScale(2, RoundingMode.DOWN); } BigDecimal send_prize = groupPrize; JSONObject prizeLog = new JSONObject(); @@ -236,12 +237,12 @@ public class BDPrizeServiceImpl implements BDPrizeService { // } else { // BigDecimal _commission_rate = new BigDecimal(cplRate.getString("commission_rate")); // BigDecimal _total_amount = new BigDecimal(cityPrizeLog.getString("total_amount")); -// BigDecimal total_prize = _total_amount.multiply(_commission_rate.divide(percent)).setScale(2, BigDecimal.ROUND_DOWN); +// BigDecimal total_prize = _total_amount.multiply(_commission_rate.divide(percent)).setScale(2, RoundingMode.DOWN); // cityPrizeLog.put("total_prize", total_prize); // } // report.put("cityPrizeLogs", cityPrizeLog); List leaderPrizeLog = financialLeaderPrizeLogMapper.listLeaderPrizeLog(report.getString("record_id")); - if (leaderPrizeLog.size() > 0) { + if (!leaderPrizeLog.isEmpty()) { for (JSONObject prizeLog : leaderPrizeLog) { if (prizeLog.getIntValue("bd_type") == 3) { report.put("sydneyPrizeLog", prizeLog); @@ -270,7 +271,7 @@ public class BDPrizeServiceImpl implements BDPrizeService { sydneyPrizeLog.put("total_prize", 0.00); } else { BigDecimal sydney_commission_rate = new BigDecimal(sydneyGMRate.getString("commission_rate")); - BigDecimal total_prize = sydneyAmount.multiply(sydney_commission_rate.divide(percent)).setScale(2, BigDecimal.ROUND_DOWN); + BigDecimal total_prize = sydneyAmount.multiply(sydney_commission_rate.divide(percent)).setScale(2, RoundingMode.DOWN); sydneyPrizeLog.put("total_prize", total_prize); } report.put("sydneyPrizeLog", sydneyPrizeLog); @@ -292,7 +293,7 @@ public class BDPrizeServiceImpl implements BDPrizeService { } else { BigDecimal _commission_rate = new BigDecimal(rate.getString("commission_rate")); BigDecimal _total_amount = new BigDecimal(directPrizeLogs.getString("total_amount")); - BigDecimal total_prize = _total_amount.multiply(_commission_rate.divide(percent)).setScale(2, BigDecimal.ROUND_DOWN); + BigDecimal total_prize = _total_amount.multiply(_commission_rate.divide(percent)).setScale(2, RoundingMode.DOWN); directPrizeLogs.put("total_prize", total_prize); } report.put("directPrizeLogs", directPrizeLogs); @@ -306,7 +307,7 @@ public class BDPrizeServiceImpl implements BDPrizeService { ngDepartmentPrizeLog.put("total_prize", 0.00); } else { BigDecimal ng_commission_rate = new BigDecimal(ngRate.getString("commission_rate")); - BigDecimal ng_total_prize = totalprize.multiply(ng_commission_rate.divide(percent)).setScale(2, BigDecimal.ROUND_DOWN); + BigDecimal ng_total_prize = totalprize.multiply(ng_commission_rate.divide(percent)).setScale(2, RoundingMode.DOWN); ngDepartmentPrizeLog.put("total_prize", ng_total_prize); } report.put("ngDepartmentPrizeLog", ngDepartmentPrizeLog); diff --git a/src/main/java/au/com/royalpay/payment/manage/bdprize/support/impls/BDPrizeCalculatorDefaultImpl.java b/src/main/java/au/com/royalpay/payment/manage/bdprize/support/impls/BDPrizeCalculatorDefaultImpl.java index fcb5b3746..89cebb2fb 100644 --- a/src/main/java/au/com/royalpay/payment/manage/bdprize/support/impls/BDPrizeCalculatorDefaultImpl.java +++ b/src/main/java/au/com/royalpay/payment/manage/bdprize/support/impls/BDPrizeCalculatorDefaultImpl.java @@ -1,23 +1,17 @@ package au.com.royalpay.payment.manage.bdprize.support.impls; -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Date; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import au.com.royalpay.payment.manage.mappers.payment.TransactionMapper; -import com.alibaba.fastjson.JSONObject; - import au.com.royalpay.payment.manage.bdprize.support.BDPrizeCalculator; +import au.com.royalpay.payment.manage.mappers.payment.TransactionMapper; import au.com.royalpay.payment.manage.mappers.system.ClientBDMapper; import au.com.royalpay.payment.tools.exceptions.ServerErrorException; +import com.alibaba.fastjson.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.util.*; + /** * Created by yixian on 2017-02-08. */ @@ -107,24 +101,24 @@ public class BDPrizeCalculatorDefaultImpl implements BDPrizeCalculator { int prizeLevel = getKpiPrizeLevel(totalAmount,log.getBigDecimal("kpi_amount")); logger.debug("-------->bd kpi level:"+bd.getString("bd_name")+"---level:"+prizeLevel+",kpi:"+log.getBigDecimal("kpi_amount")+",trans:"+totalAmount+",client_id:"+clientId); BigDecimal bdRate = getNewRate(bdLevel, prizeLevel, detailItem.getIntValue("client_source"), detailItem.getBigDecimal("rate_value")); - BigDecimal prizeValue = totalTransaction.multiply(coefficient).multiply(bdRate).divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_DOWN); + BigDecimal prizeValue = totalTransaction.multiply(coefficient).multiply(bdRate).divide(BigDecimal.valueOf(100), 2, RoundingMode.DOWN); BigDecimal donation = BigDecimal.ZERO; if (clientsWithBDAwayDeterminor.clientWithBDAway(clientId, month)) { - prizeValue = prizeValue.multiply(BigDecimal.valueOf(0.5)).setScale(2, BigDecimal.ROUND_DOWN); - donation = new BigDecimal(prizeValue.toPlainString()).setScale(2, BigDecimal.ROUND_DOWN); + prizeValue = prizeValue.multiply(BigDecimal.valueOf(0.5)).setScale(2, RoundingMode.DOWN); + donation = new BigDecimal(prizeValue.toPlainString()).setScale(2, RoundingMode.DOWN); detailItem.put("client_status", 2); } detailItem.put("prize_value", prizeValue); detailItem.put("donation", donation); detailItem.put("bd_rate", bdRate); details.add(detailItem); - log.put("total_amount", log.getBigDecimal("total_amount").add(totalTransaction.multiply(coefficient)).setScale(2, BigDecimal.ROUND_DOWN)); + log.put("total_amount", log.getBigDecimal("total_amount").add(totalTransaction.multiply(coefficient)).setScale(2, RoundingMode.DOWN)); log.put("total_prize", log.getBigDecimal("total_prize").add(prizeValue)); log.put("total_donation", log.getBigDecimal("total_donation").add(donation)); } log.put("details", details); BigDecimal totalPrize = log.getBigDecimal("total_prize"); - BigDecimal sendPrize = totalPrize.multiply(BigDecimal.valueOf(0.8)).setScale(2, BigDecimal.ROUND_DOWN); + BigDecimal sendPrize = totalPrize.multiply(BigDecimal.valueOf(0.8)).setScale(2, RoundingMode.DOWN); log.put("send_prize", sendPrize); log.put("hold_prize", totalPrize.subtract(sendPrize)); report.add(log); @@ -237,7 +231,7 @@ public class BDPrizeCalculatorDefaultImpl implements BDPrizeCalculator { if (clientSource == 1) { return prizeRate; } else { - return prizeRate.divide(BigDecimal.valueOf(2),3,BigDecimal.ROUND_HALF_DOWN); + return prizeRate.divide(BigDecimal.valueOf(2), 3, RoundingMode.HALF_DOWN); } } @@ -245,7 +239,7 @@ public class BDPrizeCalculatorDefaultImpl implements BDPrizeCalculator { if (kpiAmount.compareTo(BigDecimal.ZERO)==0){//未设置kpi金额的按照最小完成度来计算 return 1; } - BigDecimal rate = transactionAmount.divide(kpiAmount,2,BigDecimal.ROUND_HALF_DOWN); + BigDecimal rate = transactionAmount.divide(kpiAmount, 2, RoundingMode.HALF_DOWN); if (rate.compareTo(BigDecimal.valueOf(0.5))<0){ return 1; } diff --git a/src/main/java/au/com/royalpay/payment/manage/bill/core/impl/BillServiceImpl.java b/src/main/java/au/com/royalpay/payment/manage/bill/core/impl/BillServiceImpl.java index 53db378c9..6349a184b 100644 --- a/src/main/java/au/com/royalpay/payment/manage/bill/core/impl/BillServiceImpl.java +++ b/src/main/java/au/com/royalpay/payment/manage/bill/core/impl/BillServiceImpl.java @@ -1,17 +1,5 @@ package au.com.royalpay.payment.manage.bill.core.impl; -import java.math.BigDecimal; -import java.util.Date; - -import javax.annotation.Resource; - -import org.apache.commons.lang3.time.DateUtils; -import org.springframework.stereotype.Service; - -import com.alibaba.fastjson.JSONObject; -import com.github.miemiedev.mybatis.paginator.domain.PageBounds; -import com.github.miemiedev.mybatis.paginator.domain.PageList; - import au.com.royalpay.payment.manage.bill.bean.NewBillBean; import au.com.royalpay.payment.manage.bill.bean.QueryBillBean; import au.com.royalpay.payment.manage.bill.core.BillService; @@ -22,6 +10,15 @@ import au.com.royalpay.payment.tools.env.PlatformEnvironment; import au.com.royalpay.payment.tools.exceptions.BadRequestException; import au.com.royalpay.payment.tools.exceptions.ServerErrorException; import au.com.royalpay.payment.tools.utils.PageListUtils; +import com.alibaba.fastjson.JSONObject; +import com.github.miemiedev.mybatis.paginator.domain.PageBounds; +import com.github.miemiedev.mybatis.paginator.domain.PageList; +import org.apache.commons.lang3.time.DateUtils; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.math.RoundingMode; +import java.util.Date; /** * Created by wangning on 11/02/2018. @@ -42,7 +39,7 @@ public class BillServiceImpl implements BillService { Date now = new Date(); JSONObject record = new JSONObject(); record.put("client_id", client_id); - record.put("price", newBillBean.getAmount().divide(CommonConsts.HUNDRED,2, BigDecimal.ROUND_DOWN)); + record.put("price", newBillBean.getAmount().divide(CommonConsts.HUNDRED, 2, RoundingMode.DOWN)); record.put("currency", newBillBean.getCurrency()); record.put("remark", newBillBean.getRemark()); record.put("create_time", now); diff --git a/src/main/java/au/com/royalpay/payment/manage/cashiers/core/impls/CashierServiceImp.java b/src/main/java/au/com/royalpay/payment/manage/cashiers/core/impls/CashierServiceImp.java index 09d4343e9..72e2a654e 100644 --- a/src/main/java/au/com/royalpay/payment/manage/cashiers/core/impls/CashierServiceImp.java +++ b/src/main/java/au/com/royalpay/payment/manage/cashiers/core/impls/CashierServiceImp.java @@ -23,7 +23,7 @@ import org.springframework.ui.Model; import org.springframework.util.Assert; import javax.annotation.Resource; -import java.math.BigDecimal; +import java.math.RoundingMode; import java.util.Date; import java.util.concurrent.TimeUnit; @@ -141,7 +141,7 @@ public class CashierServiceImp implements CashierService { @Override public void prepareModalMap(JSONObject client, JSONObject cashier, String channel, Model modelMap) { PaymentChannelApi api = paymentApi.channelApi(channel); - String exchangeRate = api.queryExchangeRateDecimal(client.getIntValue("client_id")).setScale(5, BigDecimal.ROUND_DOWN).toPlainString(); + String exchangeRate = api.queryExchangeRateDecimal(client.getIntValue("client_id")).setScale(5, RoundingMode.DOWN).toPlainString(); modelMap.addAttribute("exchange_rate", exchangeRate); modelMap.addAttribute("channel", channel); diff --git a/src/main/java/au/com/royalpay/payment/manage/citypartner/core/impls/CityPartnerPrizeServiceImpl.java b/src/main/java/au/com/royalpay/payment/manage/citypartner/core/impls/CityPartnerPrizeServiceImpl.java index 9a0c1f9f2..062fdb8aa 100644 --- a/src/main/java/au/com/royalpay/payment/manage/citypartner/core/impls/CityPartnerPrizeServiceImpl.java +++ b/src/main/java/au/com/royalpay/payment/manage/citypartner/core/impls/CityPartnerPrizeServiceImpl.java @@ -345,7 +345,7 @@ public class CityPartnerPrizeServiceImpl implements CityPartnerPrizeService { int month = monthCal.get(Calendar.MONTH) + 1; List list = financialPartnerCommissionMapper.list(year, month); - if (list != null && list.size() > 0) { + if (list != null && !list.isEmpty()) { throw new ServerErrorException("请不要重复生成合伙人记录"); } @@ -630,13 +630,13 @@ public class CityPartnerPrizeServiceImpl implements CityPartnerPrizeService { BigDecimal thirdPartyPaymentCharge = BigDecimal.ZERO; switch (channel) { case "Alipay": - thirdPartyPaymentCharge = total.multiply(chargeRate.getBigDecimal("alipayChargeRate").divide(CommonConsts.HUNDRED, 4, BigDecimal.ROUND_DOWN)).setScale(2, RoundingMode.HALF_UP); + thirdPartyPaymentCharge = total.multiply(chargeRate.getBigDecimal("alipayChargeRate").divide(CommonConsts.HUNDRED, 4, RoundingMode.DOWN)).setScale(2, RoundingMode.HALF_UP); break; case "Wechat": - thirdPartyPaymentCharge = total.multiply(chargeRate.getBigDecimal("wechatChargeRate").divide(CommonConsts.HUNDRED, 4, BigDecimal.ROUND_DOWN)).setScale(2, RoundingMode.HALF_UP); + thirdPartyPaymentCharge = total.multiply(chargeRate.getBigDecimal("wechatChargeRate").divide(CommonConsts.HUNDRED, 4, RoundingMode.DOWN)).setScale(2, RoundingMode.HALF_UP); break; case "AlipayOnline": - thirdPartyPaymentCharge = total.multiply(chargeRate.getBigDecimal("alipayonlineChargeRate").divide(CommonConsts.HUNDRED, 4, BigDecimal.ROUND_DOWN)).setScale(2, RoundingMode.HALF_UP); + thirdPartyPaymentCharge = total.multiply(chargeRate.getBigDecimal("alipayonlineChargeRate").divide(CommonConsts.HUNDRED, 4, RoundingMode.DOWN)).setScale(2, RoundingMode.HALF_UP); break; default: break; @@ -1145,7 +1145,7 @@ public class CityPartnerPrizeServiceImpl implements CityPartnerPrizeService { } BigDecimal finalRate = rate; result.parallelStream().forEach(p -> { - p.put("net_charge", p.getBigDecimal("gross_amount").multiply(finalRate).setScale(2, BigDecimal.ROUND_HALF_DOWN)); + p.put("net_charge", p.getBigDecimal("gross_amount").multiply(finalRate).setScale(2, RoundingMode.HALF_DOWN)); p.put("org_rate", finalRate.multiply(CommonConsts.HUNDRED)); }); return result; diff --git a/src/main/java/au/com/royalpay/payment/manage/complianceAudit/core/impl/ClientComplianceApplyImpl.java b/src/main/java/au/com/royalpay/payment/manage/complianceAudit/core/impl/ClientComplianceApplyImpl.java index d92cb2b5d..1c17826dd 100644 --- a/src/main/java/au/com/royalpay/payment/manage/complianceAudit/core/impl/ClientComplianceApplyImpl.java +++ b/src/main/java/au/com/royalpay/payment/manage/complianceAudit/core/impl/ClientComplianceApplyImpl.java @@ -60,7 +60,7 @@ public class ClientComplianceApplyImpl implements ClientComplianceApply } List clientFiles = clientFilesMapper.findAllClientFile(client.getIntValue("client_id")); JSONObject fileJson = new JSONObject(); - if (clientFiles != null && clientFiles.size() > 0) { + if (clientFiles != null && !clientFiles.isEmpty()) { for (String fileKey : fileKeys) { List clientFileUrl = clientFiles.stream() .filter(json -> (fileKey.equals(json.getString("file_name")))) @@ -73,7 +73,7 @@ public class ClientComplianceApplyImpl implements ClientComplianceApply return params; }) .collect(Collectors.toList()); - if (clientFileUrl != null && clientFileUrl.size() > 0) { + if (clientFileUrl != null && !clientFileUrl.isEmpty()) { fileJson.put(fileKey, clientFileUrl); } } diff --git a/src/main/java/au/com/royalpay/payment/manage/customers/core/impls/CouponValidateServiceImpl.java b/src/main/java/au/com/royalpay/payment/manage/customers/core/impls/CouponValidateServiceImpl.java index 9cc652ff0..5163f7f79 100644 --- a/src/main/java/au/com/royalpay/payment/manage/customers/core/impls/CouponValidateServiceImpl.java +++ b/src/main/java/au/com/royalpay/payment/manage/customers/core/impls/CouponValidateServiceImpl.java @@ -7,9 +7,9 @@ import au.com.royalpay.payment.manage.mappers.system.CustomerMapper; import au.com.royalpay.payment.manage.merchants.core.ClientManager; import au.com.royalpay.payment.tools.exceptions.BadRequestException; import au.com.royalpay.payment.tools.exceptions.NotFoundException; - +import cn.yixblog.platform.http.HttpRequestGenerator; +import cn.yixblog.platform.http.HttpRequestResult; import com.alibaba.fastjson.JSONObject; - import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.lang3.time.DateUtils; import org.apache.http.NameValuePair; @@ -21,15 +21,11 @@ import org.springframework.stereotype.Service; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.util.UriComponentsBuilder; +import javax.annotation.Resource; import java.util.ArrayList; import java.util.Date; import java.util.List; -import javax.annotation.Resource; - -import cn.yixblog.platform.http.HttpRequestGenerator; -import cn.yixblog.platform.http.HttpRequestResult; - /** * Created by yuan on 2017/10/10. @@ -251,7 +247,7 @@ public class CouponValidateServiceImpl implements CouponValidateService { } // 获取万圣节活动当天支付成功的订单 JSONObject result = null; - if (orderList != null && orderList.size() > 0) { + if (orderList != null && !orderList.isEmpty()) { result = new JSONObject(); result.put("orderList", orderList); for (JSONObject order : orderList) { diff --git a/src/main/java/au/com/royalpay/payment/manage/customers/core/impls/EncourageUseProcessor.java b/src/main/java/au/com/royalpay/payment/manage/customers/core/impls/EncourageUseProcessor.java index 9576ad6b2..8e13ac3b4 100644 --- a/src/main/java/au/com/royalpay/payment/manage/customers/core/impls/EncourageUseProcessor.java +++ b/src/main/java/au/com/royalpay/payment/manage/customers/core/impls/EncourageUseProcessor.java @@ -21,12 +21,10 @@ import au.com.royalpay.payment.tools.exceptions.BadRequestException; import au.com.royalpay.payment.tools.exceptions.NotFoundException; import au.com.royalpay.payment.tools.permission.enums.ManagerRole; import au.com.royalpay.payment.tools.utils.PageListUtils; - import com.alibaba.fastjson.JSONObject; import com.github.miemiedev.mybatis.paginator.domain.Order; import com.github.miemiedev.mybatis.paginator.domain.PageBounds; import com.github.miemiedev.mybatis.paginator.domain.PageList; - import org.apache.commons.lang3.RandomUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.time.DateFormatUtils; @@ -37,13 +35,13 @@ import org.springframework.cache.annotation.Cacheable; import org.springframework.core.Ordered; import org.springframework.stereotype.Service; +import javax.annotation.Resource; import java.math.BigDecimal; +import java.math.RoundingMode; import java.util.Calendar; import java.util.Date; import java.util.List; -import javax.annotation.Resource; - /** * 鼓励金 Created by yixian on 2017-04-24. */ @@ -178,7 +176,7 @@ public class EncourageUseProcessor implements Ordered, EncourageService { } int rand = RandomUtils.nextInt(0, config.getBigDecimal("max_amount").subtract(config.getBigDecimal("min_amount")).multiply(CommonConsts.HUNDRED).intValue()); - BigDecimal amount = config.getBigDecimal("min_amount").add(BigDecimal.valueOf(rand).divide(CommonConsts.HUNDRED, 2, BigDecimal.ROUND_DOWN)); + BigDecimal amount = config.getBigDecimal("min_amount").add(BigDecimal.valueOf(rand).divide(CommonConsts.HUNDRED, 2, RoundingMode.DOWN)); customerMembershipMapper.addEncourage(memberId, amount); JSONObject customer = customerMembershipMapper.findByMemberId(memberId); JSONObject accessLog = new JSONObject(); @@ -219,8 +217,8 @@ public class EncourageUseProcessor implements Ordered, EncourageService { int critRate = config.getIntValue("crit_rate"); if (RandomUtils.nextInt(0, 100) < critRate) { int factorInt = RandomUtils.nextInt(0, config.getBigDecimal("max_crit").multiply(CommonConsts.HUNDRED).intValue() - 100); - BigDecimal factor = BigDecimal.valueOf(factorInt + 100).divide(CommonConsts.HUNDRED, 2, BigDecimal.ROUND_DOWN); - BigDecimal actural = log.getBigDecimal("access_amount").multiply(factor).setScale(2, BigDecimal.ROUND_DOWN); + BigDecimal factor = BigDecimal.valueOf(factorInt + 100).divide(CommonConsts.HUNDRED, 2, RoundingMode.DOWN); + BigDecimal actural = log.getBigDecimal("access_amount").multiply(factor).setScale(2, RoundingMode.DOWN); BigDecimal sub = actural.subtract(log.getBigDecimal("actural_amount")); customerMembershipMapper.addEncourage(log.getString("member_id"), sub); JSONObject customer = customerMembershipMapper.findByMemberId(log.getString("member_id")); @@ -252,7 +250,7 @@ public class EncourageUseProcessor implements Ordered, EncourageService { if(use!=null){ balance = use.getBigDecimal("use_amount"); } - member.put("used_amount",balance.setScale(2, BigDecimal.ROUND_DOWN).toPlainString()); + member.put("used_amount", balance.setScale(2, RoundingMode.DOWN).toPlainString()); if (member != null) { status.put("member_info", member); List balanceLogs = customerMembershipMapper.listEncourageBalanceHistory(fromDate, toDate, member.getString("member_id")); diff --git a/src/main/java/au/com/royalpay/payment/manage/dev/core/impl/AliforexcelServiceImpl.java b/src/main/java/au/com/royalpay/payment/manage/dev/core/impl/AliforexcelServiceImpl.java index 2321a83e7..b81534c34 100644 --- a/src/main/java/au/com/royalpay/payment/manage/dev/core/impl/AliforexcelServiceImpl.java +++ b/src/main/java/au/com/royalpay/payment/manage/dev/core/impl/AliforexcelServiceImpl.java @@ -496,7 +496,7 @@ public class AliforexcelServiceImpl implements AliforexcelService { clientConfig.put("client_id", partner.getIntValue("client_id")); clientConfig.put("client_moniker", partner.getString("client_moniker")); List gateways = orderMapper.listGatewayByClientId(partner.getIntValue("client_id")); - if (gateways.size() == 0) { + if (gateways.isEmpty()) { unOrdersPartner(partner, clientConfig); continue; } diff --git a/src/main/java/au/com/royalpay/payment/manage/dev/listeners/recognizers/PaymentAmountCheatMonitor.java b/src/main/java/au/com/royalpay/payment/manage/dev/listeners/recognizers/PaymentAmountCheatMonitor.java index 6d5dfff1d..c20ecf12e 100644 --- a/src/main/java/au/com/royalpay/payment/manage/dev/listeners/recognizers/PaymentAmountCheatMonitor.java +++ b/src/main/java/au/com/royalpay/payment/manage/dev/listeners/recognizers/PaymentAmountCheatMonitor.java @@ -7,11 +7,11 @@ import au.com.royalpay.payment.manage.dev.listeners.WarningSenderHelper; import au.com.royalpay.payment.manage.mappers.payment.OrderMapper; import au.com.royalpay.payment.manage.mappers.system.ClientMapper; import au.com.royalpay.payment.manage.mappers.system.ManagerMapper; -import au.com.royalpay.payment.tools.permission.enums.ManagerRole; import au.com.royalpay.payment.tools.CommonConsts; import au.com.royalpay.payment.tools.connections.mpsupport.MpWechatApi; import au.com.royalpay.payment.tools.connections.mpsupport.MpWechatApiProvider; import au.com.royalpay.payment.tools.connections.mpsupport.beans.TemplateMessage; +import au.com.royalpay.payment.tools.permission.enums.ManagerRole; import com.alibaba.fastjson.JSONObject; import com.github.miemiedev.mybatis.paginator.domain.Order; import com.github.miemiedev.mybatis.paginator.domain.PageBounds; @@ -23,6 +23,7 @@ import org.springframework.stereotype.Component; import javax.annotation.Resource; import java.math.BigDecimal; +import java.math.RoundingMode; import java.util.*; @Component @@ -87,7 +88,7 @@ public class PaymentAmountCheatMonitor implements CheatMonitor { logger.debug("order count:" + cleaned.size() + " is less than min orders, skip"); return; } - BigDecimal percentage = BigDecimal.valueOf(orderCount).multiply(CommonConsts.HUNDRED).divide(BigDecimal.valueOf(cleaned.size()), 2, BigDecimal.ROUND_DOWN); + BigDecimal percentage = BigDecimal.valueOf(orderCount).multiply(CommonConsts.HUNDRED).divide(BigDecimal.valueOf(cleaned.size()), 2, RoundingMode.DOWN); if (percentage.compareTo(sysConfig.getBigDecimal("cheat_monitor.warning_rate")) > 0) { JSONObject client = clientMapper.findClient(order.getIntValue("client_id")); String clientMoniker = client.getString("client_moniker"); diff --git a/src/main/java/au/com/royalpay/payment/manage/dev/web/TestController.java b/src/main/java/au/com/royalpay/payment/manage/dev/web/TestController.java index fcdf0bccf..acfe399d9 100644 --- a/src/main/java/au/com/royalpay/payment/manage/dev/web/TestController.java +++ b/src/main/java/au/com/royalpay/payment/manage/dev/web/TestController.java @@ -53,8 +53,8 @@ import org.joda.time.DateTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; -import org.springframework.ui.Model; import org.springframework.data.mongodb.core.MongoTemplate; +import org.springframework.ui.Model; import org.springframework.util.Assert; import org.springframework.validation.Errors; import org.springframework.web.bind.annotation.*; @@ -67,7 +67,7 @@ import javax.validation.Valid; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; -import java.math.BigDecimal; +import java.math.RoundingMode; import java.net.URISyntaxException; import java.text.ParseException; import java.text.SimpleDateFormat; @@ -157,7 +157,7 @@ public class TestController { if (rate == null) { throw new BadRequestException("The Partner's Rate is not config!"); } - client.put("rate_value", rate.getBigDecimal("rate_value").setScale(2, BigDecimal.ROUND_DOWN)); + client.put("rate_value", rate.getBigDecimal("rate_value").setScale(2, RoundingMode.DOWN)); client.put("clean", "T+" + rate.getString("clean_days")); client.put("clean_days", rate.getString("clean_days")); JSONObject account = getBankAccountByClientId(client.getIntValue("client_id")); @@ -209,18 +209,18 @@ public class TestController { if (weChatRate == null) { throw new BadRequestException("The Partner's Rate is not config!"); } - client.put("wechat_rate", weChatRate.getBigDecimal("rate_value").setScale(2, BigDecimal.ROUND_DOWN)); + client.put("wechat_rate", weChatRate.getBigDecimal("rate_value").setScale(2, RoundingMode.DOWN)); client.put("clean", "T+" + weChatRate.getString("clean_days")); client.put("clean_days", weChatRate.getString("clean_days")); try { JSONObject alipayRate = merchantInfoProvider.clientCurrentRate(client.getIntValue("client_id"), new Date(), "Alipay"); if (alipayRate != null) { - client.put("alipay_rate", alipayRate.getBigDecimal("rate_value").setScale(2, BigDecimal.ROUND_DOWN)); + client.put("alipay_rate", alipayRate.getBigDecimal("rate_value").setScale(2, RoundingMode.DOWN)); } JSONObject alipayOnlineRate = merchantInfoProvider.clientCurrentRate(client.getIntValue("client_id"), new Date(), "AlipayOnline"); if (alipayOnlineRate != null) { - client.put("alipay_online_rate", alipayOnlineRate.getBigDecimal("rate_value").setScale(2, BigDecimal.ROUND_DOWN)); + client.put("alipay_online_rate", alipayOnlineRate.getBigDecimal("rate_value").setScale(2, RoundingMode.DOWN)); } } catch (Exception ignored) { //do nothing diff --git a/src/main/java/au/com/royalpay/payment/manage/fund/beans/XPlanFundConfig.java b/src/main/java/au/com/royalpay/payment/manage/fund/beans/XPlanFundConfig.java index ca2e953b4..5a80cc3dc 100644 --- a/src/main/java/au/com/royalpay/payment/manage/fund/beans/XPlanFundConfig.java +++ b/src/main/java/au/com/royalpay/payment/manage/fund/beans/XPlanFundConfig.java @@ -4,6 +4,7 @@ import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.annotation.JSONField; import java.math.BigDecimal; +import java.math.RoundingMode; /** * Create by yixian at 2017-09-05 19:09 @@ -35,9 +36,9 @@ public class XPlanFundConfig { public static XPlanFundConfig fromSysConfig(JSONObject sysConfig) { XPlanFundConfig conf = new XPlanFundConfig(); - conf.setInterestRate(sysConfig.getBigDecimal("fund.x-plan.interest-rate").setScale(4,BigDecimal.ROUND_DOWN)); + conf.setInterestRate(sysConfig.getBigDecimal("fund.x-plan.interest-rate").setScale(4, RoundingMode.DOWN)); conf.setAutoJoin(sysConfig.getBooleanValue("fund.x-plan.auto-join-enabled")); - conf.setMaxAmount(sysConfig.getBigDecimal("fund.x-plan.max-money").setScale(2,BigDecimal.ROUND_DOWN)); + conf.setMaxAmount(sysConfig.getBigDecimal("fund.x-plan.max-money").setScale(2, RoundingMode.DOWN)); conf.setTradeRule(sysConfig.getString("fund.x-plan.trade-rule")); conf.setWithdrawRule(sysConfig.getString("fund.x-plan.withdraw-rule")); conf.setInterestRule(sysConfig.getString("fund.x-plan.interest-rule")); diff --git a/src/main/java/au/com/royalpay/payment/manage/fund/core/impls/FundsConfigServiceImpl.java b/src/main/java/au/com/royalpay/payment/manage/fund/core/impls/FundsConfigServiceImpl.java index 01dd941ce..902632d97 100644 --- a/src/main/java/au/com/royalpay/payment/manage/fund/core/impls/FundsConfigServiceImpl.java +++ b/src/main/java/au/com/royalpay/payment/manage/fund/core/impls/FundsConfigServiceImpl.java @@ -6,7 +6,7 @@ import com.alibaba.fastjson.JSONObject; import org.springframework.stereotype.Service; import javax.annotation.Resource; -import java.math.BigDecimal; +import java.math.RoundingMode; import java.util.List; /** @@ -25,7 +25,7 @@ public class FundsConfigServiceImpl implements FundsConfigService { switch (conf.getIntValue("type_desc")) { case 1: case 2: - conf.put("rate", conf.getBigDecimal("rate").setScale(2, BigDecimal.ROUND_DOWN).toPlainString() + "%"); + conf.put("rate", conf.getBigDecimal("rate").setScale(2, RoundingMode.DOWN).toPlainString() + "%"); break; } } diff --git a/src/main/java/au/com/royalpay/payment/manage/fund/core/impls/XPlanFundConfigServiceImpl.java b/src/main/java/au/com/royalpay/payment/manage/fund/core/impls/XPlanFundConfigServiceImpl.java index 56ee61c21..9c444d9aa 100644 --- a/src/main/java/au/com/royalpay/payment/manage/fund/core/impls/XPlanFundConfigServiceImpl.java +++ b/src/main/java/au/com/royalpay/payment/manage/fund/core/impls/XPlanFundConfigServiceImpl.java @@ -15,22 +15,19 @@ import au.com.royalpay.payment.tools.env.SysConfigManager; import au.com.royalpay.payment.tools.exceptions.BadRequestException; import au.com.royalpay.payment.tools.exceptions.ForbiddenException; import au.com.royalpay.payment.tools.utils.PageListUtils; - import com.alibaba.fastjson.JSONObject; import com.github.miemiedev.mybatis.paginator.domain.Order; import com.github.miemiedev.mybatis.paginator.domain.PageBounds; import com.github.miemiedev.mybatis.paginator.domain.PageList; - import org.springframework.stereotype.Service; +import javax.annotation.Resource; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.ArrayList; import java.util.Date; import java.util.List; -import javax.annotation.Resource; - /** * Create by yixian at 2017-09-14 17:33 */ @@ -114,7 +111,7 @@ public class XPlanFundConfigServiceImpl implements XPlanFundConfigService { } public static BigDecimal calculateInterest(BigDecimal interestRate, BigDecimal amount) { - return amount.multiply(interestRate.divide(CommonConsts.HUNDRED, 4, BigDecimal.ROUND_DOWN)).divide(BigDecimal.valueOf(365), 2, RoundingMode.HALF_UP); + return amount.multiply(interestRate.divide(CommonConsts.HUNDRED, 4, RoundingMode.DOWN)).divide(BigDecimal.valueOf(365), 2, RoundingMode.HALF_UP); } private JSONObject getClient(String clientMoniker) { diff --git a/src/main/java/au/com/royalpay/payment/manage/gateway/advice/Gtw2SignAspect.java b/src/main/java/au/com/royalpay/payment/manage/gateway/advice/Gtw2SignAspect.java index e87b87e53..e35834636 100644 --- a/src/main/java/au/com/royalpay/payment/manage/gateway/advice/Gtw2SignAspect.java +++ b/src/main/java/au/com/royalpay/payment/manage/gateway/advice/Gtw2SignAspect.java @@ -6,6 +6,7 @@ import au.com.royalpay.payment.core.exceptions.ParamInvalidException; import au.com.royalpay.payment.core.exceptions.SignInvalidException; import au.com.royalpay.payment.manage.mappers.system.OrgSignInfoMapper; import au.com.royalpay.payment.tools.exceptions.ServerErrorException; +import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.serializer.SerializerFeature; import org.apache.commons.codec.binary.Base64; @@ -83,7 +84,7 @@ public class Gtw2SignAspect { for (Object arg : requestArgs) { try { if (arg instanceof JSONObject) { - requestBody = JSONObject.parseObject(arg.toString()); + requestBody = JSON.parseObject(arg.toString()); } } catch (Exception e) { throw new ParamInvalidException("Request Body", "error.payment.valid.invalid_param"); @@ -102,7 +103,7 @@ public class Gtw2SignAspect { throw new SignInvalidException(); } Object result = pjp.proceed(); - JSONObject data = JSONObject.parseObject(result.toString()); + JSONObject data = JSON.parseObject(result.toString()); return buildResponseData(pathVariables.get("shortId"), requestUrl, data); } diff --git a/src/main/java/au/com/royalpay/payment/manage/gateway/core/impls/GatewayMerchantApplyImpl.java b/src/main/java/au/com/royalpay/payment/manage/gateway/core/impls/GatewayMerchantApplyImpl.java index 864cc38de..18be11791 100644 --- a/src/main/java/au/com/royalpay/payment/manage/gateway/core/impls/GatewayMerchantApplyImpl.java +++ b/src/main/java/au/com/royalpay/payment/manage/gateway/core/impls/GatewayMerchantApplyImpl.java @@ -123,7 +123,7 @@ public class GatewayMerchantApplyImpl implements GatewayMerchantApply { ClientAuthFilesInfo clientAuthFilesInfo = registerBean.insertClientComplianceInfo(); clientManager.uploadAuthFiles(manager, client.getString("client_moniker"), clientAuthFilesInfo); - JSONObject rateConfig = registerBean.insertClientRateInfo(JSONObject.parseObject(sysConfigManager.getSysConfig().getString("sys_rates"))); + JSONObject rateConfig = registerBean.insertClientRateInfo(JSON.parseObject(sysConfigManager.getSysConfig().getString("sys_rates"))); clientManager.newConfigRate(manager, client.getString("client_moniker"), rateConfig); clientManager.commitToCompliance(client.getString("client_moniker"), manager); result.put("partner_code", client.getString("client_moniker")); diff --git a/src/main/java/au/com/royalpay/payment/manage/kyc/core/impls/KycServiceImpl.java b/src/main/java/au/com/royalpay/payment/manage/kyc/core/impls/KycServiceImpl.java index 3a5b554ac..dbe16abbe 100644 --- a/src/main/java/au/com/royalpay/payment/manage/kyc/core/impls/KycServiceImpl.java +++ b/src/main/java/au/com/royalpay/payment/manage/kyc/core/impls/KycServiceImpl.java @@ -129,7 +129,7 @@ public class KycServiceImpl implements KycService { ctx.setVariable("contact_email", client.getString("contact_email")); ctx.setVariable("submit_time", DateFormatUtils.format(complianceInfo.getDate("submit_time"),"yyyy-MM-dd HH:mm:ss")); final String content = thymeleaf.process("mail/kyc_email_notice", ctx); - if (emails.size() > 0) { + if (!emails.isEmpty()) { royalThreadPoolExecutor.execute(() -> { try { mailService.sendEmail("[RoyalPay]商户需要您协助补充KYC材料,请尽快查看", StringUtils.join(emails, ","), "", content); @@ -138,7 +138,7 @@ public class KycServiceImpl implements KycService { } }); } - if (openIds.size() > 0) { + if (!openIds.isEmpty()) { for (String openId : openIds) { try { MpWechatApi mpWechatApi = mpWechatApiProvider.getApiFromOpenId(openId); @@ -223,7 +223,7 @@ public class KycServiceImpl implements KycService { } int sourceEnum = 2; List clientAllAuthFiles = clientFilesMapper.findAllClientFile(client.getIntValue("client_id")); - if (clientAllAuthFiles == null || clientAllAuthFiles.size() == 0) { + if (clientAllAuthFiles == null || clientAllAuthFiles.isEmpty()) { throw new BadRequestException("Please check the information is uploaded completely"); } if (StringUtils.isNotBlank(account.getString("beneficiary_id_title"))) { diff --git a/src/main/java/au/com/royalpay/payment/manage/management/clearing/core/impl/CleanServiceImpl.java b/src/main/java/au/com/royalpay/payment/manage/management/clearing/core/impl/CleanServiceImpl.java index c40760d8d..c0cee2321 100644 --- a/src/main/java/au/com/royalpay/payment/manage/management/clearing/core/impl/CleanServiceImpl.java +++ b/src/main/java/au/com/royalpay/payment/manage/management/clearing/core/impl/CleanServiceImpl.java @@ -1104,7 +1104,7 @@ public class CleanServiceImpl implements CleanService, ManagerTodoNoticeProvider } else { row.createCell(6, Cell.CELL_TYPE_STRING).setCellValue("-"); } - row.createCell(7, Cell.CELL_TYPE_STRING).setCellValue(settle.getBigDecimal("exchange_rate").setScale(5, BigDecimal.ROUND_DOWN).toPlainString()); + row.createCell(7, Cell.CELL_TYPE_STRING).setCellValue(settle.getBigDecimal("exchange_rate").setScale(5, RoundingMode.DOWN).toPlainString()); cell = row.createCell(8, Cell.CELL_TYPE_STRING); cell.setCellValue(settle.getString("transaction_type")); cell.setCellStyle(!"Credit".equals(settle.getString("transaction_type")) ? analysisStyle2 : null); @@ -1112,20 +1112,20 @@ public class CleanServiceImpl implements CleanService, ManagerTodoNoticeProvider cell = row.createCell(10, Cell.CELL_TYPE_STRING); cell.setCellValue(settle.getBigDecimal("display_amount") == null ? "" : "Credit".equals(settle.getString("transaction_type")) ? - settle.getBigDecimal("display_amount").setScale(2, BigDecimal.ROUND_DOWN).toPlainString() : - "-" + settle.getBigDecimal("display_amount").setScale(2, BigDecimal.ROUND_DOWN).toPlainString()); + settle.getBigDecimal("display_amount").setScale(2, RoundingMode.DOWN).toPlainString() : + "-" + settle.getBigDecimal("display_amount").setScale(2, RoundingMode.DOWN).toPlainString()); cell.setCellStyle(!"Credit".equals(settle.getString("transaction_type")) ? analysisStyle2 : null); cell = row.createCell(11, Cell.CELL_TYPE_STRING); cell.setCellValue(settle.getBigDecimal("transaction_amount") == null ? "" : "Credit".equals(settle.getString("transaction_type")) ? - settle.getBigDecimal("transaction_amount").setScale(2, BigDecimal.ROUND_DOWN).toPlainString() : - "-" + settle.getBigDecimal("transaction_amount").setScale(2, BigDecimal.ROUND_DOWN).toPlainString()); + settle.getBigDecimal("transaction_amount").setScale(2, RoundingMode.DOWN).toPlainString() : + "-" + settle.getBigDecimal("transaction_amount").setScale(2, RoundingMode.DOWN).toPlainString()); cell.setCellStyle(!"Credit".equals(settle.getString("transaction_type")) ? analysisStyle2 : null); cell = row.createCell(12, Cell.CELL_TYPE_STRING); cell.setCellValue(settle.getBigDecimal("clearing_amount") == null ? "" : "Credit".equals(settle.getString("transaction_type")) ? - settle.getBigDecimal("clearing_amount").setScale(2, BigDecimal.ROUND_DOWN).toPlainString() : - "-" + settle.getBigDecimal("clearing_amount").setScale(2, BigDecimal.ROUND_DOWN).toPlainString()); + settle.getBigDecimal("clearing_amount").setScale(2, RoundingMode.DOWN).toPlainString() : + "-" + settle.getBigDecimal("clearing_amount").setScale(2, RoundingMode.DOWN).toPlainString()); cell.setCellStyle(!"Credit".equals(settle.getString("transaction_type")) ? analysisStyle2 : null); row.createCell(13, Cell.CELL_TYPE_STRING).setCellValue(channels.getString(settle.getString("channel")) == null ? "" : channels.getJSONObject(settle.getString("channel")).getBigDecimal("rate").toPlainString() + "%"); @@ -1137,8 +1137,8 @@ public class CleanServiceImpl implements CleanService, ManagerTodoNoticeProvider cell = row.createCell(16, Cell.CELL_TYPE_STRING); cell.setCellValue(settle.getBigDecimal("settle_amount") == null ? "" : "Credit".equals(settle.getString("transaction_type")) ? - settle.getBigDecimal("settle_amount").setScale(2, BigDecimal.ROUND_DOWN).toPlainString() : - "-" + settle.getBigDecimal("settle_amount").setScale(2, BigDecimal.ROUND_DOWN).toPlainString()); + settle.getBigDecimal("settle_amount").setScale(2, RoundingMode.DOWN).toPlainString() : + "-" + settle.getBigDecimal("settle_amount").setScale(2, RoundingMode.DOWN).toPlainString()); cell.setCellStyle(!"Credit".equals(settle.getString("transaction_type")) ? analysisStyle2 : null); row.createCell(17, Cell.CELL_TYPE_STRING).setCellValue(settle.containsKey("order_detail") ? settle.getString("order_detail") : settle.getString("remark")); String clientDevId = StringUtils.defaultString(settle.getString("dev_id"), "-"); @@ -1226,7 +1226,7 @@ public class CleanServiceImpl implements CleanService, ManagerTodoNoticeProvider } else { row.createCell(6, Cell.CELL_TYPE_STRING).setCellValue("-"); } - row.createCell(7, Cell.CELL_TYPE_STRING).setCellValue(settle.getBigDecimal("exchange_rate").setScale(5, BigDecimal.ROUND_DOWN).toPlainString()); + row.createCell(7, Cell.CELL_TYPE_STRING).setCellValue(settle.getBigDecimal("exchange_rate").setScale(5, RoundingMode.DOWN).toPlainString()); cell = row.createCell(8, Cell.CELL_TYPE_STRING); cell.setCellValue(settle.getString("transaction_type")); cell.setCellStyle(!"Credit".equals(settle.getString("transaction_type")) ? analysisStyle2 : null); @@ -1234,20 +1234,20 @@ public class CleanServiceImpl implements CleanService, ManagerTodoNoticeProvider cell = row.createCell(10, Cell.CELL_TYPE_STRING); cell.setCellValue(settle.getBigDecimal("display_amount") == null ? "" : "Credit".equals(settle.getString("transaction_type")) ? - settle.getBigDecimal("display_amount").setScale(2, BigDecimal.ROUND_DOWN).toPlainString() : - "-" + settle.getBigDecimal("display_amount").setScale(2, BigDecimal.ROUND_DOWN).toPlainString()); + settle.getBigDecimal("display_amount").setScale(2, RoundingMode.DOWN).toPlainString() : + "-" + settle.getBigDecimal("display_amount").setScale(2, RoundingMode.DOWN).toPlainString()); cell.setCellStyle(!"Credit".equals(settle.getString("transaction_type")) ? analysisStyle2 : null); cell = row.createCell(11, Cell.CELL_TYPE_STRING); cell.setCellValue(settle.getBigDecimal("transaction_amount") == null ? "" : "Credit".equals(settle.getString("transaction_type")) ? - settle.getBigDecimal("transaction_amount").setScale(2, BigDecimal.ROUND_DOWN).toPlainString() : - "-" + settle.getBigDecimal("transaction_amount").setScale(2, BigDecimal.ROUND_DOWN).toPlainString()); + settle.getBigDecimal("transaction_amount").setScale(2, RoundingMode.DOWN).toPlainString() : + "-" + settle.getBigDecimal("transaction_amount").setScale(2, RoundingMode.DOWN).toPlainString()); cell.setCellStyle(!"Credit".equals(settle.getString("transaction_type")) ? analysisStyle2 : null); cell = row.createCell(12, Cell.CELL_TYPE_STRING); cell.setCellValue(settle.getBigDecimal("clearing_amount") == null ? "" : "Credit".equals(settle.getString("transaction_type")) ? - settle.getBigDecimal("clearing_amount").setScale(2, BigDecimal.ROUND_DOWN).toPlainString() : - "-" + settle.getBigDecimal("clearing_amount").setScale(2, BigDecimal.ROUND_DOWN).toPlainString()); + settle.getBigDecimal("clearing_amount").setScale(2, RoundingMode.DOWN).toPlainString() : + "-" + settle.getBigDecimal("clearing_amount").setScale(2, RoundingMode.DOWN).toPlainString()); cell.setCellStyle(!"Credit".equals(settle.getString("transaction_type")) ? analysisStyle2 : null); row.createCell(13, Cell.CELL_TYPE_STRING).setCellValue(channels.getString(settle.getString("channel")) == null ? "" : channels.getJSONObject(settle.getString("channel")).getBigDecimal("rate").toPlainString() + "%"); @@ -1259,8 +1259,8 @@ public class CleanServiceImpl implements CleanService, ManagerTodoNoticeProvider cell = row.createCell(16, Cell.CELL_TYPE_STRING); cell.setCellValue(settle.getBigDecimal("settle_amount") == null ? "" : "Credit".equals(settle.getString("transaction_type")) ? - settle.getBigDecimal("settle_amount").setScale(2, BigDecimal.ROUND_DOWN).toPlainString() : - "-" + settle.getBigDecimal("settle_amount").setScale(2, BigDecimal.ROUND_DOWN).toPlainString()); + settle.getBigDecimal("settle_amount").setScale(2, RoundingMode.DOWN).toPlainString() : + "-" + settle.getBigDecimal("settle_amount").setScale(2, RoundingMode.DOWN).toPlainString()); cell.setCellStyle(!"Credit".equals(settle.getString("transaction_type")) ? analysisStyle2 : null); row.createCell(17, Cell.CELL_TYPE_STRING).setCellValue(settle.getString("order_detail")); String clientDevId = StringUtils.defaultString(settle.getString("dev_id"), "-"); diff --git a/src/main/java/au/com/royalpay/payment/manage/merchantid/core/impl/MerchantIdManageServiceImpl.java b/src/main/java/au/com/royalpay/payment/manage/merchantid/core/impl/MerchantIdManageServiceImpl.java index c30c83d22..21acde64b 100644 --- a/src/main/java/au/com/royalpay/payment/manage/merchantid/core/impl/MerchantIdManageServiceImpl.java +++ b/src/main/java/au/com/royalpay/payment/manage/merchantid/core/impl/MerchantIdManageServiceImpl.java @@ -90,8 +90,8 @@ public class MerchantIdManageServiceImpl implements MerchantIdManageService { } Map> merchantIdMap = clients.stream().filter(t->t.containsKey("merchant_id")).filter(t->t.containsKey("sub_merchant_id")).collect(Collectors.groupingBy(t->t.getString("merchant_id"))); JSONObject returnJason = new JSONObject(); - returnJason.put("merchant_id_map",merchantIdMap); - returnJason.put("refresh_time",clients.size()>0?clients.get(0).getDate("create_time"):""); + returnJason.put("merchant_id_map", merchantIdMap); + returnJason.put("refresh_time", !clients.isEmpty() ? clients.get(0).getDate("create_time") : ""); return returnJason; } @@ -99,7 +99,7 @@ public class MerchantIdManageServiceImpl implements MerchantIdManageService { public void generateClientsSunMerchantId() { //重构未交易商户号逻辑 List clients = clientAnalysisMapper.tradeSubMerchantIdBy60Days(DateUtils.addDays(new Date(), -60)); - if (clients.size() > 0) { + if (!clients.isEmpty()) { clientSubMerchantIdMapper.deleteAll(); } for (JSONObject client: clients) { diff --git a/src/main/java/au/com/royalpay/payment/manage/merchants/core/impls/ClientManagerImpl.java b/src/main/java/au/com/royalpay/payment/manage/merchants/core/impls/ClientManagerImpl.java index 6e6f13c8b..c939da170 100644 --- a/src/main/java/au/com/royalpay/payment/manage/merchants/core/impls/ClientManagerImpl.java +++ b/src/main/java/au/com/royalpay/payment/manage/merchants/core/impls/ClientManagerImpl.java @@ -364,13 +364,13 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid @Override public JSONObject getSysRateConfig() { String rateConfig = sysConfigManager.getSysConfig().getString("sys_rates"); - return JSONObject.parseObject(rateConfig); + return JSON.parseObject(rateConfig); } @Override public JSONObject getSysCardRateConfig() { String rateConfig = sysConfigManager.getSysConfig().getString("sys_card_rates"); - return JSONObject.parseObject(rateConfig); + return JSON.parseObject(rateConfig); } @Override @@ -447,7 +447,7 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid if (ManagerRole.OPERATOR.hasRole(role)) { List log = logClientSubMerchantIdMapper.listLogsByClientId(client.getInteger("client_id"), new PageBounds(Order.formString("create_time.desc"))); - client.put("sub_merchant_id_log", log.size() > 0); + client.put("sub_merchant_id_log", !log.isEmpty()); } if (ManagerRole.BD_USER.hasRole(role)) { int checkBDPermission = clientBDMapper.checkBDPermission(client.getIntValue("client_id"), manager.getString("manager_id")); @@ -728,7 +728,7 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid param.put("type", 0); List orgIds = new ArrayList<>(); List childOrgs = orgMapper.listOrgsWithChid(param); - if (childOrgs.size() > 0) { + if (!childOrgs.isEmpty()) { for (JSONObject object : childOrgs) { orgIds.add(object.getIntValue("org_id")); } @@ -1206,7 +1206,7 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid createKycAuthStatus(manager, client); clientModifySupport.processClientConfigModify(new SwitchPermissionModify(manager, clientMoniker, "skip_clearing", false)); List accounts = clientAccountMapper.listAdminAccounts(clientId); - if (accounts != null && accounts.size() > 0) { + if (accounts != null && !accounts.isEmpty()) { sendInitEmail(client, accounts.get(0).getString("username"), "*******", true); } else { initAdminUserAndSendEmail(manager, clientMoniker, client, true); @@ -1306,7 +1306,7 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid // sendInitEmail(manager, client, account.getString("username"), "*****"); sendInitEmail(client, account.getString("username"), "*****", cardApproving); } else { - if (accounts.size() == 0) { + if (accounts.isEmpty()) { initAdminUserAndSendEmail(manager, clientMoniker, client, cardApproving); } else { JSONObject account = accounts.get(0); @@ -1540,7 +1540,7 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid int clientId = client.getIntValue("client_id"); List clientBankAccounts = clientBankAccountMapper.clientBankAccounts(clientId); - if (clientBankAccounts.size() > 0) { + if (!clientBankAccounts.isEmpty()) { isRiskyMerchant(client, clientBankAccounts.get(0)); } else { isRiskyMerchant(client, null); @@ -1599,7 +1599,7 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid private void checkPhoneAndWechatExist(NewAccountBean account) { List accounts = clientAccountMapper.findByPhone(account.getContactPhone(), account.getNation_code().startsWith("+") ? account.getNation_code() : "+" + account.getNation_code()); - if (accounts != null && accounts.size() > 0) { + if (accounts != null && !accounts.isEmpty()) { throw new BadRequestException("Mobile phone number has been bound to other accounts"); } } @@ -1867,7 +1867,7 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid rate.put("clean_days", clientConfig.getIntValue("clean_days")); } if (StringUtils.equalsIgnoreCase("rpaypmt_card", rate.getString("rate_name"))) { - JSONObject extRates = JSONObject.parseObject(rate.getString("ext_rates")); + JSONObject extRates = JSON.parseObject(rate.getString("ext_rates")); convertExtRateValueDataVersion(rate, extRates, "domestic_rate_value"); convertExtRateValueDataVersion(rate, extRates, "overseas_rate_value"); rate.put("ext_rates", extRates); @@ -1973,11 +1973,11 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid clientRateMapper.updateConfig(rateLog); } if (StringUtils.equalsIgnoreCase("rpaypmt_card", config.getString("type"))) { - JSONObject extRateParams = new JSONObject() {{ - put("domestic_rate_value", subRateObject(config.getBigDecimal("rate_value"), config.getIntValue("clean_days"))); + JSONObject extRateParams = JsonHelper.newJson(json -> { + json.put("domestic_rate_value", subRateObject(config.getBigDecimal("rate_value"), config.getIntValue("clean_days"))); JSONObject extRates = config.getJSONObject("ext_rates"); - put("overseas_rate_value", subRateObject(extRates.getBigDecimal("international_rate_value"), config.getIntValue("clean_days") + 1)); - }}; + json.put("overseas_rate_value", subRateObject(extRates.getBigDecimal("international_rate_value"), config.getIntValue("clean_days") + 1)); + }); newConfig.put("ext_rates", extRateParams.toJSONString()); } if ("cb_bankpay".equalsIgnoreCase(channel)) { @@ -1987,7 +1987,7 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid } else { clientRateMapper.saveRate(newConfig); } - logger.info(clientId + "的" + channel + "费率设置成功"); + logger.info("{}的{}费率设置成功", clientId, channel); } } @@ -2041,7 +2041,6 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid throw new ForbiddenException("费率参数小于旗下商户最低" + rateName + "费率,请重新输入"); } - ; } } } @@ -2053,7 +2052,6 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid throw new ForbiddenException("费率参数小于旗下商户最低" + channel + "费率,请重新输入"); } - ; } } } @@ -2073,11 +2071,9 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid if (mchConfig.getBooleanValue("level3_mch_config")) { for (JSONObject partner : listChildClients) { List clients = clientMapper.listChildClients(partner.getIntValue("client_id")); - if (clients.size() > 0) { + if (!clients.isEmpty()) { partner.put("level3Clients", clients); - clients.forEach(e -> { - e.put("parent_client_moniker", partner.getString("client_moniker")); - }); + clients.forEach(e -> e.put("parent_client_moniker", partner.getString("client_moniker"))); } } } @@ -2094,9 +2090,7 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid PageBounds pageBounds; pageBounds = new PageBounds(page, 20, Order.formString("create_time.desc")); - JSONObject params = new JSONObject() {{ - put("parent_client_id", client.getIntValue("client_id")); - }}; + JSONObject params = JsonHelper.newJson(json -> json.put("parent_client_id", client.getIntValue("client_id"))); if (StringUtils.isNotBlank(searchText)) { params.put("search_text", searchText); } @@ -2105,11 +2099,9 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid if (mchConfig.getBooleanValue("level3_mch_config")) { for (JSONObject partner : childClients) { List clients = clientMapper.listChildClients(partner.getIntValue("client_id")); - if (clients.size() > 0) { + if (!clients.isEmpty()) { partner.put("level3Clients", clients); - clients.forEach(e -> { - e.put("parent_client_moniker", partner.getString("client_moniker")); - }); + clients.forEach(e -> e.put("parent_client_moniker", partner.getString("client_moniker"))); } } } @@ -2123,48 +2115,6 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid return clientMapper.listChildClients(clientId); } - // @Override - // @Transactional - // public void newSubClient(String clientMoniker, SubClientRegistry registry, JSONObject manager) { - // JSONObject client = getClientInfoByMoniker(clientMoniker); - // if (client == null) { - // throw new InvalidShortIdException(); - // } - // checkOrgPermission(manager, client); - // JSONObject subClient = registry.insertObject(); - // client.put("parent_client_id", client.getIntValue("client_id")); - // //解决子商户不能编辑 - // client.remove("client_id"); - // client.remove("approve_result"); - // client.remove("approver"); - // client.remove("approve_time"); - // client.remove("approve_email_id"); - // client.remove("approve_email_send"); - // client.putAll(subClient); - // client.put("create_time", new Date()); - // client.put("credential_code", RandomStringUtils.random(32, true, true)); - // client.put("creator", manager.getString("manager_id")); - // if (ManagerRole.OPERATOR.hasRole(manager.getIntValue("role"))) { - // client.put("approve_result", 1); - // client.put("approver", manager.getString("manager_id")); - // client.put("approve_time", new Date()); - // } - // if (clientMapper.findClientByMoniker(registry.getClientMoniker()) != null) { - // throw new BadRequestException("error.partner.valid.dumplicate_client_moniker"); - // } - // clientMapper.save(client); - // - // List client_bds = listClientCurrentBDUsers(manager, clientMoniker); - // if (!client_bds.isEmpty() && client_bds.size() > 0) { - // for (JSONObject client_bd : client_bds) { - // client_bd.put("client_id", client.getIntValue("client_id")); - // client_bd.remove("client_bd_id"); - // clientBDMapper.saveBD(client_bd); - // } - // } - // - // - // } @Override public void toggleAccountReceiveNoticeByOpenId(String openid, boolean enable) { @@ -2284,26 +2234,26 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid if (weChatRate == null) { throw new BadRequestException("The Partner's Rate is not config!"); } - client.put("wechat_rate", weChatRate.getBigDecimal("rate_value").setScale(2, BigDecimal.ROUND_DOWN)); + client.put("wechat_rate", weChatRate.getBigDecimal("rate_value").setScale(2, RoundingMode.DOWN)); client.put("clean", "T+" + weChatRate.getString("clean_days")); client.put("clean_days", weChatRate.getString("clean_days")); String rateConfig = sysConfigManager.getSysConfig().getString("sys_rates"); - JSONObject sysConfigRate = JSONObject.parseObject(rateConfig); + JSONObject sysConfigRate = JSON.parseObject(rateConfig); try { JSONObject alipayRate = merchantInfoProvider.clientCurrentRate(client.getIntValue("client_id"), new Date(), "Alipay"); if (alipayRate != null) { - client.put("alipay_rate", alipayRate.getBigDecimal("rate_value").setScale(2, BigDecimal.ROUND_DOWN)); + client.put("alipay_rate", alipayRate.getBigDecimal("rate_value").setScale(2, RoundingMode.DOWN)); } JSONObject alipayOnlineRate = merchantInfoProvider.clientCurrentRate(client.getIntValue("client_id"), new Date(), "AlipayOnline"); if (alipayOnlineRate != null) { - client.put("alipay_online_rate", alipayOnlineRate.getBigDecimal("rate_value").setScale(2, BigDecimal.ROUND_DOWN)); + client.put("alipay_online_rate", alipayOnlineRate.getBigDecimal("rate_value").setScale(2, RoundingMode.DOWN)); } JSONObject cbBankPayRate = merchantInfoProvider.clientCurrentRate(client.getIntValue("client_id"), new Date(), "CB_BankPay"); if (cbBankPayRate != null) { - client.put("cbbank_rate", cbBankPayRate.getBigDecimal("rate_value").setScale(2, BigDecimal.ROUND_DOWN)); + client.put("cbbank_rate", cbBankPayRate.getBigDecimal("rate_value").setScale(2, RoundingMode.DOWN)); } } catch (Exception ignored) { throw new BadRequestException("Merchant Rate Not Configure,Please Contact Customer Service"); @@ -2373,14 +2323,14 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid @Transactional public void updateBD(String manager_id, JSONObject data, JSONObject client) throws Exception { String type = data.getString("type").isEmpty() ? "add" : data.getString("type"); - List users = (List) data.get("users"); + List users = data.getJSONArray("users").toJavaList(JSONObject.class); JSONObject params = new JSONObject(); params.put("client_id", client.getIntValue("client_id")); params.put("end_date", null); params.put("is_valid", "1"); String start_date = DateFormatUtils.format(data.getDate("start_date"), "yyyy-MM-dd"); List listClientBDUsers = clientBDMapper.listClientDB(params, new PageBounds(Order.formString("create_time.desc"))); - if (!listClientBDUsers.isEmpty() && listClientBDUsers.size() > 0) { + if (!listClientBDUsers.isEmpty()) { JSONObject clientBDUser = listClientBDUsers.get(0); clientBDUser.put("end_date", start_date); if (type.equals("add") && (clientBDUser.getDate("end_date").getTime() < clientBDUser.getDate("start_date").getTime())) { @@ -2417,7 +2367,7 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid } BDUserModify bdUserModify = new BDUserModify(managerMapper.findById(manager_id), client.getString("client_moniker"), bd_id.substring(0, bd_id.length() - 1), bd_name.substring(0, bd_name.length() - 1)); - if (users.size() > 0) { + if (!users.isEmpty()) { String bd_manager_id = users.get(0).getString("manager_id"); JSONObject manager = managerMapper.findById(bd_manager_id); bdUserModify.setOrg_id(manager.getIntValue("org_id")); @@ -2455,9 +2405,7 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid @Override public String getQrCodeBoard(JSONObject client, QRCodeConfig config, JSONObject account, String plantform) { - // JSONObject org = orgMapper.findOne(client.getIntValue("org_id")); return merchantInfoProvider.getQrCodeBoard(client, config); - // return merchantInfoProvider.getQrCodeBoard(client, config,account,plantform); } @Override @@ -2680,9 +2628,7 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid queryModifyClientIds(client.getIntValue("client_id"), params); } List deviceIds = clientDeviceMapper.listClientDeviceIds(params); - return new JSONObject() {{ - put("data", deviceIds); - }}; + return JsonHelper.newJson(json -> json.put("data", deviceIds)); } @Override @@ -2889,7 +2835,7 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid if (rate == null) { throw new BadRequestException("The Partner's Rate is not config!"); } - client.put("rate_value", rate.getBigDecimal("rate_value").setScale(2, BigDecimal.ROUND_DOWN)); + client.put("rate_value", rate.getBigDecimal("rate_value").setScale(2, RoundingMode.DOWN)); client.put("clean", "T+" + rate.getString("clean_days")); client.put("clean_days", rate.getString("clean_days")); JSONObject account = getBankAccountByClientId(client.getIntValue("client_id")); @@ -2908,17 +2854,13 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid PdfUtils pdu = new PdfUtils(); pdu.setTemplatePdfPath(agreetemplatePdfPath); pdu.setPdfTemplate(client); - InputStream stream = null; - try { - File file = new File(clientMoniker + "_agreement.pdf"); - ByteArrayOutputStream bos = pdu.templetPdfBos(file); - stream = new ByteArrayInputStream(bos.toByteArray()); + File file = new File(clientMoniker + "_agreement.pdf"); + try (ByteArrayOutputStream bos = pdu.templetPdfBos(file); + InputStream stream = new ByteArrayInputStream(bos.toByteArray())) { JSONObject fileRes = attachmentClient.uploadFile(stream, clientMoniker + "_agreement.pdf", false); importAgreeFile(clientMoniker, manager, fileRes.getString("url"), false); } catch (Exception e) { logger.error("合同制作出现问题:", e); - } finally { - stream.close(); } } @@ -2947,18 +2889,18 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid if (weChatRate == null) { throw new BadRequestException("The Partner's Rate is not config!"); } - client.put("wechat_rate", weChatRate.getBigDecimal("rate_value").setScale(2, BigDecimal.ROUND_DOWN)); + client.put("wechat_rate", weChatRate.getBigDecimal("rate_value").setScale(2, RoundingMode.DOWN)); client.put("clean", "T+" + weChatRate.getString("clean_days")); client.put("clean_days", weChatRate.getString("clean_days")); try { JSONObject alipayRate = merchantInfoProvider.clientCurrentRate(client.getIntValue("client_id"), new Date(), "Alipay"); if (alipayRate != null) { - client.put("alipay_rate", alipayRate.getBigDecimal("rate_value").setScale(2, BigDecimal.ROUND_DOWN)); + client.put("alipay_rate", alipayRate.getBigDecimal("rate_value").setScale(2, RoundingMode.DOWN)); } JSONObject alipayOnlineRate = merchantInfoProvider.clientCurrentRate(client.getIntValue("client_id"), new Date(), "AlipayOnline"); if (alipayOnlineRate != null) { - client.put("alipay_online_rate", alipayOnlineRate.getBigDecimal("rate_value").setScale(2, BigDecimal.ROUND_DOWN)); + client.put("alipay_online_rate", alipayOnlineRate.getBigDecimal("rate_value").setScale(2, RoundingMode.DOWN)); } } catch (Exception ignored) { // do nothing @@ -3055,13 +2997,13 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid clientRate.forEach((p) -> { String rate_name = p.getString("rate_name"); if ("Wechat".equals(rate_name)) { - client.put("wechat_rate", p.getBigDecimal("rate_value").setScale(2, BigDecimal.ROUND_DOWN)); + client.put("wechat_rate", p.getBigDecimal("rate_value").setScale(2, RoundingMode.DOWN)); client.put("clean", "T+" + p.getString("clean_days")); client.put("clean_days", p.getString("clean_days")); } else if ("Alipay".equals(rate_name)) { - client.put("alipay_rate", p.getBigDecimal("rate_value").setScale(2, BigDecimal.ROUND_DOWN)); + client.put("alipay_rate", p.getBigDecimal("rate_value").setScale(2, RoundingMode.DOWN)); } else if ("AlipayOnline".equals(rate_name)) { - client.put("alipay_online_rate", p.getBigDecimal("rate_value").setScale(2, BigDecimal.ROUND_DOWN)); + client.put("alipay_online_rate", p.getBigDecimal("rate_value").setScale(2, RoundingMode.DOWN)); } }); @@ -3126,19 +3068,19 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid if (weChatRate == null) { throw new BadRequestException("The Partner's Rate is not config!"); } - client.put("wechat_rate", weChatRate.getBigDecimal("rate_value").setScale(2, BigDecimal.ROUND_DOWN)); + client.put("wechat_rate", weChatRate.getBigDecimal("rate_value").setScale(2, RoundingMode.DOWN)); client.put("clean", "T+" + weChatRate.getString("clean_days")); client.put("clean_days", weChatRate.getString("clean_days")); try { JSONObject alipayRate = merchantInfoProvider.clientCurrentRate(client.getIntValue("client_id"), new Date(), "Alipay"); if (alipayRate != null) { - client.put("alipay_rate", alipayRate.getBigDecimal("rate_value").setScale(2, BigDecimal.ROUND_DOWN)); + client.put("alipay_rate", alipayRate.getBigDecimal("rate_value").setScale(2, RoundingMode.DOWN)); } JSONObject alipayOnlineRate = merchantInfoProvider.clientCurrentRate(client.getIntValue("client_id"), new Date(), "AlipayOnline"); if (alipayOnlineRate != null) { - client.put("alipay_online_rate", alipayOnlineRate.getBigDecimal("rate_value").setScale(2, BigDecimal.ROUND_DOWN)); + client.put("alipay_online_rate", alipayOnlineRate.getBigDecimal("rate_value").setScale(2, RoundingMode.DOWN)); } } catch (Exception ignored) { // do nothing @@ -3258,7 +3200,7 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid throw new InvalidShortIdException(); } List files = clientFilesMapper.findClientFile(client.getIntValue("client_id")); - if (files != null && files.size() > 0) { + if (files != null && !files.isEmpty()) { List filePaths = new ArrayList<>(); for (JSONObject file : files) { filePaths.add(file.getString("file_value")); @@ -3298,7 +3240,7 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid throw new InvalidShortIdException(); } List files = clientMWAuthFilesInfo.findClientFile(client.getIntValue("client_id"), new PageBounds(1, 999999, Order.formString("last_update_date.asc"))); - if (files != null && files.size() > 0) { + if (files != null && !files.isEmpty()) { List filePaths = new ArrayList<>(); for (JSONObject file : files) { filePaths.add(file.getString("file_value")); @@ -3549,7 +3491,7 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid fileJson.put(file.getString("file_name"), file.getString("file_value")); } String[] fileKeys = {"kyc_utility_bill_file"}; - if (clientFiles.size() > 0) { + if (!clientFiles.isEmpty()) { for (String fileKey : fileKeys) { List clientFileUrl = clientFiles.stream() .filter(json -> (fileKey.equals(json.getString("file_name")))) @@ -3561,7 +3503,7 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid return params; }) .collect(Collectors.toList()); - if (clientFileUrl != null && clientFileUrl.size() > 0) { + if (clientFileUrl != null && !clientFileUrl.isEmpty()) { fileJson.put(fileKey, clientFileUrl); } } @@ -3609,7 +3551,7 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid } List clientFiles = clientFilesMapper.findClientFile(client.getIntValue("client_id")); JSONObject fileJson = new JSONObject(); - if (clientFiles != null && clientFiles.size() > 0) { + if (clientFiles != null && !clientFiles.isEmpty()) { for (String fileKey : fileKeys) { List clientFileUrl = clientFiles.stream() .filter(json -> (fileKey.equals(json.getString("file_name")))) @@ -3621,7 +3563,7 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid return params; }) .collect(Collectors.toList()); - if (clientFileUrl != null && clientFileUrl.size() > 0) { + if (clientFileUrl != null && !clientFileUrl.isEmpty()) { fileJson.put(fileKey, clientFileUrl); } } @@ -3643,7 +3585,7 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid String[] fileKeys = UPayAuthFileEnum.ALL.getFileNameArrays(); List clientFiles = clientMWAuthFilesInfo.findClientFile(client.getIntValue("client_id"), new PageBounds(1, 999999, Order.formString("last_update_date.asc"))); JSONObject fileJson = new JSONObject(); - if (clientFiles != null && clientFiles.size() > 0) { + if (clientFiles != null && !clientFiles.isEmpty()) { for (String fileKey : fileKeys) { List clientFileUrl = clientFiles.stream() .filter(json -> (fileKey.equals(json.getString("file_name")))) @@ -3655,7 +3597,7 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid return params; }) .collect(Collectors.toList()); - if (clientFileUrl != null && clientFileUrl.size() > 0) { + if (clientFileUrl != null && !clientFileUrl.isEmpty()) { fileJson.put(fileKey, clientFileUrl); } } @@ -3674,7 +3616,7 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid JSONObject fileJson = new JSONObject(); JSONObject companyFile = clientComplianceCompanyMapper.findKycFileByClientId(client.getIntValue("client_id")); fileJson.put("companyFile", companyFile); - if (clientFiles != null && clientFiles.size() > 0) { + if (clientFiles != null && !clientFiles.isEmpty()) { for (String fileKey : fileKeys) { List clientFileUrl = clientFiles.stream() .filter(json -> (fileKey.equals(json.getString("file_name")))) @@ -3686,7 +3628,7 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid return params; }) .collect(Collectors.toList()); - if (clientFileUrl != null && clientFileUrl.size() > 0) { + if (clientFileUrl != null && !clientFileUrl.isEmpty()) { fileJson.put(fileKey, clientFileUrl); } } @@ -3704,7 +3646,7 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid } List clientFiles = clientFilesMapper.findAllClientFile(client.getIntValue("client_id")); JSONObject fileJson = new JSONObject(); - if (clientFiles != null && clientFiles.size() > 0) { + if (clientFiles != null && !clientFiles.isEmpty()) { for (String fileKey : fileKeys) { List clientFileUrl = clientFiles.stream() .filter(json -> (fileKey.equals(json.getString("file_name")))) @@ -3717,7 +3659,7 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid return params; }) .collect(Collectors.toList()); - if (clientFileUrl != null && clientFileUrl.size() > 0) { + if (clientFileUrl != null && !clientFileUrl.isEmpty()) { fileJson.put(fileKey, clientFileUrl); } } @@ -3929,7 +3871,7 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid throw new InvalidShortIdException(); } List clientAllAuthFiles = clientFilesMapper.findAllClientFile(client.getIntValue("client_id")); - if (clientAllAuthFiles == null || clientAllAuthFiles.size() == 0) { + if (clientAllAuthFiles == null || clientAllAuthFiles.isEmpty()) { throw new BadRequestException("Please check the information is uploaded completely"); } String[] fileKeys = {"client_bank_file", "client_company_file", "client_id_file", "client_agree_file"}; @@ -4009,26 +3951,26 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid if (weChatRate == null) { throw new BadRequestException("The Partner's Rate is not config!"); } - client.put("wechat_rate", weChatRate.getBigDecimal("rate_value").setScale(2, BigDecimal.ROUND_DOWN)); + client.put("wechat_rate", weChatRate.getBigDecimal("rate_value").setScale(2, RoundingMode.DOWN)); client.put("clean", "T+" + weChatRate.getString("clean_days")); client.put("clean_days", weChatRate.getString("clean_days")); String rateConfig = sysConfigManager.getSysConfig().getString("sys_rates"); - JSONObject sysConfigRate = JSONObject.parseObject(rateConfig); + JSONObject sysConfigRate = JSON.parseObject(rateConfig); try { JSONObject alipayRate = merchantInfoProvider.clientCurrentRate(client.getIntValue("client_id"), new Date(), "Alipay"); if (alipayRate != null) { - client.put("alipay_rate", alipayRate.getBigDecimal("rate_value").setScale(2, BigDecimal.ROUND_DOWN)); + client.put("alipay_rate", alipayRate.getBigDecimal("rate_value").setScale(2, RoundingMode.DOWN)); } JSONObject alipayOnlineRate = merchantInfoProvider.clientCurrentRate(client.getIntValue("client_id"), new Date(), "AlipayOnline"); if (alipayOnlineRate != null) { - client.put("alipay_online_rate", alipayOnlineRate.getBigDecimal("rate_value").setScale(2, BigDecimal.ROUND_DOWN)); + client.put("alipay_online_rate", alipayOnlineRate.getBigDecimal("rate_value").setScale(2, RoundingMode.DOWN)); } JSONObject cbBankPayRate = merchantInfoProvider.clientCurrentRate(client.getIntValue("client_id"), new Date(), "CB_BankPay"); if (cbBankPayRate != null) { - client.put("cbbank_rate", cbBankPayRate.getBigDecimal("rate_value").setScale(2, BigDecimal.ROUND_DOWN)); + client.put("cbbank_rate", cbBankPayRate.getBigDecimal("rate_value").setScale(2, RoundingMode.DOWN)); } } catch (Exception ignored) { throw new BadRequestException("Merchant Rate Not Configure,Please Contact Customer Service"); @@ -4091,14 +4033,14 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid new PageBounds(query.getPage(), query.getLimit(), Order.formString("clearing_time.desc"))); JSONObject result = PageListUtils.buildPageListResult(logs); if (query.getPage() == 1) { - if (!logs.isEmpty() && logs.size() > 0) { + if (!logs.isEmpty()) { JSONObject clearingDetail = clearingDetailMapper.findByDetailId(logs.get(0).getIntValue("clear_detail_id")); if (clearingDetail != null) { JSONObject clearingLog = clearingLogMapper.findById(clearingDetail.getIntValue("clearing_id")); if (clearingLog.getBooleanValue("editable")) { result.put("padding", true); logs.get(0).put("padding", true); - logger.info("##editable" + clearingLog.getBooleanValue("editable")); + logger.info("##editable{}", clearingLog.getBooleanValue("editable")); } } } @@ -4146,7 +4088,7 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid for (int i = 0; i < childs.size(); i++) { params.put("client_id", childs.get(i).getInteger("client_id")); PageList childLogs = transactionMapper.listSettlementLog(params, new PageBounds(query.getPage(), 10000, Order.formString("clearing_time.desc"))); - if (childLogs.size() > 0) { + if (!childLogs.isEmpty()) { addSheet(i + 1, workbook, childs.get(i), childLogs); } } @@ -4244,9 +4186,9 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid HSSFRichTextString text0 = new HSSFRichTextString(client.getString("short_name")); HSSFRichTextString text1 = new HSSFRichTextString(client.getString("client_moniker")); HSSFRichTextString text2 = new HSSFRichTextString(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(dataItem.getDate("report_date"))); - HSSFRichTextString text3 = new HSSFRichTextString(dataItem.getBigDecimal("total").setScale(2, BigDecimal.ROUND_HALF_DOWN).toString()); - HSSFRichTextString text4 = new HSSFRichTextString(dataItem.getBigDecimal("income").setScale(2, BigDecimal.ROUND_HALF_DOWN).toString()); - HSSFRichTextString text5 = new HSSFRichTextString(dataItem.getBigDecimal("fee").setScale(2, BigDecimal.ROUND_HALF_DOWN).toString()); + HSSFRichTextString text3 = new HSSFRichTextString(dataItem.getBigDecimal("total").setScale(2, RoundingMode.HALF_DOWN).toString()); + HSSFRichTextString text4 = new HSSFRichTextString(dataItem.getBigDecimal("income").setScale(2, RoundingMode.HALF_DOWN).toString()); + HSSFRichTextString text5 = new HSSFRichTextString(dataItem.getBigDecimal("fee").setScale(2, RoundingMode.HALF_DOWN).toString()); cell0.setCellValue(text0); cell1.setCellValue(text1); cell2.setCellValue(text2); @@ -4391,11 +4333,11 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid public void updateAggregateFilesForWaitCompliance(JSONObject manager, int clientId, String fileType, String fileValue, List fileResult) { if (fileValue != null) { List passAggregateFiles = clientFilesMapper.findClientPassAggreeFile(clientId); - if (passAggregateFiles != null && passAggregateFiles.size() > 0) { + if (passAggregateFiles != null && !passAggregateFiles.isEmpty()) { throw new BadRequestException("合同已提交或审核通过,请勿重复签订合同"); } List aggregateFiles = clientFilesMapper.findClientAggreeFileCommit(clientId); - if (aggregateFiles != null && aggregateFiles.size() > 0) { + if (aggregateFiles != null && !aggregateFiles.isEmpty()) { clientFilesMapper.deleteAggreeByClientId(clientId); } String signatureAccountId = StringUtils.isNotBlank("account_id") ? manager.getString("account_id") : manager.getString("manager_id"); @@ -4582,12 +4524,12 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid } JSONObject cardFlowInfo = sysClientUpayProfileMapper.findInfo(clientId); - JSONObject cardFlow = new JSONObject() {{ - put("client_id", clientId); - put("upay_approve_result", 4); - put("upay_open_status", 1); - put("upay_approve_time", new Date()); - }}; + JSONObject cardFlow = JsonHelper.newJson(json -> { + json.put("client_id", clientId); + json.put("upay_approve_result", 4); + json.put("upay_open_status", 1); + json.put("upay_approve_time", new Date()); + }); sysClientUpayProfileMapper.update(cardFlow); saveClientAuditProcess(client.getIntValue("client_id"), null, 1, "提交Card Payment Compliance制作合同", manager, 2); } @@ -5017,12 +4959,12 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid public void updateAppClient(JSONObject account, int clientId, AppClientBean appClientBean) { JSONObject client = getClientInfo(clientId); JSONObject updateObj = appClientBean.updateObject(); - if (updateObj.size() > 0) { + if (!updateObj.isEmpty()) { updateObj.put("client_id", clientId); clientMapper.update(updateObj); } JSONObject clientLegal = appClientBean.legalObject(); - if (clientLegal.size() > 0) { + if (!clientLegal.isEmpty()) { clientLegal.put("client_id", clientId); JSONObject oldClienetLegal = sysClientLegalPersonMapper.findRepresentativeInfo(clientId); if (oldClienetLegal == null) { @@ -5221,7 +5163,7 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid private void sendMessagetoCompliance(JSONObject client, String bd_user_name) { List complianceList = managerMapper.getOnlyCompliance(); - if (complianceList != null && complianceList.size() > 0) { + if (complianceList != null && !complianceList.isEmpty()) { for (JSONObject compliance : complianceList) { String wxopenid = compliance.getString("wx_openid"); String loginUrl = PlatformEnvironment.getEnv().concatUrl("/global/userstatus/manager_signin_wechat"); @@ -5313,7 +5255,7 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid private void sendAgreeFileMsgtoCompliance(JSONObject client, String bd_user_name) { List complianceList = managerMapper.getOnlyCompliance(); - if (complianceList != null && complianceList.size() > 0) { + if (complianceList != null && !complianceList.isEmpty()) { for (JSONObject compliance : complianceList) { String wxopenid = compliance.getString("wx_openid"); String loginUrl = PlatformEnvironment.getEnv().concatUrl("/global/userstatus/manager_signin_wechat"); @@ -5346,7 +5288,7 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid private void sendGreenChannelMessagetoCompliance(JSONObject client, String bd_user_name) { List complianceList = managerMapper.getOnlyCompliance(); - if (complianceList != null && complianceList.size() > 0) { + if (complianceList != null && !complianceList.isEmpty()) { for (JSONObject compliance : complianceList) { String wxopenid = compliance.getString("wx_openid"); String loginUrl = PlatformEnvironment.getEnv().concatUrl("/global/userstatus/manager_signin_wechat"); @@ -5424,7 +5366,7 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid if (client.getIntValue("open_status") == 1) { List complianceList = managerMapper.getOnlyCompliance(); - if (complianceList != null && complianceList.size() > 0) { + if (complianceList != null && !complianceList.isEmpty()) { for (JSONObject compliance : complianceList) { String wxopenid = compliance.getString("wx_openid"); try { @@ -5465,7 +5407,7 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid bd_user_name = "自助开通商户"; } List complianceList = managerMapper.getOnlyCompliance(); - if (complianceList != null && complianceList.size() > 0) { + if (complianceList != null && !complianceList.isEmpty()) { for (JSONObject compliance : complianceList) { String wxopenid = compliance.getString("wx_openid"); try { @@ -5503,7 +5445,7 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid if (client.getIntValue("open_status") == 10) { List complianceList = managerMapper.getOnlyCompliance(); - if (complianceList != null && complianceList.size() > 0) { + if (complianceList != null && !complianceList.isEmpty()) { for (JSONObject compliance : complianceList) { String wxopenid = compliance.getString("wx_openid"); try { @@ -5532,7 +5474,7 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid } if (cardFlowInfo.getIntValue("upay_open_status") == 1) { List complianceList = managerMapper.getOnlyCompliance(); - if (complianceList != null && complianceList.size() > 0) { + if (complianceList != null && !complianceList.isEmpty()) { for (JSONObject compliance : complianceList) { String wxopenid = compliance.getString("wx_openid"); try { @@ -5573,7 +5515,7 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid bd_user_name = "自助开通商户"; } List complianceList = managerMapper.getOnlyCompliance(); - if (complianceList != null && complianceList.size() > 0) { + if (complianceList != null && !complianceList.isEmpty()) { for (JSONObject compliance : complianceList) { String wxopenid = compliance.getString("wx_openid"); try { @@ -5905,7 +5847,7 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid List listByshortName = sysRpayMerchantApplyMapper.listByShortName(merchantInfo.getString("company_shortname")); - if (listByshortName.size() > 0) { + if (!listByshortName.isEmpty()) { throw new BadRequestException("请修改【" + clientMoniker + "】的Company shortName信息(Short Name 已被使用)"); } if (client.getString("rpay_enterprise_id") != null) { @@ -6555,7 +6497,7 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid } } String path = paymentConfig.getString("path"); - path = path.replaceAll("app", "pc"); + path = path.replace("app", "pc"); response.sendRedirect(String.format(PlatformEnvironment.getEnv().concatUrl(path), clientMoniker)); } @@ -6600,7 +6542,12 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid logger.error("合同制作出现问题:", e); throw new BadRequestException("合同制作出现问题:" + e.getMessage()); } finally { - stream.close(); + if (stream != null) { + try { + stream.close(); + } catch (IOException e) { + } + } } return result; } @@ -6684,10 +6631,10 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid } } incrementalChannels.remove("system"); - return new JSONObject() {{ - put("all_service", service); - put("incremental_channel", incrementalChannels); - }}; + return JsonHelper.newJson(json -> { + json.put("all_service", service); + json.put("incremental_channel", incrementalChannels); + }); } @Override @@ -6812,10 +6759,10 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid public JSONObject findByLookupCode(String code) { JSONObject industryInfo = industryLookupMapper.findByLookupCode(code); if (industryInfo == null) { - return new JSONObject() {{ - put("lookup_code", "code"); - put("lookup_value", "未知行业"); - }}; + return JsonHelper.newJson(json -> { + json.put("lookup_code", "code"); + json.put("lookup_value", "未知行业"); + }); } return industryInfo; } @@ -6900,10 +6847,8 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid clientIds.add(p.getString("client_id")); if (mchConfig.getBooleanValue("level3_mch_config")) { List clients = clientMapper.listChildClients(p.getIntValue("client_id")); - if (clients.size() > 0) { - clients.forEach(e -> { - clientIds.add(e.getString("client_id")); - }); + if (!clients.isEmpty()) { + clients.forEach(e -> clientIds.add(e.getString("client_id"))); } } }); @@ -6961,7 +6906,7 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid if (client == null) { throw new InvalidShortIdException(); } - JSONObject extParmas = JSONObject.parseObject(client.getString("ext_params")); + JSONObject extParmas = JSON.parseObject(client.getString("ext_params")); if ("true".equals(params.getString("value")) || "false".equals(params.getString("value"))) { extParmas.put(params.getString("key"), params.getBoolean("value")); } else { @@ -7126,7 +7071,7 @@ public class ClientManagerImpl implements ClientManager, ManagerTodoNoticeProvid info.put("partner_bussiness_name", client.getString("business_name"));//商户商用名称 info.put("legal_bussiness", legalInfo.getString("representative_person") + " AS " + (client.containsKey("business_name") ? client.getString("business_name") : legalInfo.getString("representative_person")) + " ABN " + client.getString("abn"));//拼接规则:法人名 AS 商用名称 ABD 编码 info.put("domestic_fee", cardRate.getString("domestic_rate_value"));//国内服务费 - info.put("international_fee", upayProfileInfo.getBoolean("enable_international_card") ? cardRate.getString("overseas_rate_value") : "-");//国际服务费 + info.put("international_fee", upayProfileInfo.getBooleanValue("enable_international_card") ? cardRate.getString("overseas_rate_value") : "-");//国际服务费 info.put("promotional_effective_date", formatter.print(currentRate.getDate("active_time").getTime())); info.put("promotional_period", formatter.print(currentRate.getDate("expiry_time").getTime())); return info; diff --git a/src/main/java/au/com/royalpay/payment/manage/notice/beans/NoticeInfo.java b/src/main/java/au/com/royalpay/payment/manage/notice/beans/NoticeInfo.java index 2bb82f64c..b3c16cda0 100644 --- a/src/main/java/au/com/royalpay/payment/manage/notice/beans/NoticeInfo.java +++ b/src/main/java/au/com/royalpay/payment/manage/notice/beans/NoticeInfo.java @@ -91,15 +91,15 @@ public class NoticeInfo { } if (button2 != null) { JSONObject buttonJson = JSON.parseObject(button2); - if (StringUtils.isNotBlank(buttonJson.getString("name")) && StringUtils.isNotBlank(buttonJson.getString("type"))) { + if (StringUtils.isNotBlank(buttonJson.getString("name")) && StringUtils.isNotBlank(buttonJson.getString("type"))) { buttons.add(buttonJson); } } - if (buttons.size() > 0 ) { - res.put("buttons",buttons); + if (!buttons.isEmpty()) { + res.put("buttons", buttons); } if (aggregate_file != null) { - res.put("aggregate_file",aggregate_file); + res.put("aggregate_file", aggregate_file); } if (url != null) { res.put("url",url); diff --git a/src/main/java/au/com/royalpay/payment/manage/notice/core/impls/MailServiceImp.java b/src/main/java/au/com/royalpay/payment/manage/notice/core/impls/MailServiceImp.java index 50c1ababd..a43030776 100644 --- a/src/main/java/au/com/royalpay/payment/manage/notice/core/impls/MailServiceImp.java +++ b/src/main/java/au/com/royalpay/payment/manage/notice/core/impls/MailServiceImp.java @@ -125,7 +125,7 @@ public class MailServiceImp implements MailService { noticeBean.setNotice_id(notice_id); noticeBean.setMailClients(mailToWithoutUnsub); noticeBean.setContent(doc.outerHtml()); - if (files.size() > 0) { + if (!files.isEmpty()) { noticeBean.setFiles(files.toString()); } JSONObject sysConfig = sysConfigManager.getSysConfig(); diff --git a/src/main/java/au/com/royalpay/payment/manage/notice/core/impls/NoticeManageImpl.java b/src/main/java/au/com/royalpay/payment/manage/notice/core/impls/NoticeManageImpl.java index 8c932290a..dc4ed8d40 100644 --- a/src/main/java/au/com/royalpay/payment/manage/notice/core/impls/NoticeManageImpl.java +++ b/src/main/java/au/com/royalpay/payment/manage/notice/core/impls/NoticeManageImpl.java @@ -13,12 +13,10 @@ import au.com.royalpay.payment.manage.notice.core.NoticeManage; import au.com.royalpay.payment.manage.system.core.MailGunService; import au.com.royalpay.payment.tools.exceptions.ForbiddenException; import au.com.royalpay.payment.tools.utils.PageListUtils; - import com.alibaba.fastjson.JSONObject; import com.github.miemiedev.mybatis.paginator.domain.Order; import com.github.miemiedev.mybatis.paginator.domain.PageBounds; import com.github.miemiedev.mybatis.paginator.domain.PageList; - import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -27,14 +25,13 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.Assert; +import javax.annotation.Resource; import java.io.IOException; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Date; import java.util.List; -import javax.annotation.Resource; - /** * Created by yishuqian on 28/09/2016. */ @@ -73,7 +70,7 @@ public class NoticeManageImpl implements NoticeManage { if (notice.getIntValue("type") == 2) { if (notice.get("buttons") != null) { List buttons = JSONObject.parseArray(notice.getString("buttons"), JSONObject.class); - if (buttons != null && buttons.size() > 0) { + if (buttons != null && !buttons.isEmpty()) { for (int i = 0; i < buttons.size(); i++) { notice.put("button" + i, buttons.get(i)); } @@ -156,7 +153,7 @@ public class NoticeManageImpl implements NoticeManage { if (notice.getIntValue("type") == 2) { if (notice.get("buttons") != null) { List buttons = JSONObject.parseArray(notice.getString("buttons"), JSONObject.class); - if (buttons != null && buttons.size() > 0) { + if (buttons != null && !buttons.isEmpty()) { for (int i = 0; i < buttons.size(); i++) { notice.put("button" + i, buttons.get(i)); } diff --git a/src/main/java/au/com/royalpay/payment/manage/notice/core/impls/NoticePartnerImpl.java b/src/main/java/au/com/royalpay/payment/manage/notice/core/impls/NoticePartnerImpl.java index af0773143..a3efbda06 100644 --- a/src/main/java/au/com/royalpay/payment/manage/notice/core/impls/NoticePartnerImpl.java +++ b/src/main/java/au/com/royalpay/payment/manage/notice/core/impls/NoticePartnerImpl.java @@ -3,20 +3,17 @@ package au.com.royalpay.payment.manage.notice.core.impls; import au.com.royalpay.payment.manage.mappers.notice.NoticePartnerMapper; import au.com.royalpay.payment.manage.notice.core.NoticePartner; import au.com.royalpay.payment.tools.utils.PageListUtils; - import com.alibaba.fastjson.JSONObject; import com.github.miemiedev.mybatis.paginator.domain.Order; import com.github.miemiedev.mybatis.paginator.domain.PageBounds; import com.github.miemiedev.mybatis.paginator.domain.PageList; - import org.springframework.stereotype.Service; +import javax.annotation.Resource; import java.util.Collections; import java.util.Date; import java.util.List; -import javax.annotation.Resource; - /** * Created by yishuqian on 29/09/2016. */ @@ -54,13 +51,13 @@ public class NoticePartnerImpl implements NoticePartner { params.put("client_id",partner.getIntValue("client_id")); params.put("notice_id",noticeId); List partnerNotices = noticePartnerMapper.listNoticePartner(params); - if (!partnerNotices.isEmpty() && partnerNotices.size()>0){ + if (!partnerNotices.isEmpty()) { JSONObject noticePartner = partnerNotices.get(0); - noticePartner.put("status",'1'); - noticePartner.put("read_id",partner.getString("account_id")); - noticePartner.put("read_time",new Date()); + noticePartner.put("status", '1'); + noticePartner.put("read_id", partner.getString("account_id")); + noticePartner.put("read_time", new Date()); noticePartnerMapper.update(noticePartner); - }else { + } else { throw new Exception("there is no notice for the noticeId"); } } diff --git a/src/main/java/au/com/royalpay/payment/manage/openim/core/OpenimClient.java b/src/main/java/au/com/royalpay/payment/manage/openim/core/OpenimClient.java index ee4ce9bb0..ab45ce25e 100644 --- a/src/main/java/au/com/royalpay/payment/manage/openim/core/OpenimClient.java +++ b/src/main/java/au/com/royalpay/payment/manage/openim/core/OpenimClient.java @@ -1,7 +1,7 @@ package au.com.royalpay.payment.manage.openim.core; import au.com.royalpay.payment.tools.exceptions.ServerErrorException; - +import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.taobao.api.ApiException; import com.taobao.api.DefaultTaobaoClient; @@ -15,7 +15,6 @@ import com.taobao.api.response.OpenimCustmsgPushResponse; import com.taobao.api.response.OpenimUsersAddResponse; import com.taobao.api.response.OpenimUsersGetResponse; import com.taobao.api.response.OpenimUsersUpdateResponse; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; @@ -47,7 +46,7 @@ public class OpenimClient { } catch (ApiException e) { logger.info("openim get user fail", e); } - JSONObject openInfo = JSONObject.parseObject(rsp.getBody()); + JSONObject openInfo = JSON.parseObject(rsp.getBody()); if (openInfo.getJSONObject("openim_users_get_response").getJSONObject("userinfos").size() < 1) { return null; } @@ -64,9 +63,9 @@ public class OpenimClient { } catch (ApiException e) { logger.info("openim add user fail", e); } - JSONObject result = JSONObject.parseObject(rsp.getBody()); + JSONObject result = JSON.parseObject(rsp.getBody()); JSONObject failMsg = result.getJSONObject("openim_users_add_response").getJSONObject("fail_msg"); - if (failMsg.size() > 0) { + if (!failMsg.isEmpty()) { if ("data exist".equals(failMsg.getJSONArray("string").get(0))) { return; } @@ -85,7 +84,7 @@ public class OpenimClient { } catch (ApiException e) { logger.info("openim update user fail", e); } - JSONObject result = JSONObject.parseObject(rsp.getBody()); + JSONObject result = JSON.parseObject(rsp.getBody()); if (result.getJSONObject("openim_users_update_response").getJSONObject("fail_msg").size() > 0) { logger.info("openim update user fail reason:" + result.getJSONObject("openim_users_update_response").getJSONObject("fail_msg").getJSONArray("string").toJSONString()); @@ -103,7 +102,7 @@ public class OpenimClient { } catch (ApiException e) { logger.info("openim push msg fail", e); } - JSONObject result = JSONObject.parseObject(rsp.getBody()); + JSONObject result = JSON.parseObject(rsp.getBody()); if (result.getJSONObject("openim_custmsg_push_response").getJSONObject("fail_msg").size() > 0) { logger.info("openim push message fail reason:" + result.getJSONObject("openim_custmsg_push_response").getJSONObject("fail_msg").getJSONArray("string").toJSONString()); diff --git a/src/main/java/au/com/royalpay/payment/manage/openim/core/impl/CustomerServiceServiceImpl.java b/src/main/java/au/com/royalpay/payment/manage/openim/core/impl/CustomerServiceServiceImpl.java index d7286a94f..62962b6d2 100644 --- a/src/main/java/au/com/royalpay/payment/manage/openim/core/impl/CustomerServiceServiceImpl.java +++ b/src/main/java/au/com/royalpay/payment/manage/openim/core/impl/CustomerServiceServiceImpl.java @@ -13,9 +13,8 @@ import au.com.royalpay.payment.tools.connections.mpsupport.beans.TemplateMessage import au.com.royalpay.payment.tools.exceptions.BadRequestException; import au.com.royalpay.payment.tools.exceptions.ForbiddenException; import au.com.royalpay.payment.tools.exceptions.ServerErrorException; - +import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; - import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.StringUtils; @@ -26,13 +25,8 @@ import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Date; -import java.util.List; - import javax.annotation.Resource; +import java.util.*; /** * @author kira @@ -173,7 +167,7 @@ public class CustomerServiceServiceImpl implements CustomerServiceService { for (int i = 0; i < ops.size(); i++) { String jStr = ops.index(i); if (jStr.contains(uid)) { - JSONObject record = JSONObject.parseObject(jStr); + JSONObject record = JSON.parseObject(jStr); record.put("unreadMsg", record.getIntValue("unreadMsg") + 1); ops.set(i, record.toJSONString()); return; @@ -197,7 +191,7 @@ public class CustomerServiceServiceImpl implements CustomerServiceService { int unreadMsg = 0; for (int i = 0; i < ops.size(); i++) { clients++; - unreadMsg += JSONObject.parseObject(ops.index(i)).getIntValue("unreadMsg"); + unreadMsg += JSON.parseObject(ops.index(i)).getIntValue("unreadMsg"); } TemplateMessage msg = initUnreadMsg(unreadMsg, clients, p.getString("wx_openid"), paymentApi.getTemplateId("commission")); paymentApi.sendTemplateMessage(msg); diff --git a/src/main/java/au/com/royalpay/payment/manage/organizations/core/impls/OrgManagerImpl.java b/src/main/java/au/com/royalpay/payment/manage/organizations/core/impls/OrgManagerImpl.java index 4f4beea92..6ff7bec80 100644 --- a/src/main/java/au/com/royalpay/payment/manage/organizations/core/impls/OrgManagerImpl.java +++ b/src/main/java/au/com/royalpay/payment/manage/organizations/core/impls/OrgManagerImpl.java @@ -353,24 +353,24 @@ public class OrgManagerImpl implements OrgManager { if(StringUtils.isEmpty(orgObject.getString(rateName))){ rate1.add(rateName); } - if(StringUtils.isEmpty(json.getString(rateName))){ + if (StringUtils.isEmpty(json.getString(rateName))) { rate2.add(rateName); } - if(StringUtils.isNotEmpty(orgObject.getString(rateName))&&StringUtils.isNotEmpty(json.getString(rateName))){ - if(orgObject.getDouble(rateName).compareTo(json.getDouble(rateName)) > 0){ - rateNames += rateName +","; + if (StringUtils.isNotEmpty(orgObject.getString(rateName)) && StringUtils.isNotEmpty(json.getString(rateName))) { + if (orgObject.getDouble(rateName).compareTo(json.getDouble(rateName)) > 0) { + rateNames += rateName + ","; } } } } - if(rate1.size()>0){ + if (!rate1.isEmpty()) { throw new ForbiddenException("费率异常,请联系管理员"); } - if(rate2.size()>0){ + if (!rate2.isEmpty()) { throw new ForbiddenException("费率输入不完整,请重新输入"); } - if(!rateNames.equals("")){ - throw new ForbiddenException("二级组织"+rateNames+"费率参数应大于一级组织费率,请重新输入"); + if (!rateNames.equals("")) { + throw new ForbiddenException("二级组织" + rateNames + "费率参数应大于一级组织费率,请重新输入"); } } } diff --git a/src/main/java/au/com/royalpay/payment/manage/processors/CtripCouponOnlyLogProcessor.java b/src/main/java/au/com/royalpay/payment/manage/processors/CtripCouponOnlyLogProcessor.java index c11c56ba5..f63418a00 100644 --- a/src/main/java/au/com/royalpay/payment/manage/processors/CtripCouponOnlyLogProcessor.java +++ b/src/main/java/au/com/royalpay/payment/manage/processors/CtripCouponOnlyLogProcessor.java @@ -27,6 +27,7 @@ import org.springframework.web.util.UriComponentsBuilder; import javax.annotation.Resource; import java.math.BigDecimal; +import java.math.RoundingMode; import java.util.Date; import java.util.List; @@ -82,7 +83,7 @@ public class CtripCouponOnlyLogProcessor implements PaymentProcessor { BigDecimal payFee = paymentInfo.getTotalFee(); BigDecimal exchange = paymentApi.channelApi(paymentInfo.getChannel()).queryExchangeRateDecimal(paymentInfo.getClientId()); if (StringUtils.equals(paymentInfo.getCurrency(), "CNY")) { - payFee = CurrencyAmountUtils.scale(payFee.divide(exchange,2, BigDecimal.ROUND_HALF_UP), PlatformEnvironment.getEnv().getForeignCurrency()); + payFee = CurrencyAmountUtils.scale(payFee.divide(exchange, 2, RoundingMode.HALF_UP), PlatformEnvironment.getEnv().getForeignCurrency()); } BigDecimal couponCondition = couponInfo.getBigDecimal("condition") == null ? BigDecimal.ZERO : couponInfo.getBigDecimal("condition"); @@ -105,7 +106,7 @@ public class CtripCouponOnlyLogProcessor implements PaymentProcessor { } //携程折扣 if (StringUtils.equals(couponInfo.getString("type"), "32")) { - BigDecimal couponDiscount = couponInfo.getBigDecimal("discount").divide(CommonConsts.HUNDRED, 4, BigDecimal.ROUND_HALF_UP); + BigDecimal couponDiscount = couponInfo.getBigDecimal("discount").divide(CommonConsts.HUNDRED, 4, RoundingMode.HALF_UP); BigDecimal couponDealAmount = CurrencyAmountUtils.scale(couponDiscount.multiply(paymentInfo.getTotalFee()), PlatformEnvironment.getEnv().getForeignCurrency()); couponAccuessLog.put("coupon_deal_amount", couponDealAmount); } @@ -119,7 +120,7 @@ public class CtripCouponOnlyLogProcessor implements PaymentProcessor { JSONObject order = finishedEvent.getOrder(); String orderId = order.getString("order_id"); List accuessCouponLogs = payCouponAccuessLogMapper.findAccuessLogByOrderId(orderId, new PageBounds(Order.formString("last_update_date.desc"))); - if (accuessCouponLogs != null&&accuessCouponLogs.size()>0) { + if (accuessCouponLogs != null && !accuessCouponLogs.isEmpty()) { if (!isOnlyLogMerchant(order.getIntValue("client_id"))) { return; } @@ -128,7 +129,7 @@ public class CtripCouponOnlyLogProcessor implements PaymentProcessor { logger.info("订单 [" + orderId + "]成功使用Ctrip卡券=======>[" + couponLogId + "]"); accuessCouponLog.put("is_valid", 1); accuessCouponLog.put("last_update_date", new Date()); - accuessCouponLog.put("customer_openid",order.getString("customer_id")); + accuessCouponLog.put("customer_openid", order.getString("customer_id")); payCouponAccuessLogMapper.update(accuessCouponLog); } @@ -145,14 +146,14 @@ public class CtripCouponOnlyLogProcessor implements PaymentProcessor { JSONObject refundOrder = event.getRefundOrder(); String orderId = refundOrder.getString("order_id"); List accuessCouponLogs = payCouponAccuessLogMapper.findUsedCouponByOrderIdList(orderId); - if (accuessCouponLogs != null&& accuessCouponLogs.size()>0) { + if (accuessCouponLogs != null && !accuessCouponLogs.isEmpty()) { if (!isOnlyLogMerchant(refundOrder.getIntValue("client_id"))) { return; } JSONObject accuessCouponLog = accuessCouponLogs.get(0); accuessCouponLog.put("is_valid", 0); accuessCouponLog.put("last_update_date", new Date()); - accuessCouponLog.put("refund_id",refundOrder.getString("refund_id")); + accuessCouponLog.put("refund_id", refundOrder.getString("refund_id")); payCouponAccuessLogMapper.update(accuessCouponLog); } } diff --git a/src/main/java/au/com/royalpay/payment/manage/processors/CtripCouponProvideProcessor.java b/src/main/java/au/com/royalpay/payment/manage/processors/CtripCouponProvideProcessor.java index 1354d7813..321728514 100644 --- a/src/main/java/au/com/royalpay/payment/manage/processors/CtripCouponProvideProcessor.java +++ b/src/main/java/au/com/royalpay/payment/manage/processors/CtripCouponProvideProcessor.java @@ -30,6 +30,7 @@ import org.springframework.web.util.UriComponentsBuilder; import javax.annotation.Resource; import java.math.BigDecimal; +import java.math.RoundingMode; import java.util.Date; import java.util.List; @@ -91,7 +92,7 @@ public class CtripCouponProvideProcessor implements PaymentProcessor { BigDecimal payFee = paymentInfo.getTotalFee(); BigDecimal exchange = paymentApi.channelApi(paymentInfo.getChannel()).queryExchangeRateDecimal(paymentInfo.getClientId()); if (StringUtils.equals(paymentInfo.getCurrency(), "CNY")) { - payFee = CurrencyAmountUtils.scale(payFee.divide(exchange,2, BigDecimal.ROUND_HALF_UP), PlatformEnvironment.getEnv().getForeignCurrency()); + payFee = CurrencyAmountUtils.scale(payFee.divide(exchange, 2, RoundingMode.HALF_UP), PlatformEnvironment.getEnv().getForeignCurrency()); } BigDecimal couponCondition = couponInfo.getBigDecimal("condition") == null ? BigDecimal.ZERO : couponInfo.getBigDecimal("condition"); @@ -116,7 +117,7 @@ public class CtripCouponProvideProcessor implements PaymentProcessor { } //携程折扣 if (StringUtils.equals(couponInfo.getString("type"), "32")) { - BigDecimal couponDiscount = couponInfo.getBigDecimal("discount").divide(CommonConsts.HUNDRED, 4, BigDecimal.ROUND_HALF_UP); + BigDecimal couponDiscount = couponInfo.getBigDecimal("discount").divide(CommonConsts.HUNDRED, 4, RoundingMode.HALF_UP); BigDecimal couponDealAmount = CurrencyAmountUtils.scale(couponDiscount.multiply(paymentInfo.getTotalFee()), PlatformEnvironment.getEnv().getForeignCurrency()); paymentInfo.setDiscount(currentDiscount.add(couponDealAmount)); couponAccuessLog.put("coupon_deal_amount", couponDealAmount); @@ -146,7 +147,7 @@ public class CtripCouponProvideProcessor implements PaymentProcessor { }*/ String orderId = order.getString("order_id"); List accuessCouponLogs = payCouponAccuessLogMapper.findAccuessLogByOrderId(orderId, new PageBounds(Order.formString("last_update_date.desc"))); - if (accuessCouponLogs != null&&accuessCouponLogs.size()>0) { + if (accuessCouponLogs != null && !accuessCouponLogs.isEmpty()) { if (isOnlyLogMerchant(order.getIntValue("client_id"))) { return; } @@ -203,7 +204,7 @@ public class CtripCouponProvideProcessor implements PaymentProcessor { logger.info("积分商城携程优惠券开始退款"); String orderId = refundOrder.getString("order_id"); List accuessCouponLogs = payCouponAccuessLogMapper.findUsedCouponByOrderIdList(orderId); - if (accuessCouponLogs != null&& accuessCouponLogs.size()>0) { + if (accuessCouponLogs != null && !accuessCouponLogs.isEmpty()) { if (isOnlyLogMerchant(refundOrder.getIntValue("client_id"))) { return; } diff --git a/src/main/java/au/com/royalpay/payment/manage/redpack/core/impls/ActRedPackServiceImpl.java b/src/main/java/au/com/royalpay/payment/manage/redpack/core/impls/ActRedPackServiceImpl.java index 833728814..29a0c1170 100644 --- a/src/main/java/au/com/royalpay/payment/manage/redpack/core/impls/ActRedPackServiceImpl.java +++ b/src/main/java/au/com/royalpay/payment/manage/redpack/core/impls/ActRedPackServiceImpl.java @@ -17,11 +17,9 @@ import au.com.royalpay.payment.tools.env.PlatformEnvironment; import au.com.royalpay.payment.tools.exceptions.ForbiddenException; import au.com.royalpay.payment.tools.exceptions.NotFoundException; import au.com.royalpay.payment.tools.utils.PageListUtils; - import com.alibaba.fastjson.JSONObject; import com.github.miemiedev.mybatis.paginator.domain.PageBounds; import com.github.miemiedev.mybatis.paginator.domain.PageList; - import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.RandomUtils; @@ -34,6 +32,7 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.util.Assert; +import javax.annotation.Resource; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.Collections; @@ -43,8 +42,6 @@ import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; -import javax.annotation.Resource; - /** * Created by wangning on 2017/8/10. */ @@ -239,7 +236,7 @@ public class ActRedPackServiceImpl implements ActRedPackService { for (int i = 0; i < redpackCounts; i++) { BigDecimal amount = amountFrom.equals(amountTo) ? amountFrom : amountFrom.add(BigDecimal.valueOf(RandomUtils.nextInt(0, amountTo.subtract(amountFrom).multiply(CommonConsts.HUNDRED).intValue())) - .divide(CommonConsts.HUNDRED, 2, BigDecimal.ROUND_DOWN)); + .divide(CommonConsts.HUNDRED, 2, RoundingMode.DOWN)); JSONObject prize = new JSONObject(); String prefix = DateFormatUtils.format(new Date(), "yyyyMMddHHmmssSSS"); String redpackOrderId = prefix + RandomStringUtils.random(28 - prefix.length(), true, true); diff --git a/src/main/java/au/com/royalpay/payment/manage/redpack/core/impls/PartnerLMServiceImp.java b/src/main/java/au/com/royalpay/payment/manage/redpack/core/impls/PartnerLMServiceImp.java index 61d123b89..4959a6a49 100644 --- a/src/main/java/au/com/royalpay/payment/manage/redpack/core/impls/PartnerLMServiceImp.java +++ b/src/main/java/au/com/royalpay/payment/manage/redpack/core/impls/PartnerLMServiceImp.java @@ -7,15 +7,15 @@ import au.com.royalpay.payment.manage.mappers.system.ClientMapper; import au.com.royalpay.payment.manage.mappers.system.CustomerMapper; import au.com.royalpay.payment.manage.merchants.beans.PartnerQuery; import au.com.royalpay.payment.manage.merchants.core.ClientManager; -import au.com.royalpay.payment.tools.connections.mpsupport.MpWechatApiProvider; -import au.com.royalpay.payment.tools.env.PlatformEnvironment; -import au.com.royalpay.payment.tools.permission.enums.ManagerRole; import au.com.royalpay.payment.manage.redpack.beans.ActTypeEnum; import au.com.royalpay.payment.manage.redpack.beans.RedpackQuery; import au.com.royalpay.payment.manage.redpack.core.PartnerLMService; import au.com.royalpay.payment.manage.redpack.core.RedpackService; import au.com.royalpay.payment.tools.connections.mpsupport.MpWechatApi; +import au.com.royalpay.payment.tools.connections.mpsupport.MpWechatApiProvider; import au.com.royalpay.payment.tools.connections.mpsupport.beans.WechatRedpack; +import au.com.royalpay.payment.tools.env.PlatformEnvironment; +import au.com.royalpay.payment.tools.permission.enums.ManagerRole; import au.com.royalpay.payment.tools.utils.PageListUtils; import com.alibaba.fastjson.JSONObject; import com.github.miemiedev.mybatis.paginator.domain.Order; @@ -40,7 +40,7 @@ import java.util.Date; import java.util.List; import java.util.Random; -import static java.math.BigDecimal.ROUND_DOWN; +import static java.math.RoundingMode.DOWN; /** * Created by yishuqian on 08/12/2016. @@ -141,7 +141,7 @@ public class PartnerLMServiceImp implements PartnerLMService { params.put("status", 1); params.put("act_type", ActTypeEnum.partner.toString()); List openList = actPartnerLMMapper.actList(params); - if (!openList.isEmpty() && openList.size() > 0) { + if (!openList.isEmpty()) { throw new Exception("存在已经开启的红包返现活动,请先关闭旧的活动再开启新的活动"); } } @@ -171,7 +171,7 @@ public class PartnerLMServiceImp implements PartnerLMService { JSONObject res = actPartnerLMMapper.findOne(act_id); if (res.getString("act_type").equals(ActTypeEnum.redpack.toString())) { List prize_type_list = actPrizeTypeMapper.listPrizeTypes(act_id, new PageBounds(Order.formString("rate.desc ,weight.asc"))); - if (!prize_type_list.isEmpty() && prize_type_list.size() > 0) { + if (!prize_type_list.isEmpty()) { for (JSONObject prize_type : prize_type_list) { JSONObject params = new JSONObject(); params.put("red_pack_type_id", prize_type.getString("type_id")); @@ -182,7 +182,7 @@ public class PartnerLMServiceImp implements PartnerLMService { } } List blackList = actBlackListMapper.listByActId(act_id); - if (blackList != null && blackList.size() > 0) { + if (blackList != null && !blackList.isEmpty()) { String partnerCodes = ""; for (JSONObject b : blackList) { partnerCodes += b.getString("partner_code") + ","; @@ -204,7 +204,7 @@ public class PartnerLMServiceImp implements PartnerLMService { params.put("act_type", ActTypeEnum.partner.toString()); params.put("status", 1); List actList = actPartnerLMMapper.actList(params); - if (!actList.isEmpty() && actList.size() > 0) { + if (!actList.isEmpty()) { JSONObject act = actList.get(0); String act_id = act.getString("act_id"); BigDecimal rule_order_total = act.getBigDecimal("rule_order_total"); @@ -217,7 +217,7 @@ public class PartnerLMServiceImp implements PartnerLMService { return; } //int random = new Random().nextInt(100); - int random = (int) (Math.random() * 100); + int random = new Random().nextInt(100); if (random > probability) { return; } @@ -229,8 +229,8 @@ public class PartnerLMServiceImp implements PartnerLMService { return; } Double max = new BigDecimal(orderAmount).multiply(new BigDecimal(rule_order_rate)).compareTo(rule_max_lucky_money) > 0 ? - rule_max_lucky_money.setScale(2, ROUND_DOWN).doubleValue() : - new BigDecimal(orderAmount).multiply(new BigDecimal(rule_order_rate)).setScale(2, ROUND_DOWN).doubleValue(); + rule_max_lucky_money.setScale(2, DOWN).doubleValue() : + new BigDecimal(orderAmount).multiply(new BigDecimal(rule_order_rate)).setScale(2, DOWN).doubleValue(); Double luckyMoney = max > 1 ? Math.random() * (max - 1) + 1 : 1; BigDecimal nowTotal = actPartnerLMLogMapper.getTotalLuckyMoney(act_id); @@ -244,7 +244,7 @@ public class PartnerLMServiceImp implements PartnerLMService { relationParams.put("client_id", client_id); relationParams.put("channel", "Wechat"); List relationList = actPartnerWechatRelationMapper.relationList(relationParams); - if (!relationList.isEmpty() && relationList.size() > 0) { + if (!relationList.isEmpty()) { int accountSize = relationList.size(); int randomAccount = new Random().nextInt(accountSize); String open_id = relationList.get(randomAccount).getString("customer_id"); @@ -274,7 +274,7 @@ public class PartnerLMServiceImp implements PartnerLMService { } String rpOpenId = customerRelation.getString(redpackApi.getOpenIdKey()); wechatRedpack.setSendName(sendName).setOpenId(rpOpenId).setActName(actName) - .setRemark("商家激励计划").setAmount(new BigDecimal(luckyMoney).setScale(2, ROUND_DOWN)).setWishing(wishing).setNotifyUrl(notifyUrl); + .setRemark("商家激励计划").setAmount(new BigDecimal(luckyMoney).setScale(2, DOWN)).setWishing(wishing).setNotifyUrl(notifyUrl); String redPacketId = redpackApi.sendRedpack(wechatRedpack).getString("out_biz_no"); send.put("red_packet_id", redPacketId); actPartnerLMLogMapper.saveLog(send); @@ -327,10 +327,10 @@ public class PartnerLMServiceImp implements PartnerLMService { params.remove("customer_id"); params.put("client_id", client.getIntValue("client_id")); List partnerBinds = actPartnerWechatRelationMapper.relationList(params); - if (!relList.isEmpty() && relList.size() > 0) { + if (!relList.isEmpty()) { throw new Exception("You have bind your wechat account !"); } - if (!partnerBinds.isEmpty() && partnerBinds.size() > 0) { + if (!partnerBinds.isEmpty()) { throw new Exception("The merchant has been bind by other wechat!"); } // JSONObject updateObj = new JSONObject(); @@ -371,10 +371,10 @@ public class PartnerLMServiceImp implements PartnerLMService { params.remove("customer_id"); params.put("client_id", client.getIntValue("client_id")); List partnerBinds = actPartnerWechatRelationMapper.relationList(params); - if (!relList.isEmpty() && relList.size() > 0) { + if (!relList.isEmpty()) { throw new Exception("You have bind your alipay account !"); } - if (!partnerBinds.isEmpty() && partnerBinds.size() > 0) { + if (!partnerBinds.isEmpty()) { throw new Exception("The merchant has been bind by other alipay!"); } JSONObject relation = new JSONObject(); @@ -444,7 +444,7 @@ public class PartnerLMServiceImp implements PartnerLMService { params.put("customer_id", customerId); params.put("channel", channel); List wechatBinds = actPartnerWechatRelationMapper.relationList(params); - if (!partnerBinds.isEmpty() && partnerBinds.size() > 0) { + if (!partnerBinds.isEmpty()) { JSONObject partnerBind = partnerBinds.get(0); if (partnerBinds.get(0).getString("customer_id").equals(customerId)) { res.put("status", 3); @@ -454,7 +454,7 @@ public class PartnerLMServiceImp implements PartnerLMService { } } else { res.put("status", 0); - if (!wechatBinds.isEmpty() && wechatBinds.size() > 0) { + if (!wechatBinds.isEmpty()) { res.put("status", 2); } } diff --git a/src/main/java/au/com/royalpay/payment/manage/redpack/core/impls/RedpackServiceImpl.java b/src/main/java/au/com/royalpay/payment/manage/redpack/core/impls/RedpackServiceImpl.java index 2b2be2755..cdc343024 100644 --- a/src/main/java/au/com/royalpay/payment/manage/redpack/core/impls/RedpackServiceImpl.java +++ b/src/main/java/au/com/royalpay/payment/manage/redpack/core/impls/RedpackServiceImpl.java @@ -31,6 +31,7 @@ import org.springframework.util.Assert; import javax.annotation.Resource; import java.math.BigDecimal; +import java.math.RoundingMode; import java.util.ArrayList; import java.util.Date; import java.util.List; @@ -153,7 +154,7 @@ public class RedpackServiceImpl implements RedpackService { int min = CurrencyAmountUtils.toCent(config.getBigDecimal("min_amount"), "CNY"); int max = CurrencyAmountUtils.toCent(config.getBigDecimal("max_amount"), "CNY"); - int amount = min == max ? min : RandomUtils.nextInt(0,max - min) + min; + int amount = min == max ? min : RandomUtils.nextInt(0, max - min) + min; WechatRedpack wechatRedpack = new WechatRedpack(); JSONObject customerRelation = customerMapper.findCustomerByOpenId(openId); MpWechatApi redpackApi = mpWechatApiProvider.getApi("Redpack"); @@ -186,8 +187,8 @@ public class RedpackServiceImpl implements RedpackService { if (redpack_counts > 0) { for (int i = 0; i < redpack_counts; i++) { BigDecimal amount = amountFrom.equals(amountTo) ? amountFrom - : amountFrom.add(BigDecimal.valueOf(RandomUtils.nextInt(0,amountTo.subtract(amountFrom).multiply(hundred).intValue())).divide(hundred, - 2, BigDecimal.ROUND_DOWN)); + : amountFrom.add(BigDecimal.valueOf(RandomUtils.nextInt(0, amountTo.subtract(amountFrom).multiply(hundred).intValue())).divide(hundred, + 2, RoundingMode.DOWN)); JSONObject prize = new JSONObject(); String prefix = DateFormatUtils.format(new Date(), "yyyyMMddHHmmssSSS"); String red_packet_order_id = prefix + RandomStringUtils.random(28 - prefix.length(), true, true); @@ -216,7 +217,7 @@ public class RedpackServiceImpl implements RedpackService { params.put("act_type", ActTypeEnum.redpack.toString()); params.put("status", 1); List actList = actPartnerLMMapper.actList(params); - if (!actList.isEmpty() && actList.size() > 0) { + if (!actList.isEmpty()) { JSONObject act = actList.get(0); String act_id = act.getString("act_id"); @@ -224,14 +225,14 @@ public class RedpackServiceImpl implements RedpackService { blackListParams.put("act_id", act_id); blackListParams.put("client_id", client_id); List blackList = actBlackListMapper.list(blackListParams); - if (blackList != null && blackList.size() > 0) { + if (blackList != null && !blackList.isEmpty()) { logger.error("client_id:" + client_id + ",在活动" + act_id + "的黑名单下"); return; } BigDecimal rule_order_total = act.getBigDecimal("rule_order_total"); int probability = act.getIntValue("probability"); if (orderAmount.compareTo(rule_order_total) < 0) { - logger.error("订单不满足金额" + rule_order_total + ",跳过"); + logger.error("订单不满足金额{},跳过", rule_order_total); return; } // int random = new Random().nextInt(100); @@ -246,8 +247,8 @@ public class RedpackServiceImpl implements RedpackService { relationParams.put("client_id", client_id); relationParams.put("channel", "Wechat"); List relationList = actPartnerWechatRelationMapper.relationList(relationParams); - if (relationList.isEmpty() || relationList.size() == 0) { - logger.error("client_id:" + client_id + ";没有绑定的wechat!跳过"); + if (relationList.isEmpty()) { + logger.error("client_id:{};没有绑定的wechat!跳过", client_id); return; } @@ -256,7 +257,7 @@ public class RedpackServiceImpl implements RedpackService { // add 每天只能得到100个红包的限制 int getTotalCounts = getRedPacketsByOpenid(open_id, new Date()); if (getTotalCounts >= 100) { - logger.error("open_id:" + open_id + "当日红包发送数量已到达100!跳过"); + logger.error("open_id:{}当日红包发送数量已到达100!跳过", open_id); return; } List prizeTypes = actPrizeTypeMapper.listAvailableTypes(BigDecimal.ONE, act_id); @@ -264,7 +265,7 @@ public class RedpackServiceImpl implements RedpackService { for (JSONObject prizeType : prizeTypes) { totalWeight += prizeType.getIntValue("weight"); } - int ran = RandomUtils.nextInt(0,totalWeight); + int ran = RandomUtils.nextInt(0, totalWeight); for (JSONObject prizeType : prizeTypes) { ran -= prizeType.getIntValue("weight"); @@ -325,16 +326,16 @@ public class RedpackServiceImpl implements RedpackService { @Override public void sendAlipayLuckyMoney(String orderId, BigDecimal orderAmount, int client_id) throws RedPackException { logger.info("======================sendAlipayLuckyMoney===================="); - logger.info("======================orderId:" + orderId + ";orderAmount:" + orderAmount + ";client_id:" + client_id + "===================="); + logger.info("======================orderId:{};orderAmount:{};client_id:{}====================", orderId, orderAmount, client_id); JSONObject params = new JSONObject(); params.put("act_type", ActTypeEnum.redpack.toString()); params.put("status", 1); List actList = actPartnerLMMapper.actList(params); - if (!actList.isEmpty() && actList.size() > 0) { + if (!actList.isEmpty()) { JSONObject act = actList.get(0); if (orderAmount.compareTo(act.getBigDecimal("rule_order_total")) < 0) { - logger.info("支付金额不足" + act.getDouble("rule_order_total") + "跳过"); + logger.info("支付金额不足{}跳过", act.getDouble("rule_order_total")); return; } @@ -344,8 +345,8 @@ public class RedpackServiceImpl implements RedpackService { blackListParams.put("act_id", act_id); blackListParams.put("client_id", client_id); List blackList = actBlackListMapper.list(blackListParams); - if (blackList != null && blackList.size() > 0) { - logger.error("client_id:" + client_id + ",在活动" + act_id + "的黑名单下"); + if (blackList != null && !blackList.isEmpty()) { + logger.error("client_id:{},在活动{}的黑名单下", client_id, act_id); return; } JSONObject actPartnerParams = new JSONObject(); @@ -373,8 +374,8 @@ public class RedpackServiceImpl implements RedpackService { relationParams.put("client_id", client_id); relationParams.put("channel", "Alipay"); List relationList = actPartnerWechatRelationMapper.relationList(relationParams); - if (relationList.isEmpty() || relationList.size() == 0) { - logger.error("client_id:" + client_id + ";没有绑定的Alipay!跳过"); + if (relationList.isEmpty()) { + logger.error("client_id:{};没有绑定的Alipay!跳过", client_id); return; } @@ -384,7 +385,7 @@ public class RedpackServiceImpl implements RedpackService { for (JSONObject prizeType : prizeTypes) { totalWeight += prizeType.getIntValue("weight"); } - int ran = RandomUtils.nextInt(0,totalWeight); + int ran = RandomUtils.nextInt(0, totalWeight); for (JSONObject prizeType : prizeTypes) { ran -= prizeType.getIntValue("weight"); diff --git a/src/main/java/au/com/royalpay/payment/manage/riskbusiness/core/impl/RiskBusinessServiceImpl.java b/src/main/java/au/com/royalpay/payment/manage/riskbusiness/core/impl/RiskBusinessServiceImpl.java index 48e3186b6..c8e9ddb51 100644 --- a/src/main/java/au/com/royalpay/payment/manage/riskbusiness/core/impl/RiskBusinessServiceImpl.java +++ b/src/main/java/au/com/royalpay/payment/manage/riskbusiness/core/impl/RiskBusinessServiceImpl.java @@ -730,7 +730,7 @@ public class RiskBusinessServiceImpl implements RiskBusinessService, ManagerTodo Context ctx = getMailContext(event); ctx.setVariable("refuse", true); List findAllMaterials = riskMaterialMapper.findAllMaterials(riskId); - if (findAllMaterials == null || findAllMaterials.size() == 0) { + if (findAllMaterials == null || findAllMaterials.isEmpty()) { ctx.setVariable("refuse_description", ""); } else { ctx.setVariable("refuse_description", findAllMaterials.get(0).getString("refuse_description")); @@ -942,7 +942,7 @@ public class RiskBusinessServiceImpl implements RiskBusinessService, ManagerTodo @Override public JSONObject getRiskMaterial(JSONObject param) { List riskMaterialList = riskMaterialMapper.findAllMaterials(param.getString("risk_id")); - if (riskMaterialList != null && riskMaterialList.size() > 0) { + if (riskMaterialList != null && !riskMaterialList.isEmpty()) { JSONObject fileNew = riskMaterialList.get(0); List files = riskFileMapper.findAllFiles(fileNew.getString("material_id")); for (JSONObject file : files) { @@ -973,7 +973,7 @@ public class RiskBusinessServiceImpl implements RiskBusinessService, ManagerTodo @Transactional public void completeEventRealOrderIds() { List riskEventList = getRiskEvents(null); - if (riskEventList != null && riskEventList.size() > 0) { + if (riskEventList != null && !riskEventList.isEmpty()) { for (JSONObject riskEvent : riskEventList) { String clientMoniker = riskEvent.getString("client_moniker"); JSONObject client = clientMapper.findClientByMonikerAll(clientMoniker); @@ -989,7 +989,7 @@ public class RiskBusinessServiceImpl implements RiskBusinessService, ManagerTodo client.getIntValue("client_id"), systemTransactionIdArr[i], new PageBounds(Order.formString("transaction_time.desc"))); - if (transactionList != null && transactionList.size() > 0) + if (transactionList != null && !transactionList.isEmpty()) realOrderIds.add(transactionList.get(0).getString("order_id")); } riskEvent.put("real_order_ids", StringUtils.join(realOrderIds, ",")); @@ -1192,7 +1192,7 @@ public class RiskBusinessServiceImpl implements RiskBusinessService, ManagerTodo JSONObject result = new JSONObject(); result.put("notice_flag", false); - if (riskEventList != null && riskEventList.size() > 0) { + if (riskEventList != null && !riskEventList.isEmpty()) { result.put("notice_flag", true); } return result; @@ -1232,7 +1232,7 @@ public class RiskBusinessServiceImpl implements RiskBusinessService, ManagerTodo String alipayMaterials = riskEvent.getString("alipay_materials"); if (StringUtils.isNotBlank(alipayMaterials)) { List alipayMaterialRemarkList = JSONObject.parseArray(alipayMaterials, JSONObject.class); - if (alipayMaterialRemarkList != null && alipayMaterialRemarkList.size() > 0) { + if (alipayMaterialRemarkList != null && !alipayMaterialRemarkList.isEmpty()) { for (int i = 0; i < alipayMaterialRemarkList.size(); i++) { materialsRemark.add(alipayMaterialRemarkList.get(i).getString("question" + (i + 1))); } diff --git a/src/main/java/au/com/royalpay/payment/manage/signin/core/impls/SignInAccountServiceImpl.java b/src/main/java/au/com/royalpay/payment/manage/signin/core/impls/SignInAccountServiceImpl.java index d8d6fd340..6b556e27a 100644 --- a/src/main/java/au/com/royalpay/payment/manage/signin/core/impls/SignInAccountServiceImpl.java +++ b/src/main/java/au/com/royalpay/payment/manage/signin/core/impls/SignInAccountServiceImpl.java @@ -181,7 +181,7 @@ public class SignInAccountServiceImpl implements SignInAccountService, Applicati client.put("client_less_file", false); if ((client.getIntValue("approve_result") == 2 || client.getIntValue("open_status") == 10 || client.getIntValue("approve_result") == 1 || client.getIntValue("open_status") == 5)) { List clientFiles = clientFilesMapper.findAllClientFile(client.getIntValue("client_id")); - if (clientFiles != null && clientFiles.size() > 0) { + if (clientFiles != null && !clientFiles.isEmpty()) { clientFiles = clientFiles.stream().filter(fileJson -> ((fileJson.getIntValue("status") == 1 || fileJson.getIntValue("status") == 2))).collect(Collectors.toList()); String[] fileKeys = {"client_bank_file", "client_company_file", "client_id_file", "client_agree_file"}; for (String fileKey : fileKeys) { @@ -426,7 +426,7 @@ public class SignInAccountServiceImpl implements SignInAccountService, Applicati throw new Exception("Email Address of this partner is null,Please contact customer service"); } List accounts = clientAccountMapper.listAdminAccounts(client.getIntValue("client_id")); - if (accounts != null && accounts.size() > 0) { + if (accounts != null && !accounts.isEmpty()) { String codeKey = signInStatusManager.addChangepasswordVerifyCode(client_moniker); String url = PlatformEnvironment.getEnv().concatUrl("/global/userstatus/partner_changepassword_page/" + codeKey); @@ -466,7 +466,7 @@ public class SignInAccountServiceImpl implements SignInAccountService, Applicati // throw new Exception("Email Address of this partner is null,Please contact customer service"); // } // List accounts = clientAccountMapper.listAdminAccounts(client.getIntValue("client_id")); -// if (accounts != null && accounts.size() > 0) { +// if (accounts != null && !accounts.isEmpty()) { // // String codeKey = signInStatusManager.addChangepasswordVerifyCode(client_moniker); // String url = PlatformEnvironment.getEnv().concatUrl("/global/userstatus/partner_changepassword_page/" + codeKey); @@ -694,7 +694,7 @@ public class SignInAccountServiceImpl implements SignInAccountService, Applicati boolean clientFilesIsLess = false; for (int i = 0; i < FILE_KEYS.length; i++) { String fileKey = FILE_KEYS[i]; - if (clientFiles != null && clientFiles.size() > 0) { + if (clientFiles != null && !clientFiles.isEmpty()) { List clientFileUrl = clientFiles.stream() .filter(fileJson -> (fileKey.equals(fileJson.getString("file_name")) && (fileJson.getIntValue("status") == 1 || fileJson.getIntValue("status") == 2))) .sorted((log1, log2) -> log2.getDate("last_update_date").compareTo(log1.getDate("last_update_date"))) @@ -705,7 +705,7 @@ public class SignInAccountServiceImpl implements SignInAccountService, Applicati return params; }) .collect(Collectors.toList()); - if (clientFileUrl != null && clientFileUrl.size() > 0) { + if (clientFileUrl != null && !clientFileUrl.isEmpty()) { JSONObject fileJson = new JSONObject(); fileJson.put("key", PUT_KEYS[i]); fileJson.put("name", FILE_NAMES[i]); @@ -726,7 +726,7 @@ public class SignInAccountServiceImpl implements SignInAccountService, Applicati JSONObject fileJson = new JSONObject(); fileJson.put("key", PUT_KEYS[i]); fileJson.put("name", FILE_NAMES[i]); - if (clientBackToFileUrl != null && clientBackToFileUrl.size() > 0) { + if (clientBackToFileUrl != null && !clientBackToFileUrl.isEmpty()) { if ("client_agree_file".equals(fileKey)) { List agreeFile = new ArrayList<>(); agreeFile.add(clientBackToFileUrl.get(0)); @@ -791,7 +791,7 @@ public class SignInAccountServiceImpl implements SignInAccountService, Applicati return params; }) .collect(Collectors.toList()); - if (clientFileUrl.size() > 0) { + if (!clientFileUrl.isEmpty()) { result.put("kyc_utility_bill_file", clientFileUrl); } } @@ -826,7 +826,7 @@ public class SignInAccountServiceImpl implements SignInAccountService, Applicati return params; }) .collect(Collectors.toList()); - if (clientFileUrl.size() > 0) { + if (!clientFileUrl.isEmpty()) { result.put("kyc_utility_bill_file", clientFileUrl); } } diff --git a/src/main/java/au/com/royalpay/payment/manage/signin/core/impls/SignInStatusManagerImpl.java b/src/main/java/au/com/royalpay/payment/manage/signin/core/impls/SignInStatusManagerImpl.java index 0f9952ecc..d68279e5e 100644 --- a/src/main/java/au/com/royalpay/payment/manage/signin/core/impls/SignInStatusManagerImpl.java +++ b/src/main/java/au/com/royalpay/payment/manage/signin/core/impls/SignInStatusManagerImpl.java @@ -10,6 +10,7 @@ import au.com.royalpay.payment.tools.env.PlatformEnvironment; import au.com.royalpay.payment.tools.exceptions.BadRequestException; import au.com.royalpay.payment.tools.exceptions.ForbiddenException; import au.com.royalpay.payment.tools.permission.enums.ManagerRole; +import au.com.royalpay.payment.tools.utils.JsonHelper; import au.com.royalpay.payment.tools.utils.QRCodeUtils; import au.com.royalpay.payment.tools.utils.apple.AppleAuthUtils; import au.com.royalpay.payment.tools.utils.apple.UserClaim; @@ -298,10 +299,10 @@ public class SignInStatusManagerImpl implements SignInStatusManager { } JSONObject account = signInAccountService.clientAppleSignIn(userClaim.getSub()); if (account == null || account.isEmpty()) { - return new JSONObject() {{ - put("apple_userid", userClaim.getSub()); - put("bind_status", false); - }}; + return JsonHelper.newJson(json -> { + json.put("apple_userid", userClaim.getSub()); + json.put("bind_status", false); + }); } String statusKey = newStatusKey(); JSONObject result = new JSONObject(); @@ -348,7 +349,7 @@ public class SignInStatusManagerImpl implements SignInStatusManager { getlockRandomCodeId(codeId); String statusKey = newStatusKey(); JSONObject account = new JSONObject(); - if (device != null && device.size() > 0) { + if (device != null && !device.isEmpty()) { account = signInAccountService.getClient(device.getString("account_id")); } if (account == null || account.size() <= 0) { @@ -366,7 +367,7 @@ public class SignInStatusManagerImpl implements SignInStatusManager { getlockRandomCodeId(codeId); String statusKey = newStatusKey(); JSONObject account = new JSONObject(); - if (wxUser != null && wxUser.size() > 0) { + if (wxUser != null && !wxUser.isEmpty()) { account = signInAccountService.clientWechatSignIn(wxUser.getString("openid")); } if (account == null || account.size() <= 0) { @@ -464,10 +465,10 @@ public class SignInStatusManagerImpl implements SignInStatusManager { String nickName = codeValue.split("&")[1]; String unionId = codeValue.split("&")[2]; stringRedisTemplate.delete(rediskey); - return new JSONObject() {{ - put("nick_name", nickName); - put("union_id", unionId); - }}; + return JsonHelper.newJson(json -> { + json.put("nick_name", nickName); + json.put("union_id", unionId); + }); } private String getClientLoginPhoneBindRedisKey(String phone, String nationCode) { diff --git a/src/main/java/au/com/royalpay/payment/manage/system/core/impl/MailGunServiceImpl.java b/src/main/java/au/com/royalpay/payment/manage/system/core/impl/MailGunServiceImpl.java index 8ee553227..2f059663b 100644 --- a/src/main/java/au/com/royalpay/payment/manage/system/core/impl/MailGunServiceImpl.java +++ b/src/main/java/au/com/royalpay/payment/manage/system/core/impl/MailGunServiceImpl.java @@ -1,14 +1,12 @@ package au.com.royalpay.payment.manage.system.core.impl; import au.com.royalpay.payment.manage.mappers.system.MailSendMapper; -import au.com.royalpay.payment.manage.merchants.core.ClientManager; import au.com.royalpay.payment.manage.system.core.MailGunService; import au.com.royalpay.payment.tools.connections.attachment.core.AttachmentClient; import au.com.royalpay.payment.tools.mail.MailGunClient; import au.com.royalpay.payment.tools.mail.SendMail; - +import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; - import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; import org.jsoup.Jsoup; @@ -20,16 +18,11 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; +import javax.annotation.Resource; import java.io.IOException; import java.net.URISyntaxException; import java.net.URLDecoder; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.annotation.Resource; +import java.util.*; @Service public class MailGunServiceImpl implements MailGunService { @@ -54,7 +47,7 @@ public class MailGunServiceImpl implements MailGunService { String myData = mailgunNotify.get("my-custom-data"); String recipient = mailgunNotify.get("recipient"); if (StringUtils.isNotEmpty(myData) && StringUtils.isNotEmpty(recipient)) { - JSONObject tmpJSONObject = JSONObject.parseObject(myData); + JSONObject tmpJSONObject = JSON.parseObject(myData); String[] mailAddresses = recipient.split(","); for (String mailAddress : mailAddresses) { JSONObject record = new JSONObject(); @@ -81,7 +74,7 @@ public class MailGunServiceImpl implements MailGunService { String myData = myDataArr[0]; String recipient = recipientArr[0]; if (StringUtils.isNotEmpty(myData) && StringUtils.isNotEmpty(recipient)) { - JSONObject tmpJSONObject = JSONObject.parseObject(myData); + JSONObject tmpJSONObject = JSON.parseObject(myData); String[] mailAddresses = recipient.split(","); for (String mailAddress : mailAddresses) { JSONObject record = new JSONObject(); diff --git a/src/main/java/au/com/royalpay/payment/manage/tradelog/beans/TradeLogQuery.java b/src/main/java/au/com/royalpay/payment/manage/tradelog/beans/TradeLogQuery.java index 1cfccc151..b4f0fbfa5 100644 --- a/src/main/java/au/com/royalpay/payment/manage/tradelog/beans/TradeLogQuery.java +++ b/src/main/java/au/com/royalpay/payment/manage/tradelog/beans/TradeLogQuery.java @@ -78,7 +78,7 @@ public class TradeLogQuery { tradeTypes.add(type.getGateway()); } } - if (tradeTypes.size() > 0) { + if (!tradeTypes.isEmpty()) { params.put("trade_type", tradeTypes); } } diff --git a/src/main/java/au/com/royalpay/payment/manage/tradelog/core/impls/ReportConfigServiceImp.java b/src/main/java/au/com/royalpay/payment/manage/tradelog/core/impls/ReportConfigServiceImp.java index 36e51e3ba..47073eaa1 100644 --- a/src/main/java/au/com/royalpay/payment/manage/tradelog/core/impls/ReportConfigServiceImp.java +++ b/src/main/java/au/com/royalpay/payment/manage/tradelog/core/impls/ReportConfigServiceImp.java @@ -20,9 +20,9 @@ public class ReportConfigServiceImp implements ReportConfigService { @Override public JSONObject getReportConfig(){ List configs = reportConfigMapper.listReportConfig(); - if (!configs.isEmpty() && configs.size()>0){ + if (!configs.isEmpty()) { return configs.get(0); - }else { + } else { return null; } } diff --git a/src/main/java/au/com/royalpay/payment/manage/tradelog/core/impls/TradeLogServiceImpl.java b/src/main/java/au/com/royalpay/payment/manage/tradelog/core/impls/TradeLogServiceImpl.java index e8e35e2cb..67c3765b9 100644 --- a/src/main/java/au/com/royalpay/payment/manage/tradelog/core/impls/TradeLogServiceImpl.java +++ b/src/main/java/au/com/royalpay/payment/manage/tradelog/core/impls/TradeLogServiceImpl.java @@ -32,6 +32,7 @@ import au.com.royalpay.payment.tools.permission.enums.ManagerRole; import au.com.royalpay.payment.tools.utils.CurrencyAmountUtils; import au.com.royalpay.payment.tools.utils.PageListUtils; import au.com.royalpay.payment.tools.utils.TimeZoneUtils; +import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.github.miemiedev.mybatis.paginator.domain.Order; import com.github.miemiedev.mybatis.paginator.domain.PageBounds; @@ -428,7 +429,7 @@ public class TradeLogServiceImpl implements TradeLogService { order.put("status_str", statusStr); if (StringUtils.equalsIgnoreCase("rpaypmt_card", order.getString("channel")) || StringUtils.equalsIgnoreCase("rpaypmt_dd", order.getString("channel"))) { - JSONObject extParams = JSONObject.parseObject(order.getString("ext_params")); + JSONObject extParams = JSON.parseObject(order.getString("ext_params")); if (extParams != null) { order.putAll(extParams); } @@ -1358,7 +1359,7 @@ public class TradeLogServiceImpl implements TradeLogService { for (int i = 0; i < childs.size(); i++) { params.put("client_id", childs.get(i).getInteger("client_id")); PageList childLogs = transactionMapper.listSettlementLog(params, new PageBounds(1, 100000000, Order.formString("clearing_time.desc"))); - if (childLogs.size() > 0) { + if (!childLogs.isEmpty()) { addSheet(i + 1, workbook, childs.get(i), childLogs); } } @@ -1455,9 +1456,9 @@ public class TradeLogServiceImpl implements TradeLogService { HSSFRichTextString text0 = new HSSFRichTextString(client.getString("short_name")); HSSFRichTextString text1 = new HSSFRichTextString(client.getString("client_moniker")); HSSFRichTextString text2 = new HSSFRichTextString(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(dataItem.getDate("report_date"))); - HSSFRichTextString text3 = new HSSFRichTextString(dataItem.getBigDecimal("total").setScale(2, BigDecimal.ROUND_HALF_DOWN).toString()); - HSSFRichTextString text4 = new HSSFRichTextString(dataItem.getBigDecimal("income").setScale(2, BigDecimal.ROUND_HALF_DOWN).toString()); - HSSFRichTextString text5 = new HSSFRichTextString(dataItem.getBigDecimal("fee").setScale(2, BigDecimal.ROUND_HALF_DOWN).toString()); + HSSFRichTextString text3 = new HSSFRichTextString(dataItem.getBigDecimal("total").setScale(2, RoundingMode.HALF_DOWN).toString()); + HSSFRichTextString text4 = new HSSFRichTextString(dataItem.getBigDecimal("income").setScale(2, RoundingMode.HALF_DOWN).toString()); + HSSFRichTextString text5 = new HSSFRichTextString(dataItem.getBigDecimal("fee").setScale(2, RoundingMode.HALF_DOWN).toString()); cell0.setCellValue(text0); cell1.setCellValue(text1); cell2.setCellValue(text2); @@ -1638,13 +1639,6 @@ public class TradeLogServiceImpl implements TradeLogService { List oneClear = transactionMapper.getMerchantAmount(dateParams); Date now = new Date(); for (JSONObject clientClear : oneClear) { - // JSONObject params = new JSONObject(); - // params.put("client_id",clientClear.getIntValue("client_id")); - // params.put("clearing_time",clientClear.getDate("clearing_time")); - // List clientTrans = austracDataMapper.getTransactionTotal(params); - // if (!clientTrans.isEmpty() && clientTrans.size()>0){ - // austracDataMapper.delete(clientClear.getIntValue("client_id"),clientClear.getDate("clearing_time")); - // } austracDataMapper.delete(clientClear.getIntValue("client_id"), clientClear.getDate("clearing_time")); BigDecimal lastTransTotal = austracDataMapper.getClientLastTransactionTotal(clientClear.getIntValue("client_id"), clientClear.getDate("clearing_time")); @@ -1995,7 +1989,7 @@ public class TradeLogServiceImpl implements TradeLogService { List settlementLogDetailList = new ArrayList<>(); try { parmerters.put("logo", logo.getInputStream()); - if (clientOrderList.size() > 0) { + if (!clientOrderList.isEmpty()) { List clientOrders = new ArrayList<>(clientOrderList.size()); clientOrderList.parallelStream().forEach(p -> clientOrders.add(p.getInteger("clearing_order"))); settlementLogDetailList = transactionMapper.getSettlementLogDetailList(clientOrders); diff --git a/src/main/java/au/com/royalpay/payment/manage/tradelog/refund/impls/RefundServiceImpl.java b/src/main/java/au/com/royalpay/payment/manage/tradelog/refund/impls/RefundServiceImpl.java index 4a6623cbc..820fb48ab 100644 --- a/src/main/java/au/com/royalpay/payment/manage/tradelog/refund/impls/RefundServiceImpl.java +++ b/src/main/java/au/com/royalpay/payment/manage/tradelog/refund/impls/RefundServiceImpl.java @@ -194,7 +194,7 @@ public class RefundServiceImpl implements RefundService, ApplicationEventPublish BigDecimal realAmount = original ? fee : CurrencyAmountUtils.toAmount(fee, order.getString("currency")); JSONObject refundConfig = checkRefundAuditFlag(); - if (partnerAccount != null && refundConfig != null && refundConfig.size() > 0 && refundConfig.getBoolean("refundAudit")) { + if (partnerAccount != null && refundConfig != null && !refundConfig.isEmpty() && refundConfig.getBoolean("refundAudit")) { if (realAmount.compareTo(refundConfig.getBigDecimal("refundAuditAmount")) > 0) { // 订单需要审核 boolean casherRefund = reviewNewRefundOrder(orderId, realAmount, remark, partnerAccount, manager); diff --git a/src/main/java/au/com/royalpay/payment/manage/tradelog/refund/listeners/RefundSendTemplateMessageSender.java b/src/main/java/au/com/royalpay/payment/manage/tradelog/refund/listeners/RefundSendTemplateMessageSender.java index 3826034d7..c30aa4071 100644 --- a/src/main/java/au/com/royalpay/payment/manage/tradelog/refund/listeners/RefundSendTemplateMessageSender.java +++ b/src/main/java/au/com/royalpay/payment/manage/tradelog/refund/listeners/RefundSendTemplateMessageSender.java @@ -18,7 +18,7 @@ import org.springframework.context.ApplicationListener; import org.springframework.stereotype.Service; import javax.annotation.Resource; -import java.math.BigDecimal; +import java.math.RoundingMode; import java.util.List; import java.util.TimeZone; @@ -59,7 +59,7 @@ public class RefundSendTemplateMessageSender implements ApplicationListener