From 474724c0e016be419fe84967fdcb085722e6b444 Mon Sep 17 00:00:00 2001
From: 刘帅 <rr.iii@qq.com>
Date: 星期二, 22 九月 2026 11:20:12 +0800
Subject: [PATCH] bug:营收统计数据修改

---
 cloud-server-competition/src/main/java/com/dsh/competition/controller/CompetitionController.java |  324 ++++++++++++++++++++++++++++++++++++-----------------
 1 files changed, 218 insertions(+), 106 deletions(-)

diff --git a/cloud-server-competition/src/main/java/com/dsh/competition/controller/CompetitionController.java b/cloud-server-competition/src/main/java/com/dsh/competition/controller/CompetitionController.java
index b52f889..469ca6f 100644
--- a/cloud-server-competition/src/main/java/com/dsh/competition/controller/CompetitionController.java
+++ b/cloud-server-competition/src/main/java/com/dsh/competition/controller/CompetitionController.java
@@ -3,6 +3,7 @@
 
 import cn.hutool.core.date.DateUtil;
 import cn.hutool.poi.excel.ExcelUtil;
+import cn.mb.cloud.common.core.exception.BusinessException;
 import com.alibaba.fastjson.JSONObject;
 import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
 import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
@@ -21,6 +22,7 @@
 import com.dsh.competition.feignclient.course.model.PaymentDeductionClassHour;
 import com.dsh.competition.feignclient.model.*;
 import com.dsh.competition.feignclient.other.StoreClient;
+import com.dsh.competition.feignclient.other.model.Store;
 import com.dsh.competition.model.*;
 import com.dsh.competition.service.CompetitionService;
 import com.dsh.competition.service.IParticipantService;
@@ -138,20 +140,6 @@
             List<Integer> operatorId = cttService.list(new QueryWrapper<Competition>()
                     .eq("operatorId", operatorId1)).stream().map(Competition::getId).collect(Collectors.toList());
             query.setUserIds(operatorId);
-        } else if (query.getStoreId() != null) {
-            List<Competition> list = cttService.list(new QueryWrapper<Competition>());
-            List<Integer> integers = new ArrayList<>();
-            for (Competition competition : list) {
-                for (String s : competition.getStoreId().split(",")) {
-                    if (s.equals(""+query.getStoreId())){
-                        integers.add(competition.getId());
-                    }
-                }
-            }
-            if (integers.isEmpty()){
-                integers.add(-1);
-            }
-            query.setUserIds(integers);
         }
         List<PaymentCompetition> paymentCompetitions = paymentCompetitionService.listAll(query);
         List<PaymentCompetition> result = new ArrayList<>();
@@ -170,17 +158,7 @@
             }
             return result;
         } else if (query.getStoreId() != null) {
-            for (PaymentCompetition paymentCompetition : paymentCompetitions) {
-                Integer competitionId = paymentCompetition.getCompetitionId();
-                Competition byId = cttService.getById(competitionId);
-                if (byId != null) {
-                    String storeId = byId.getStoreId();
-                    if (storeId.contains(query.getStoreId().toString())) {
-                        result.add(paymentCompetition);
-                    }
-                }
-            }
-            return result;
+            return paymentCompetitions;
         }
         return paymentCompetitions;
     }
@@ -667,6 +645,64 @@
             e.printStackTrace();
         }
     }
