From c18ec3846c8483975de2224c1ecac9470e9b2804 Mon Sep 17 00:00:00 2001
From: puzhibing <393733352@qq.com>
Date: 星期三, 16 八月 2023 19:21:36 +0800
Subject: [PATCH] 同步代码

---
 user/guns-admin/src/main/java/com/supersavedriving/user/modular/system/service/impl/AppUserServiceImpl.java |  309 +++++++++++++++++++++++++++++++++++++--------------
 1 files changed, 225 insertions(+), 84 deletions(-)

diff --git a/user/guns-admin/src/main/java/com/supersavedriving/user/modular/system/service/impl/AppUserServiceImpl.java b/user/guns-admin/src/main/java/com/supersavedriving/user/modular/system/service/impl/AppUserServiceImpl.java
index 9db79f1..382c4f4 100644
--- a/user/guns-admin/src/main/java/com/supersavedriving/user/modular/system/service/impl/AppUserServiceImpl.java
+++ b/user/guns-admin/src/main/java/com/supersavedriving/user/modular/system/service/impl/AppUserServiceImpl.java
@@ -16,6 +16,8 @@
 import com.supersavedriving.user.modular.system.util.MallBook.model.InterfaceResponse;
 import com.supersavedriving.user.modular.system.util.MallBook.model.PaymentOrder;
 import com.supersavedriving.user.modular.system.util.MallBook.model.PaymentOrderGood;
+import com.supersavedriving.user.modular.system.util.MallBook.model.QueryOrder;
+import com.supersavedriving.user.modular.system.util.MallBook.util.Transfer;
 import com.supersavedriving.user.modular.system.util.MallBook.util.TrhRequest;
 import com.supersavedriving.user.modular.system.util.PayMoneyUtil;
 import com.supersavedriving.user.modular.system.util.RedisUtil;
@@ -37,6 +39,9 @@
 import org.springframework.web.context.request.ServletRequestAttributes;
 
 import javax.servlet.http.HttpServletRequest;
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.math.RoundingMode;
 import java.net.InetAddress;
 import java.text.SimpleDateFormat;
 import java.util.ArrayList;
@@ -72,6 +77,12 @@
 
     @Autowired
     private IAccountChangeDetailService accountChangeDetailService;
+
+    @Autowired
+    private IDriverService driverService;
+
+    @Autowired
+    private ISystemConfigService systemConfigService;
 
     @Value("${callbackPath}")
     private String callbackPath;//支付回调网关地址
@@ -127,8 +138,8 @@
             if(token.length() > 16){
                 key = token.substring(token.length() - 16);
             }
-            redisUtil.setStrValue(key, appUser.getId().toString(), 7 * 24 * 60 * 60);
-            redisUtil.setStrValue("USER_" + appUser.getPhone(), key, 7 * 24 * 60 * 60);
+            redisUtil.setStrValue(key, appUser.getId().toString(), 94608000);
+            redisUtil.setStrValue("USER_" + appUser.getPhone(), key, 94608000);
             return token;
         }
         return null;
@@ -144,60 +155,116 @@
     @Override
     public ResultUtil<SignInToRegisterWarpper> signInToRegister(SignInToRegister signInToRegister) throws Exception {
         SignInToRegisterWarpper warpper = new SignInToRegisterWarpper();
-        if(ToolUtil.isEmpty(signInToRegister.getJscode())){
-            return ResultUtil.paranErr("jscode");
-        }
-        if(ToolUtil.isEmpty(signInToRegister.getEncryptedDataPhone())){
-            return ResultUtil.paranErr("encryptedDataPhone");
-        }
-        if(ToolUtil.isEmpty(signInToRegister.getIvPhone())){
-            return ResultUtil.paranErr("ivPhone");
-        }
-        Code2Session code2Session = weChatUtil.code2Session(signInToRegister.getJscode());
-        if(null != code2Session.getErrcode() && code2Session.getErrcode() != 0){
-            return ResultUtil.error(code2Session.getErrmsg());
-        }
-        String openid = code2Session.getOpenid();
-        String session_key = code2Session.getSession_key();
-        String decrypt = WXCore.decrypt(signInToRegister.getEncryptedDataPhone(), session_key, signInToRegister.getIvPhone());
-        if(ToolUtil.isEmpty(decrypt)){
-            return ResultUtil.error("获取手机号失败");
-        }
-        JSONObject phone = JSON.parseObject(decrypt);
-        String purePhoneNumber = phone.getString("purePhoneNumber");
-        AppUser appUser = this.selectOne(new EntityWrapper<AppUser>().eq("phone", purePhoneNumber).ne("status", 3));
-        if(null == appUser){
-            appUser = new AppUser();
-            appUser.setNickname("亲爱的用户");
-            appUser.setAvatar("https://csxdj.obs.cn-south-1.myhuaweicloud.com:443/66cc269703a84e4da87fb21e2c21ab1f.png");
-            appUser.setPhone(purePhoneNumber);
-            appUser.setOpenid(openid);
-            appUser.setUnionid(code2Session.getUnionid());
-            appUser.setAccountBalance(0D);
-            appUser.setStatus(1);
-            appUser.setCreateTime(new Date());
-            appUser.setIsException(1);
-            appUser.setInviterId(signInToRegister.getInviterId());
-            appUser.setInviterType(signInToRegister.getInviterType());
-            this.insert(appUser);
-            //发送优惠券
-            boolean lock = redisUtil.lock();
-            if(lock){
-                List<CouponWarpper> list = pushCoupon(appUser.getId());
-                redisUtil.unlock();
-                warpper.setCoupons(list);
+        try {
+            if(ToolUtil.isEmpty(signInToRegister.getJscode())){
+                return ResultUtil.paranErr("jscode");
             }
+            if(ToolUtil.isEmpty(signInToRegister.getEncryptedDataPhone())){
+                return ResultUtil.paranErr("encryptedDataPhone");
+            }
+            if(ToolUtil.isEmpty(signInToRegister.getIvPhone())){
+                return ResultUtil.paranErr("ivPhone");
+            }
+            Code2Session code2Session = weChatUtil.code2Session(signInToRegister.getJscode());
+            if(null != code2Session.getErrcode() && code2Session.getErrcode() != 0){
+                return ResultUtil.error(code2Session.getErrmsg());
+            }
+            String openid = code2Session.getOpenid();
+            String session_key = code2Session.getSession_key();
+            String decrypt = WXCore.decrypt(signInToRegister.getEncryptedDataPhone(), session_key, signInToRegister.getIvPhone());
+            if(ToolUtil.isEmpty(decrypt)){
+                return ResultUtil.error("获取手机号失败");
+            }
+            JSONObject phone = JSON.parseObject(decrypt);
+            String purePhoneNumber = phone.getString("purePhoneNumber");
+            AppUser appUser = this.selectOne(new EntityWrapper<AppUser>().eq("phone", purePhoneNumber).ne("status", 3));
+            if(null == appUser){
+                appUser = new AppUser();
+                appUser.setNickname("亲爱的用户");
+                appUser.setAvatar("https://csxdj.obs.cn-south-1.myhuaweicloud.com:443/66cc269703a84e4da87fb21e2c21ab1f.png");
+                appUser.setPhone(purePhoneNumber);
+                appUser.setOpenid(openid);
+                appUser.setUnionid(code2Session.getUnionid());
+                appUser.setAccountBalance(0D);
+                appUser.setStatus(1);
+                appUser.setCreateTime(new Date());
+                appUser.setIsException(1);
+                if(null != signInToRegister.getInviterId()){
+                    appUser.setInviterId(signInToRegister.getInviterId());
+                    appUser.setInviterType(signInToRegister.getInviterType());
+                }
+                this.insert(appUser);
+                //发送优惠券
+                boolean lock = redisUtil.lock(5);
+                if(!lock){
+                    int num1 = 1;
+                    while (num1 <= 10){
+                        Thread.sleep(3000);//等待3秒
+                        lock = redisUtil.lock(5);
+                        if(lock){
+                            break;
+                        }else{
+                            num1++;
+                        }
+                    }
+                }
+                if(lock){
+                    List<CouponWarpper> list = pushCoupon(appUser.getId());
+                    redisUtil.unlock();
+                    warpper.setCoupons(list);
+                }
+            }
+            if(appUser.getStatus() == 2){
+                return ResultUtil.error("账号被冻结");
+            }
+            String token = getToken(appUser);
+            if(ToolUtil.isEmpty(token)){
+                return ResultUtil.error("获取身份凭证失败");
+            }
+            warpper.setToken(token);
+        }catch (Exception e){
+            e.printStackTrace();
+            redisUtil.unlock();
         }
-        if(appUser.getStatus() == 2){
-            return ResultUtil.error("账号被冻结");
-        }
-        String token = getToken(appUser);
-        if(ToolUtil.isEmpty(token)){
-            return ResultUtil.error("获取身份凭证失败");
-        }
-        warpper.setToken(token);
         return ResultUtil.success(warpper);
     }
+
+
+    /**
+     * 转账
+     * @param id
+     * @param merOrderId
+     * @param toUserId
+     * @param amount
+     * @param notifyUrl
+     * @return
+     */
+    public ResultUtil zhaunzhang(Integer id, String merOrderId, String toUserId, Double amount, String notifyUrl){
+        Transfer transfer = new Transfer();
+        transfer.setDepositMerOrderId(merOrderId);
+        transfer.setToUserId(toUserId);
+        transfer.setAmount(new BigDecimal(amount).multiply(new BigDecimal(100)).setScale(0, RoundingMode.HALF_EVEN).longValue() + "");
+        transfer.setOrderName("补贴");
+        transfer.setNotifyUrl(notifyUrl);
+        transfer.setParameter1(id.toString());
+        TrhRequest<Transfer> request = new TrhRequest();
+        InterfaceResponse execute = request.execute(transfer, Transfer.SERVICE_CODE);
+        if("0000".equals(execute.getCode())){
+            JSONObject jsonObject = JSON.parseObject(execute.getResult());
+            Integer status = jsonObject.getInteger("status");//0:待处理;1:成功;2:失败
+            if(2 == status){
+                System.err.println("转账失败");
+                return ResultUtil.error("转账失败");
+            }
+            return ResultUtil.success();
+        }else{
+            System.err.println("转账失败:" + execute.getMsg());
+            return ResultUtil.error(execute.getMsg());
+        }
+    }
+
+
+
 
 
     /**
@@ -209,28 +276,30 @@
                 .eq("coupon_state", 1).eq("status", 1).gt("remaining_quantity", 0));
         List<CouponWarpper> list = new ArrayList<>();
         for (Coupon coupon : coupons) {
-            UserToCoupon userToCoupon = new UserToCoupon();
-            userToCoupon.setCouponId(coupon.getId());
-            userToCoupon.setCreateTime(new Date());
-            userToCoupon.setUserId(userId);
-            userToCoupon.setStatus(1);
-            userToCoupon.setCouponTotal(coupon.getCouponSendQuantity() > coupon.getRemainingQuantity() ?
-                    coupon.getRemainingQuantity() : coupon.getCouponSendQuantity());
-            userToCoupon.setValidCount(userToCoupon.getCouponTotal());
-            userToCoupon.setExpireTime(new Date(System.currentTimeMillis() + (coupon.getCouponValidity() * 24 * 60 * 60 * 1000)));
-            userToCouponService.insert(userToCoupon);
+            Long num = coupon.getCouponSendQuantity() > coupon.getRemainingQuantity() ?
+                    coupon.getRemainingQuantity() : coupon.getCouponSendQuantity();
+            for (int i = 0; i < num; i++) {
+                UserToCoupon userToCoupon = new UserToCoupon();
+                userToCoupon.setCouponId(coupon.getId());
+                userToCoupon.setCreateTime(new Date());
+                userToCoupon.setUserId(userId);
+                userToCoupon.setStatus(1);
+                userToCoupon.setCouponTotal(1);
+                userToCoupon.setValidCount(1);
+                userToCoupon.setExpireTime(new Date(System.currentTimeMillis() + (coupon.getCouponValidity().longValue() * 24L * 60L * 60L * 1000L)));
+                userToCouponService.insert(userToCoupon);
 
+                CouponWarpper couponWarpper = new CouponWarpper();
+                couponWarpper.setCouponConditionalAmount(coupon.getCouponConditionalAmount());
+                couponWarpper.setCouponPreferentialAmount(coupon.getCouponPreferentialAmount());
+                couponWarpper.setCouponName(coupon.getCouponName());
+                couponWarpper.setNumber(userToCoupon.getValidCount());
+                couponWarpper.setExpirationDate(userToCoupon.getExpireTime().getTime());
+                list.add(couponWarpper);
+            }
             coupon.setRemainingQuantity(coupon.getCouponSendQuantity() > coupon.getRemainingQuantity() ? 0 :
                     coupon.getRemainingQuantity() - coupon.getCouponSendQuantity());
             couponService.updateById(coupon);
-
-            CouponWarpper couponWarpper = new CouponWarpper();
-            couponWarpper.setCouponConditionalAmount(coupon.getCouponConditionalAmount());
-            couponWarpper.setCouponPreferentialAmount(coupon.getCouponPreferentialAmount());
-            couponWarpper.setCouponName(coupon.getCouponName());
-            couponWarpper.setNumber(userToCoupon.getValidCount());
-            couponWarpper.setExpirationDate(userToCoupon.getExpireTime().getTime());
-            list.add(couponWarpper);
         }
         return list;
     }
@@ -305,7 +374,7 @@
             return ResultUtil.error("充值金额必须大于0");
         }
         SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
-        String out_trade_no = sdf.format(new Date()) + UUIDUtil.getNumberRandom(3);
+        String out_trade_no = sdf.format(new Date()) + UUIDUtil.getNumberRandom(5);
         AppUser appUser = this.selectById(uid);
         RechargeRecord rechargeRecord = new RechargeRecord();
         rechargeRecord.setType(1);
@@ -316,13 +385,11 @@
         rechargeRecord.setPayStatus(1);
         rechargeRecord.setPayType(1);
         rechargeRecordService.insert(rechargeRecord);
-//        ResultUtil weixinpay = payMoneyUtil.weixinpay("余额充值", "", out_trade_no, amount.toString(), "/base/appUser/rechargeBalanceCallback", "JSAPI", appUser.getOpenid());
-//        return weixinpay;
 
         PaymentOrder paymentOrder = new PaymentOrder();
         paymentOrder.setBizOrderId(out_trade_no);
-        paymentOrder.setAmount(String.valueOf(amount * 100));
-        paymentOrder.setOrderName("余额充值");
+        paymentOrder.setAmount(new BigDecimal(amount).multiply(new BigDecimal(100)).setScale(0, RoundingMode.HALF_EVEN).longValue() + "");
+        paymentOrder.setOrderName("账户充值");
         paymentOrder.setPayType("WX_MINI");
         paymentOrder.setTransferType("0");
         paymentOrder.setAsynSplitFlag("1");
@@ -331,16 +398,16 @@
         paymentOrder.setTerminalIp(InetAddress.getLocalHost().getHostAddress());
         List<PaymentOrderGood> goodsDetail = new ArrayList<>();
         PaymentOrderGood paymentOrderGood = new PaymentOrderGood();
-        paymentOrderGood.setGoodsName("余额充值");
+        paymentOrderGood.setGoodsName("账户充值");
         goodsDetail.add(paymentOrderGood);
         paymentOrder.setGoodsDetail(goodsDetail);
-        paymentOrder.setFrontUrl("");
+        paymentOrder.setFrontUrl(callbackPath + "/base/appUser/rechargeBalanceCallback");
         paymentOrder.setNotifyUrl(callbackPath + "/base/appUser/rechargeBalanceCallback");
         paymentOrder.setParameter1(out_trade_no);
 
         TrhRequest<PaymentOrder> request = new TrhRequest();
         InterfaceResponse execute = request.execute(paymentOrder, PaymentOrder.SERVICE_CODE);
-        if(!"0000".equals(execute.getResult())){
+        if(!"0000".equals(execute.getCode())){
             return ResultUtil.error(execute.getMsg());
         }
         JSONObject jsonObject = JSON.parseObject(execute.getResult());
@@ -348,10 +415,78 @@
         if("2".equals(status)){
             return ResultUtil.error("失败");
         }
-        if("0".equals(status)){
-            return ResultUtil.error("处理中");
-        }
+        String merOrderId = jsonObject.getString("merOrderId");
         String payCode = jsonObject.getString("payCode");
+        if(ToolUtil.isNotEmpty(payCode)){
+            new Thread(new Runnable() {
+                @Override
+                public void run() {
+                    try {
+                        int num = 1;
+                        int wait = 0;
+                        while (num <= 10){
+                            int min = 5000;
+                            wait += (min * num);
+                            RechargeRecord rechargeRecord1 = rechargeRecordService.selectOne(new EntityWrapper<RechargeRecord>().eq("code", out_trade_no));
+                            if(rechargeRecord1.getPayStatus() != 1){
+                                return;
+                            }
+                            QueryOrder queryOrder = new QueryOrder();
+                            queryOrder.setOriginalMerOrderId(merOrderId);
+                            queryOrder.setQueryType("1");
+                            TrhRequest<QueryOrder> request = new TrhRequest();
+                            InterfaceResponse execute1 = request.execute(queryOrder, QueryOrder.SERVICE_CODE);
+                            if("0000".equals(execute1.getCode())){
+                                JSONObject jsonObject1 = JSON.parseObject(execute1.getResult());
+                                String status1 = jsonObject1.getString("status");
+                                if("0".equals(status1)){//待处理
+                                    Thread.sleep(wait);
+                                    num++;
+                                }
+                                if("1".equals(status1)){//成功
+                                    String merOrderId = jsonObject1.getString("merOrderId");
+                                    AppUser appUser1 = AppUserServiceImpl.this.selectById(rechargeRecord1.getUserId());
+                                    AccountChangeDetail accountChangeDetail = new AccountChangeDetail();
+                                    accountChangeDetail.setUserType(1);
+                                    accountChangeDetail.setUserId(appUser1.getId());
+                                    accountChangeDetail.setCode(System.currentTimeMillis() + UUIDUtil.getNumberRandom(5));
+                                    accountChangeDetail.setChangeType(3);
+                                    accountChangeDetail.setType(1);
+                                    accountChangeDetail.setCreateTime(new Date());
+                                    accountChangeDetail.setExplain("账户充值");
+                                    accountChangeDetail.setOldData(appUser1.getAccountBalance());
+                                    appUser1.setAccountBalance(new BigDecimal(appUser1.getAccountBalance()).add(new BigDecimal(rechargeRecord1.getAmount())).setScale(2, RoundingMode.HALF_EVEN).doubleValue());
+                                    accountChangeDetail.setNewData(appUser1.getAccountBalance());
+                                    accountChangeDetailService.saveData(accountChangeDetail);
+                                    SystemConfig systemConfig = systemConfigService.selectOne(new EntityWrapper<SystemConfig>().eq("type", 6));
+                                    Double num2 = JSON.parseObject(systemConfig.getContent()).getDouble("num2");
+                                    if(appUser1.getHavDiscount() == 0 && rechargeRecord1.getAmount().compareTo(num2) >= 0){
+                                        appUser1.setHavDiscount(1);
+                                    }
+                                    AppUserServiceImpl.this.updateById(appUser1);
+
+                                    rechargeRecord1.setPayTime(new Date());
+                                    rechargeRecord1.setPayStatus(2);
+                                    rechargeRecord1.setOrderNumber(merOrderId);
+                                    rechargeRecord1.setSurplusDividedAmount(rechargeRecord1.getAmount());
+                                    rechargeRecordService.updateById(rechargeRecord1);
+                                    break;
+                                }
+                                if("2".equals(status1) || 10 == num){//失败
+                                    rechargeRecordService.deleteById(rechargeRecord1.getId());
+                                    break;
+                                }
+                            }else{
+                                Thread.sleep(wait);
+                                num++;
+                            }
+                        }
+                    }catch (Exception e){
+                        e.printStackTrace();
+                    }
+                }
+            }).start();
+        }
         return ResultUtil.success(payCode);
     }
 
@@ -373,20 +508,26 @@
         AccountChangeDetail accountChangeDetail = new AccountChangeDetail();
         accountChangeDetail.setUserType(1);
         accountChangeDetail.setUserId(rechargeRecord1.getUserId());
-        accountChangeDetail.setCode(System.currentTimeMillis() + UUIDUtil.getNumberRandom(3));
+        accountChangeDetail.setCode(System.currentTimeMillis() + UUIDUtil.getNumberRandom(5));
         accountChangeDetail.setChangeType(3);
         accountChangeDetail.setType(1);
         accountChangeDetail.setCreateTime(new Date());
         accountChangeDetail.setExplain("余额充值");
         accountChangeDetail.setOldData(appUser.getAccountBalance());
-        appUser.setAccountBalance(appUser.getAccountBalance() + rechargeRecord1.getAmount());
+        appUser.setAccountBalance(new BigDecimal(appUser.getAccountBalance()).add(new BigDecimal(rechargeRecord1.getAmount())).setScale(2, RoundingMode.HALF_EVEN).doubleValue());
         accountChangeDetail.setNewData(appUser.getAccountBalance());
-        this.updateById(appUser);
         accountChangeDetailService.saveData(accountChangeDetail);
+        SystemConfig systemConfig = systemConfigService.selectOne(new EntityWrapper<SystemConfig>().eq("type", 6));
+        Double num2 = JSON.parseObject(systemConfig.getContent()).getDouble("num2");
+        if(appUser.getHavDiscount() == 0 && rechargeRecord1.getAmount().compareTo(num2) >= 0){
+            appUser.setHavDiscount(1);
+        }
+        this.updateById(appUser);
 
         rechargeRecord1.setPayTime(new Date());
         rechargeRecord1.setPayStatus(2);
         rechargeRecord1.setOrderNumber(transaction_id);
+        rechargeRecord1.setSurplusDividedAmount(rechargeRecord1.getAmount());
         rechargeRecordService.updateById(rechargeRecord1);
     }
 

--
Gitblit v1.7.1