+    /**
+     * 取消已报名赛事后微信回退金额回调微信V3服务商版本
+     *
+     * @param request
+     * @param response
+     */
+    @ResponseBody
+    @PostMapping("/base/competition/weChatCancelPaymentCompetitionCallback1")
+    public void weChatCancelPaymentCompetitionCallback1(HttpServletRequest request, HttpServletResponse response) {
+        try {
+            System.err.println("微信回调");
+            System.err.println("请求" + request);
+            BufferedReader reader = request.getReader();
+            String string1 = reader.toString();
+            System.err.println("请求reader" + string1);
+            StringBuilder requestBody = new StringBuilder();
+            String line;
+            while ((line = reader.readLine()) != null) {
+                requestBody.append(line);
+            }
+            System.err.println("全部请求体" + requestBody);
+            JSONObject jsonObject = JSONObject.parseObject(requestBody.toString());
+            JSONObject resource = jsonObject.getJSONObject("resource");
+
+            AesUtil aesUtil = new AesUtil(WxV3PayConfig.apiV3Key.getBytes(StandardCharsets.UTF_8));
+            String decryptedData = aesUtil.decryptToString(resource.getString("associated_data").getBytes(StandardCharsets.UTF_8), resource.getString("nonce").getBytes(StandardCharsets.UTF_8),
+                    resource.getString("ciphertext"));
+            System.err.println("微信解密的字符串信息" + decryptedData);
+            JSONObject jsonInfo = (JSONObject) JSONObject.parse(decryptedData);
+            String code = jsonInfo.getString("out_trade_no");
+            String transaction_id = jsonInfo.getString("transaction_id");
+            String refund_status = jsonInfo.getString("refund_status");
+            String out_refund_no = jsonInfo.getString("out_refund_no");
+            if (refund_status.equals("SUCCESS")) {
+                PaymentCompetition paymentCompetition = paymentCompetitionService.getOne(new QueryWrapper<PaymentCompetition>()
+                        .eq("code", code).eq("payType", 1));
+                if (paymentCompetition.getPayStatus() == 2) {
+                    paymentCompetition.setPayStatus(3);
+                    paymentCompetition.setRefundTime(new Date());
+                    paymentCompetition.setRefundOrderNo(out_refund_no);
+                    paymentCompetition.setAppUserId(null);
+                    paymentCompetitionService.updateById(paymentCompetition);
+
+                    Competition competition = cttService.getById(paymentCompetition.getCompetitionId());
+                    competition.setApplicantsNumber(competition.getApplicantsNumber() - 1);
+                    cttService.updateById(competition);
+                    storeClient.addBackRecord(paymentCompetition.getAmount() + "_" + paymentCompetition.getAppUserId());
+
+                }
+                PrintWriter out = response.getWriter();
+                out.write("SUCCESS");
+                out.flush();
+                out.close();
+            }
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
 
 
     @PostMapping("/base/competition/queryById")
@@ -710,7 +746,8 @@
                 wrapper.ne(Competition::getAuditStatus,2);
             }
             wrapper.in(Competition::getStoreId,listQuery.getIds());
-            wrapper.orderByDesc(Competition::getInsertTime);
+            wrapper.orderByDesc(Competition::getInsertTime)
+                    .orderByDesc(Competition::getId);
             Page<Competition> page = cttService.page(competitionPage, wrapper);
             for (Competition record : page.getRecords()) {
                 // 查询当前赛事有多少人报名了
@@ -753,7 +790,8 @@
             integers.add(1);
             integers.add(3);
             wrapper.in(Competition::getAuditStatus, integers);
-            wrapper.orderByDesc(Competition::getInsertTime);
+            wrapper.orderByDesc(Competition::getInsertTime)
+                    .orderByDesc(Competition::getId);
 
             Page<Competition> page = cttService.page(competitionPage, wrapper);
             return page;
@@ -802,41 +840,14 @@
         }
     }
 
+    /**
+     * 更新活动配置。
+     *
+     * @param competition 管理端提交的活动信息
+     */
     @PostMapping("/base/competition/update")
-    public void update(@RequestBody Competition competition) {
-        try {
-            if (competition.getStartTime().after(new Date())) {
-                competition.setStatus(1);
-            }
-            if (competition.getStartTime().before(new Date())) {
-                if (competition.getEndTime().after(new Date())) {
-                    competition.setStatus(2);
-                } else {
-                    competition.setStatus(3);
-                }
-
-                if(competition.getStatus() == 2){
-                    //添加勋章数据
-                    List<PaymentCompetition> list = paymentCompetitionService.list(new QueryWrapper<PaymentCompetition>()
-                            .eq("competitionId", competition.getId()).eq("payStatus", 2).eq("state", 1));
-                    Set<Integer> collect = list.stream().map(PaymentCompetition::getAppUserId).collect(Collectors.toSet());
-                    for (Integer integer : collect) {
-                        int count = paymentCompetitionService.count(new QueryWrapper<PaymentCompetition>()
-                                .eq("appUserId", integer).eq("payStatus", 2).eq("state", 1));
-                        StudentHonor studentHonor = new StudentHonor();
-                        studentHonor.setAppUserId(integer);
-                        studentHonor.setHonorType(2);
-                        studentHonor.setNumber(count);
-                        studentHonorClient.saveStudentHonor(studentHonor);
-                    }
-                }
-            }
-            cttService.updateById(competition);
-
-
-        } catch (Exception e) {
-            e.printStackTrace();
-        }
+    public void update(@RequestBody Competition competition) throws BusinessException {
+        cttService.updateCompetition(competition);
     }
 
     @Resource
@@ -859,46 +870,32 @@
                 String code = paymentCompetition.getCode();
                 Double amount = paymentCompetition.getAmount();
                 Competition competition = competitionService.getById(paymentCompetition.getCompetitionId());
-
-
+                Store store = storeClient.queryStoreById(Integer.valueOf(competition.getStoreId().split(",")[0]));
                 String payOrderNo = paymentCompetition.getPayOrderNo();
                 if (paymentCompetition.getPayType() == 1) {//微信支付
-                    if (StringUtils.hasLength(paymentCompetition.getFenzhangNo())){
-                        // 是分账订单 如果分账金额不为0 那么回退分账金额
-                        if (paymentCompetition.getFenzhangAmount()!=null && paymentCompetition.getFenzhangAmount().compareTo(BigDecimal.ZERO)>0){
-                            String randomCode = UUIDUtil.getRandomCode(16);
-                            String randomCode1 = UUIDUtil.getRandomCode(16);
-                            if (competition.getOperatorId()!=null && competition.getOperatorId()!=0){
-                                // 微信商户号
-                                String s2 =storeClient.getmerchantNumberByOperatorId(competition.getOperatorId());
-                                ResultUtil resultUtil = payMoneyUtil.fenzhangRefund(paymentCompetition.getFenzhangNo(), paymentCompetition.getFenzhangAmount(), s2, randomCode, randomCode1);
-                                if (!resultUtil.getCode().equals(200)){
-                                    System.err.println("分账回退失败 原因是:"+resultUtil.getMsg());
-                                }else{
-                                    paymentCompetition.setFenzhangRefundNo(resultUtil.getData().toString());
-                                    paymentCompetitionService.updateById(paymentCompetition);
-                                }
-
-                            }
+                    if (store.getOperatorId()!=null && store.getOperatorId()!=0){
+                        String smidVx= storeClient.getmerchantNumberByOperatorId(store.getOperatorId());
+                        if (!StringUtils.hasLength(smidVx)){
+                            System.err.println("运营商未配置微信商户号,获取支付失败!");
                         }
-                    }
-
-
-
-
-                    Map<String, String> map = payMoneyUtil.wxRefund(payOrderNo, code, amount.toString(), amount.toString(),
-                            "/base/competition/weChatCancelPaymentCompetitionCallback");
-                    String return_code = map.get("return_code");
-                    if (!"SUCCESS".equals(return_code)) {
+                        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
+                        String codeRefund = sdf.format(new Date()) + UUIDUtil.getNumberRandom(5);// 退款单号
+                        // 运营商退款
+                        payMoneyUtil.weixinRefundV3(smidVx, codeRefund, pay.getPayOrderNo(), pay.getAmount().toString(), "/base/competition/weChatCancelPaymentCompetitionCallback1");
+                    }else {
+                        Map<String, String> map = payMoneyUtil.wxRefund(payOrderNo, code, amount.toString(), amount.toString(),
+                                "/base/competition/weChatCancelPaymentCompetitionCallback");
+                        String return_code = map.get("return_code");
+                        if (!"SUCCESS".equals(return_code)) {
 //                        return ResultUtil.error(map.get("return_msg"));
-                        continue;
+                            continue;
+                        }
+                        String refund_id = map.get("refund_id");
+                        paymentCompetition.setRefundOrderNo(refund_id);
+                        paymentCompetition.setAppUserId(null);
+                        paymentCompetitionService.updateById(paymentCompetition);
+                        storeClient.addBackRecord(paymentCompetition.getAmount() + "_" + paymentCompetition.getAppUserId());
                     }
-                    String refund_id = map.get("refund_id");
-                    paymentCompetition.setRefundOrderNo(refund_id);
-                    paymentCompetition.setAppUserId(null);
-                    paymentCompetitionService.updateById(paymentCompetition);
-                    storeClient.addBackRecord(paymentCompetition.getAmount() + "_" + paymentCompetition.getAppUserId());
-
                 }
                 if (paymentCompetition.getPayType() == 2) {//支付宝支付
                     Map<String, String> map = payMoneyUtil.aliRefund(payOrderNo, amount.toString());
@@ -1015,10 +1012,11 @@
         if (ToolUtil.isNotEmpty(data)) {
             String stime = data.split(" - ")[0] + " 00:00:00";
             String etime = data.split(" - ")[1] + " 23:59:59";
-            vipPaymentLambdaQueryWrapper.between(PaymentCompetition::getInsertTime, stime, etime);
+            vipPaymentLambdaQueryWrapper.between(PaymentCompetition::getPayTime, stime, etime);
         }
         vipPaymentLambdaQueryWrapper.in(PaymentCompetition::getCompetitionId, ids);
         vipPaymentLambdaQueryWrapper.eq(PaymentCompetition::getPayStatus, 2);
+        vipPaymentLambdaQueryWrapper.eq(PaymentCompetition::getState, 1);
         ArrayList<Integer> objects = new ArrayList<>();
         objects.add(1);
         objects.add(2);
@@ -1097,13 +1095,11 @@
         // 年
         ArrayList<Integer> years = new ArrayList<>();
         ArrayList<Integer> yearsUser = new ArrayList<>();
-        Integer operatorId = vo.getOperatorId();
-        List<Integer> operatorId1 = cttService.list(new QueryWrapper<Competition>().eq("operatorId", operatorId))
-                .stream().map(Competition::getId).collect(Collectors.toList());
         for (Object o : collect) {
             String s = o.toString();
-            int count = cttService.count(new LambdaQueryWrapper<Competition>().like(Competition::getInsertTime, s).eq(Competition::getOperatorId, vo.getOperatorId()));
-            int count1 = ucttService.count(new LambdaQueryWrapper<UserCompetition>().in(UserCompetition::getAppUserId, vo.getIds()).like(UserCompetition::getInsertTime, s));
+            List<Integer> competitionIds = listCompetitionIds(vo, s);
+            int count = competitionIds.size();
+            int count1 = countUserCompetitions(vo, s, competitionIds);
             years.add(count);
             yearsUser.add(count1);
         }
@@ -1121,8 +1117,9 @@
                 m = "0" + i;
             }
             String s = year + "-" + m;
-            int count = cttService.count(new LambdaQueryWrapper<Competition>().like(Competition::getInsertTime, s).eq(Competition::getOperatorId, operatorId));
-            int count1 = ucttService.count(new LambdaQueryWrapper<UserCompetition>().in(UserCompetition::getAppUserId, vo.getIds()).like(UserCompetition::getInsertTime, s));
+            List<Integer> competitionIds = listCompetitionIds(vo, s);
+            int count = competitionIds.size();
+            int count1 = countUserCompetitions(vo, s, competitionIds);
             months.add(count);
             monthsUser.add(count1);
         }
@@ -1132,11 +1129,127 @@
         return map;
     }
 
+    /** 门店活动统计:仅统计指定门店的赛事及其报名记录。 */
+    @ResponseBody
+    @PostMapping("/base/competition/actStore")
+    public HashMap<String, Object> actStore(@RequestBody CompetionVO vo) {
+        HashMap<String, Object> map = new HashMap<>();
+        if (vo.getStoreIds() == null || vo.getStoreIds().isEmpty()) {
+            vo.setStoreIds(Collections.singletonList(-1));
+        }
+        ArrayList<Integer> years = new ArrayList<>();
+        ArrayList<Integer> yearsUser = new ArrayList<>();
+        int year = DateUtil.year(new Date());
+        for (int statisticYear = year - 9; statisticYear <= year; statisticYear++) {
+            String dateText = String.valueOf(statisticYear);
+            List<Integer> competitionIds = listStoreCompetitionIds(vo, dateText);
+            years.add(competitionIds.size());
+            yearsUser.add(countStoreUserCompetitions(dateText, competitionIds));
+        }
+        map.put("yearData", years);
+        map.put("yearsUser", yearsUser);
+
+        ArrayList<Integer> months = new ArrayList<>();
+        ArrayList<Integer> monthsUser = new ArrayList<>();
+        for (int month = 1; month <= 12; month++) {
+            String dateText = String.format("%d-%02d", year, month);
+            List<Integer> competitionIds = listStoreCompetitionIds(vo, dateText);
+            months.add(competitionIds.size());
+            monthsUser.add(countStoreUserCompetitions(dateText, competitionIds));
+        }
+        map.put("monthData", months);
+        map.put("monthsUser", monthsUser);
+        return map;
+    }
+
+    private List<Integer> listCompetitionIds(CompetionVO vo, String dateText) {
+        return cttService.list(buildCompetitionCountWrapper(vo, dateText))
+                .stream()
+                .map(Competition::getId)
+                .collect(Collectors.toList());
+    }
+
+    private List<Integer> listStoreCompetitionIds(CompetionVO vo, String dateText) {
+        Set<String> storeIds = vo.getStoreIds().stream()
+                .filter(Objects::nonNull)
+                .map(String::valueOf)
+                .collect(Collectors.toSet());
+        return cttService.list(new LambdaQueryWrapper<Competition>()
+                        .like(Competition::getInsertTime, dateText))
+                .stream()
+                .filter(competition -> containsStoreId(competition.getStoreId(), storeIds))
+                .map(Competition::getId)
+                .collect(Collectors.toList());
+    }
+
+    private boolean containsStoreId(String competitionStoreIds, Set<String> storeIds) {
+        if (competitionStoreIds == null || competitionStoreIds.trim().isEmpty()) {
+            return false;
+        }
+        return Arrays.stream(competitionStoreIds.split(","))
+                .map(String::trim)
+                .anyMatch(storeIds::contains);
+    }
+
+    private int countStoreUserCompetitions(String dateText, List<Integer> competitionIds) {
+        if (competitionIds.isEmpty()) {
+            return 0;
+        }
+        return ucttService.count(new LambdaQueryWrapper<UserCompetition>()
+                .in(UserCompetition::getCompetitionId, competitionIds)
+                .like(UserCompetition::getInsertTime, dateText));
+    }
+
+    private int countUserCompetitions(CompetionVO vo, String dateText, List<Integer> competitionIds) {
+        if (competitionIds.isEmpty()) {
+            return 0;
+        }
+        return ucttService.count(new LambdaQueryWrapper<UserCompetition>()
+                .in(UserCompetition::getAppUserId, vo.getIds())
+                .in(UserCompetition::getCompetitionId, competitionIds)
+                .like(UserCompetition::getInsertTime, dateText));
+    }
+
+    private LambdaQueryWrapper<Competition> buildCompetitionCountWrapper(CompetionVO vo, String dateText) {
+        LambdaQueryWrapper<Competition> wrapper = new LambdaQueryWrapper<Competition>()
+                .like(Competition::getInsertTime, dateText);
+        // 运营商活动统计以其名下门店为准。历史活动的 operatorId 可能为空或未同步,
+        // 不能再以该字段过滤,否则活动管理列表能看到的门店活动会被统计遗漏。
+        appendStoreIdFilter(wrapper, vo.getStoreIds());
+        return wrapper;
+    }
+
+    private void appendStoreIdFilter(LambdaQueryWrapper<Competition> wrapper, List<Integer> storeIds) {
+        if (storeIds == null || storeIds.isEmpty()) {
+            return;
+        }
+
+        List<Integer> validStoreIds = storeIds.stream()
+                .filter(Objects::nonNull)
+                .collect(Collectors.toList());
+        if (validStoreIds.isEmpty()) {
+            return;
+        }
+
+        wrapper.and(item -> {
+            item.apply("FIND_IN_SET({0}, storeId)", validStoreIds.get(0));
+            for (int i = 1; i < validStoreIds.size(); i++) {
+                item.or().apply("FIND_IN_SET({0}, storeId)", validStoreIds.get(i));
+            }
+        });
+    }
+
 
     @ResponseBody
     @PostMapping("/base/competition/queryAppUserId")
     public List<Integer> queryAppUserId(@RequestBody List<Integer> storeIds){
-        List<Competition> list = competitionService.list(new QueryWrapper<Competition>().in("storeId", storeIds).eq("auditStatus", 2).eq("state", 1));
+        if (storeIds == null || storeIds.isEmpty()) {
+            return new ArrayList<>();
+        }
+        LambdaQueryWrapper<Competition> wrapper = new LambdaQueryWrapper<Competition>()
+                .eq(Competition::getAuditStatus, 2).eq(Competition::getState, 1);
+        appendStoreIdFilter(wrapper, storeIds);
+        List<Competition> list = competitionService.list(wrapper);
         List<Integer> collect = list.stream().map(Competition::getId).collect(Collectors.toList());
         if(collect.size() == 0){
             return new ArrayList<>();
@@ -1145,4 +1258,3 @@
         return list1.stream().map(PaymentCompetition::getAppUserId).collect(Collectors.toList());
     }
 }
-

--
Gitblit v1.7.1