From 595b7935a30e84fba1bc3561d05f9d19d3e32e1f Mon Sep 17 00:00:00 2001
From: Administrator <1101184511@qq.com>
Date: 星期三, 23 四月 2025 00:45:48 +0800
Subject: [PATCH] 后台管理页面完成

---
 src/main/java/com/taoke/autopay/service/impl/KeyOrderServiceImpl.java |  442 ++++++++++++++++++++++++++++++++++++++++++++++++++----
 1 files changed, 405 insertions(+), 37 deletions(-)

diff --git a/src/main/java/com/taoke/autopay/service/impl/KeyOrderServiceImpl.java b/src/main/java/com/taoke/autopay/service/impl/KeyOrderServiceImpl.java
index 9ed3534..c9c6dc0 100644
--- a/src/main/java/com/taoke/autopay/service/impl/KeyOrderServiceImpl.java
+++ b/src/main/java/com/taoke/autopay/service/impl/KeyOrderServiceImpl.java
@@ -1,16 +1,40 @@
 package com.taoke.autopay.service.impl;
 
+import com.google.gson.Gson;
 import com.taoke.autopay.dao.KeyOrderMapper;
-import com.taoke.autopay.entity.KeyOrder;
-import com.taoke.autopay.entity.OrderDistributeCountInfo;
+import com.taoke.autopay.dao.WxUserSettingsMapper;
+import com.taoke.autopay.dto.ChannelOrderStatistic;
+import com.taoke.autopay.dto.DYOrderDto;
+import com.taoke.autopay.entity.*;
+import com.taoke.autopay.entity.agent.ChannelAgent;
+import com.taoke.autopay.entity.agent.ChannelAgentSettings;
 import com.taoke.autopay.exception.KeyOrderException;
+import com.taoke.autopay.exception.KeyVerifyException;
+import com.taoke.autopay.exception.UserCreditException;
+import com.taoke.autopay.exception.WxOrderCountException;
 import com.taoke.autopay.factory.OrderFactory;
-import com.taoke.autopay.service.KeyOrderService;
+import com.taoke.autopay.manager.UserCreditManager;
+import com.taoke.autopay.service.*;
+import com.taoke.autopay.service.agent.ChannelAgentService;
+import com.taoke.autopay.service.agent.ChannelAgentSettingService;
+import com.taoke.autopay.service.agent.ChannelAgentSharingRatioService;
+import com.taoke.autopay.utils.*;
+import com.taoke.autopay.utils.order.DYOrderApi;
+import com.taoke.autopay.utils.order.OrderChannelUtil;
+import com.taoke.autopay.vo.SubmitKeyInfo;
+import com.taoke.autopay.vo.admin.IgnoreAgentOrderSettingVO;
+import net.sf.json.JSONArray;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 import org.springframework.stereotype.Service;
 import org.springframework.transaction.annotation.Transactional;
 
 import javax.annotation.Resource;
+import java.math.BigDecimal;
+import java.net.URI;
 import java.util.*;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
 
 /**
  * @author hxh
@@ -21,8 +45,40 @@
 @Service
 public class KeyOrderServiceImpl implements KeyOrderService {
 
+    private Logger loggerDebug= LoggerFactory.getLogger("debugLogger");
+
     @Resource
     private KeyOrderMapper keyOrderMapper;
+
+    @Resource
+    private WxUserSettingService wxUserSettingService;
+
+    @Resource
+    private WxUserOrderCountService wxUserOrderCountService;
+
+    @Resource
+    private SystemConfigService systemConfigService;
+
+    @Resource
+    private ChannelAgentService channelAgentService;
+
+    @Resource
+    private ChannelAgentSharingRatioService channelAgentSharingRatioService;
+
+    @Resource
+    private ChannelAgentSettingService channelAgentSettingService;
+
+    @Resource
+    private ClientInfoService clientInfoService;
+
+    @Resource
+    private PayMoneySettingService payMoneySettingService;
+
+    @Resource
+    private WxUserService wxUserService;
+
+    @Resource
+    private UserCreditManager userCreditManager;
 
 
     @Override
@@ -30,19 +86,94 @@
         return keyOrderMapper.selectById(id);
     }
 
+    @Transactional(rollbackFor = Exception.class)
     @Override
-    public KeyOrder addKeyOrder(String key) throws KeyOrderException {
-        String id = OrderFactory.createId(key);
+    public KeyOrder selectByIdForUpdate(String id) {
+        return keyOrderMapper.selectByPrimaryKeyForUpdate(id);
+    }
+
+    @Transactional(rollbackFor = Exception.class)
+    @Override
+    public KeyOrder addKeyOrder(SubmitKeyInfo keyInfo, Long uid, String day, Integer orderType, DYOrderDto orderDto) throws KeyOrderException, WxOrderCountException {
+        // 鍒ゆ柇鎻愪氦娆℃暟鏄惁杩囬噺
+        if (uid != null) {
+            WxUserSettings settings = wxUserSettingService.getUserSettings(uid);
+            OrderCountTypeEnum countType = OrderCountTypeEnum.SUBMIT_TOKEN_COUNT;
+            wxUserOrderCountService.addOrderCount(uid, countType, null, day, 1, settings.getTotalOrderCountPerDay());
+            wxUserService.setLatestInfoInfo(uid, keyInfo.getIp(), keyInfo.getIpInfo());
+        }
+        String id = OrderFactory.createId(keyInfo.getKey());
         KeyOrder order = keyOrderMapper.selectById(id);
         if (order != null) {
             throw new KeyOrderException("璇峰嬁閲嶅鎻愪氦鍙d护");
         }
         order = new KeyOrder();
+        // 瑙f瀽referer涓殑閾炬帴
+        if (!StringUtil.isNullOrEmpty(keyInfo.getReferer())) {
+            Map<String, String> paramsMap = HttpUtil.getPramsFromUrl(keyInfo.getReferer());
+            if (paramsMap.containsKey("a")) {
+                String alias = paramsMap.get("a");
+                ChannelAgent agent = channelAgentService.selectByAlias(alias);
+                if (agent == null) {
+                    throw new KeyOrderException("娓犻亾涓嶅瓨鍦�");
+                }
+
+                if (agent.getStatus() != ChannelAgent.STATUS_NOMAL) {
+                    throw new KeyOrderException("娓犻亾鍙楅檺");
+                }
+                // 楠岃瘉娓犻亾鏃堕棿
+                ChannelAgentSettings settings = channelAgentSettingService.selectByAgentId(agent.getId());
+                if (settings != null && !StringUtil.isNullOrEmpty(settings.getStartSubmitTime()) && !StringUtil.isNullOrEmpty(settings.getEndSubmitTime())) {
+                    String now = TimeUtil.getGernalTime(System.currentTimeMillis(), "HHmmss");
+                    String startTime = settings.getStartSubmitTime().replace(":", "");
+                    String endTime = settings.getEndSubmitTime().replace(":", "");
+                    if (Integer.parseInt(now) < Integer.parseInt(startTime) || Integer.parseInt(now) > Integer.parseInt(endTime)) {
+                        throw new KeyOrderException(String.format("鍙d护鎻愪氦鏃堕棿娈典负锛�%s-%s", settings.getStartSubmitTime(), settings.getEndSubmitTime()));
+                    }
+                }
+
+                // 鑾峰彇娓犻亾蹇界暐璁㈠崟鐨勯厤缃�
+                String config = systemConfigService.getValueCache(SystemConfigKeyEnum.IGNORE_AGENT_ORDER_SETTING);
+                if (!StringUtil.isNullOrEmpty(config)) {
+                    IgnoreAgentOrderSettingVO ignore = JsonUtil.getSimpleGson().fromJson(config, IgnoreAgentOrderSettingVO.class);
+                    if (ignore.getPercent() > 0) {
+                        // 鑾峰彇褰撳墠浠g悊浠婃棩鐨勮鍗曟暟閲�
+                        KeyOrderMapper.DaoQuery daoQuery = new KeyOrderMapper.DaoQuery();
+                        daoQuery.agentId = agent.getId();
+                        daoQuery.minCreateTime = new Date(TimeUtil.convertToTimeTemp(TimeUtil.getGernalTime(System.currentTimeMillis(), "yyyyMMdd"), "yyyyMMdd"));
+                        long keyCount = count(daoQuery);
+                        if (keyCount > ignore.getBeginCount()) {
+                            if ((keyCount - ignore.getBeginCount()) % (100 / ignore.getPercent()) == 0) {
+                                order.setIgnore(true);
+                            }
+                        }
+                    }
+                }
+                order.setAgentId(agent.getId());
+            }
+        }
+
+
         order.setId(id);
-        order.setKey(key);
+        order.setKey(keyInfo.getKey());
+        if (!StringUtil.isNullOrEmpty(keyInfo.getMoney())) {
+            order.setOrderMoney(new BigDecimal(keyInfo.getMoney()));
+        }
+        order.setUid(uid);
         order.setState(KeyOrder.STATE_NOT_PROCESS);
         order.setStateDesc("灏氭湭澶勭悊");
         order.setCreateTime(new Date());
+        if (orderType != Constant.ORDER_TYPE_UNKNOWN) {
+            order.setOrderType(orderType);
+        }
+        if (orderDto != null) {
+            order.setOrderNo(orderDto.getOrder_id());
+        }
+
+        order.setIp(keyInfo.getIp());
+        if (keyInfo.getIpInfo() != null) {
+            order.setIpInfo(new Gson().toJson(keyInfo.getIpInfo()));
+        }
         keyOrderMapper.insertSelective(order);
         return order;
     }
@@ -61,6 +192,53 @@
             keyOrder.setUpdateTime(new Date());
         }
         keyOrderMapper.updateByPrimaryKeySelective(keyOrder);
+    }
+
+    @Transactional(rollbackFor = Exception.class)
+    @Override
+    public void paySuccess(String id, String stateDesc, String day, String payMerchant) throws WxOrderCountException {
+        KeyOrder old = keyOrderMapper.selectByPrimaryKeyForUpdate(id);
+        if (old == null) {
+            return;
+        }
+        if (old.getState() == KeyOrder.STATE_PAY) {
+            return;
+        }
+        if (old.getUid() != null) {
+            Integer orderType = old.getOrderType();
+            wxUserOrderCountService.addOrderCount(old.getUid(), (orderType == null || orderType == Constant.ORDER_TYPE_DY) ? OrderCountTypeEnum.DY_ORDER_PAY : OrderCountTypeEnum.KS_ORDER_PAY, OrderChannelUtil.getChannelByKey(old.getOrderChannel()), day, 1, null);
+        }
+        KeyOrder orderUpdate = new KeyOrder();
+        orderUpdate.setId(id);
+        orderUpdate.setState(KeyOrder.STATE_PAY);
+        orderUpdate.setStateDesc(stateDesc);
+        orderUpdate.setPayMerchant(payMerchant);
+        if (old.getPayTime() == null) {
+            orderUpdate.setPayTime(new Date());
+        }
+        update(orderUpdate);
+        // 澧炲姞绉垎
+        try {
+            boolean creditEnable = true;
+            // 鍒ゆ柇浠g悊鏄惁鍏佽澧炲姞绉垎
+            Long agengId = old.getAgentId();
+            if(agengId!=null) {
+                ChannelAgentSettings agentSettings =   channelAgentSettingService.selectByAgentId(agengId);
+                if(agentSettings!=null&&agentSettings.getCreditEnable()!=null) {
+                    creditEnable =agentSettings.getCreditEnable();
+                }
+            }
+            if(creditEnable) {
+                if (old.getOrderType() == Constant.ORDER_TYPE_DY) {
+                    userCreditManager.addDYOrderPayRecord(old.getUid(), id);
+                } else if (old.getOrderType() == Constant.ORDER_TYPE_KS) {
+                    userCreditManager.addKSOrderPayRecord(old.getUid(), id);
+                }
+            }
+
+        } catch (UserCreditException e) {
+            loggerDebug.error("澧炲姞绉垎鍑洪敊锛�"+id, e);
+        }
     }
 
     @Transactional(rollbackFor = Exception.class)
@@ -93,45 +271,127 @@
     }
 
     @Override
-    public Long getCanDistributeUid() {
-        // 鏈�杩�1灏忔椂鏈夋椿璺�
-        List<OrderDistributeCountInfo> list = keyOrderMapper.listDistributeUids(new Date(System.currentTimeMillis() - 1000 * 60 * 60L));
+    public List<KeyOrder> listWithUser(KeyOrderMapper.DaoQuery query) {
+        return keyOrderMapper.listWithUser(query);
+    }
+
+    @Override
+    public long countWithUser(KeyOrderMapper.DaoQuery query) {
+        return keyOrderMapper.countWithUser(query);
+    }
+
+    @Override
+    public ChannelOrderStatistic statisticWithUser(KeyOrderMapper.DaoQuery query) {
+        Map<OrderChannelEnum, BigDecimal> shareMoneyMap = channelAgentSharingRatioService.getShareMoneyMap(query.agentId);
+        List<ChannelOrderStatistic> channelOrderStatisticList = keyOrderMapper.statisticChannelOrders(query);
+        BigDecimal totalMoney = new BigDecimal(0);
+        long totalOrderCount = 0;
+        for (ChannelOrderStatistic s : channelOrderStatisticList) {
+
+            for (OrderChannelEnum channel : OrderChannelEnum.values()) {
+                if (channel.getKey().equalsIgnoreCase(s.getOrderChannel())) {
+
+                    if (shareMoneyMap.containsKey(channel)) {
+                        totalMoney = totalMoney.add(shareMoneyMap.get(channel).multiply(new BigDecimal(s.getCount())));
+                    }
+                    break;
+                }
+            }
+            totalOrderCount += s.getCount();
+        }
+        long userCount = keyOrderMapper.countUser(query);
+        ChannelOrderStatistic statistic = new ChannelOrderStatistic();
+        statistic.setUserCount(userCount);
+        statistic.setMoney(totalMoney);
+        statistic.setCount(totalOrderCount);
+        return statistic;
+    }
+
+    @Override
+    public List<ChannelOrderStatistic> statisticChannelOrders(Long agentId, Date startTime, Date endTime) {
+        KeyOrderMapper.DaoQuery daoQuery = new KeyOrderMapper.DaoQuery();
+        daoQuery.minCreateTime = startTime;
+        daoQuery.maxCreateTime = endTime;
+        daoQuery.agentId = agentId;
+        daoQuery.state = KeyOrder.STATE_PAY;
+        daoQuery.hasPayTime = true;
+        // 灏嗘暟鎹媺鍑烘潵
+        long count = keyOrderMapper.count(daoQuery);
+        daoQuery.count = (int) count;
+        List<KeyOrder> orderList = keyOrderMapper.list(daoQuery);
+        Map<String, Set<Long>> uidsMap = new HashMap<>();
+        Map<String, Integer> countMap = new HashMap<>();
+        Map<String, BigDecimal> moneyMap = new HashMap<>();
+
+        Set<String> orderIds = new HashSet<>();
+        for (KeyOrder order : orderList) {
+            String orderId = order.getOrderType() + "#" + order.getOrderNo();
+            if (!StringUtil.isNullOrEmpty(order.getOrderNo())) {
+                if (orderIds.contains(orderId)) {
+                    continue;
+                }
+                orderIds.add(orderId);
+            }
+            String orderChannel = order.getOrderChannel();
+
+            if (!uidsMap.containsKey(orderChannel)) {
+                uidsMap.put(orderChannel, new HashSet<>());
+            }
+            uidsMap.get(orderChannel).add(order.getUid());
+
+            if (!countMap.containsKey(orderChannel)) {
+                countMap.put(orderChannel, 0);
+            }
+            countMap.put(orderChannel, countMap.get(orderChannel) + 1);
+
+
+            if (!moneyMap.containsKey(orderChannel)) {
+                moneyMap.put(orderChannel, new BigDecimal(0));
+            }
+            moneyMap.put(orderChannel, moneyMap.get(orderChannel).add(order.getOrderMoney()));
+        }
+
+        List<ChannelOrderStatistic> results = new ArrayList<>();
+        for (String orderChannel : moneyMap.keySet()) {
+            ChannelOrderStatistic statistic = new ChannelOrderStatistic();
+            statistic.setCount(countMap.get(orderChannel));
+            statistic.setMoney(moneyMap.get(orderChannel));
+            statistic.setUserCount(uidsMap.get(orderChannel).size());
+            statistic.setOrderChannel(orderChannel);
+            results.add(statistic);
+        }
+        return results;
+    }
+
+
+    @Override
+    public Long getCanDistributeUid(int maxQueueSize) {
+        // 鏈�杩�1灏忔椂鏈夋椿璺�,涓斾笉绠�12浠ヤ笂鏈墽琛岀殑鏁版嵁
+        List<OrderDistributeCountInfo> list = keyOrderMapper.listDistributeUids(new Date(System.currentTimeMillis() - 1000 * 60 * 31L), new Date(System.currentTimeMillis() - 1000 * 60 * 60 * 12L));
         if (list == null || list.size() == 0) {
             return null;
         }
+        // 鎺掗櫎閲嶆柊鍒嗛厤鐨勮澶�
+        List<Long> excludeIds = clientInfoService.getRePayClientIds();
+        for (int i = 0; i < list.size(); i++) {
+            if (excludeIds.contains(list.get(i).getUid())) {
+                list.remove(i);
+                i--;
+            }
+        }
+        List<OrderDistributeCountInfo> filterList = new ArrayList<>();
         // count灏忎簬2鐩存帴瑙嗕负0
         for (OrderDistributeCountInfo info : list) {
-            if (info.getCount() < 2) {
-                info.setCount(0);
+            if (info.getCount() >= maxQueueSize) {
+                continue;
             }
+            filterList.add(info);
+        }
+        if (filterList.size() <= 0) {
+            return null;
         }
 
-        Comparator<OrderDistributeCountInfo> cm = new Comparator<OrderDistributeCountInfo>() {
-            @Override
-            public int compare(OrderDistributeCountInfo o1, OrderDistributeCountInfo o2) {
-                return o1.getCount() - o2.getCount();
-            }
-        };
-        list.sort(cm);
-        if (list.get(0).getCount() == 0) {
-            // 澶勭悊澶у鏁拌澶囬兘娌℃湁鍒嗛厤鐨勬儏鍐�
-            // 灏嗕负0鐨勬暟鎹殢鏈哄垎閰�
-            List<OrderDistributeCountInfo> tempList = new ArrayList<>();
-            for (OrderDistributeCountInfo info : list) {
-                if (info.getCount() == 0) {
-                    tempList.add(info);
-                }
-            }
-            int index = new Random().nextInt(tempList.size());
-            if (index < 0) {
-                index = 0;
-            }
-            if (index >= tempList.size()) {
-                index = tempList.size() - 1;
-            }
-            return tempList.get(index).getUid();
-        }
-        return list.get(0).getUid();
+        return ClientDistributeUtil.computeDistributeClient(filterList);
     }
 
     @Override
@@ -143,4 +403,112 @@
     public void deleteAll(Date maxCreateTime) {
         keyOrderMapper.deleteAll(maxCreateTime);
     }
+
+    @Override
+    public DYOrderDto verifyKey(String orderNoDesc, String orderStatus, String money, Long uid, String keyId) throws KeyVerifyException {
+        int orderType = AlipayOrderUtil.getOrderType(orderNoDesc);
+        if (uid != null) {
+            WxUserSettings settings = wxUserSettingService.getUserSettings(uid);
+            OrderCountTypeEnum orderCountType = OrderCountTypeEnum.SUBMIT_TOKEN_COUNT;
+            int maxCount = settings.getTotalOrderCountPerDay();
+            switch (orderType) {
+                case Constant.ORDER_TYPE_DY:
+                    orderCountType = OrderCountTypeEnum.DY_ORDER_PAY;
+                    maxCount = settings.getDyOrderCountPerDay();
+                    break;
+                case Constant.ORDER_TYPE_KS:
+                    orderCountType = OrderCountTypeEnum.KS_ORDER_PAY;
+                    maxCount = settings.getKsOrderCountPerDay();
+                    break;
+            }
+        }
+
+
+        String orderNo = "";
+        // 鍖归厤杩炵画鐨勬暟瀛�
+        Pattern pattern = Pattern.compile("\\d+");
+        Matcher matcher = pattern.matcher(orderNoDesc);
+        while (matcher.find()) {
+            // 鑾峰彇鍖归厤鍒扮殑鏁板瓧瀛楃涓�
+            String number = matcher.group();
+            if (number.length() > 10) {
+                orderNo = number;
+                break;
+            }
+        }
+
+        if (orderType == Constant.ORDER_TYPE_UNKNOWN) {
+            throw new KeyVerifyException(KeyVerifyException.CODE_ORDER_TYPE_ERROR, "鏈畾涔夌殑璁㈠崟绫诲瀷");
+        }
+
+        if (!StringUtil.isNullOrEmpty(orderStatus) && !orderStatus.contains("鏈敮浠�")) {
+            throw new KeyVerifyException(KeyVerifyException.CODE_ORDER_STATUS_ERROR, "璁㈠崟鐘舵�侊細" + orderStatus);
+        }
+        DYOrderDto dyOrderDto = null;
+        // 鍏堝尮閰嶈鍗�
+        try {
+            if (orderType == Constant.ORDER_TYPE_DY && !StringUtil.isNullOrEmpty(orderNo)) {
+                dyOrderDto = DYOrderApi.getOrderDetail(orderNo);
+                if (dyOrderDto != null && false) {
+                    // 楠岃瘉閲戦
+                    if (dyOrderDto.getPay_amount().intValue() != new BigDecimal(money).multiply(new BigDecimal(100)).setScale(0).intValue()) {
+                        throw new KeyVerifyException(KeyVerifyException.CODE_ORDER_MONEY_NOT_MATCH, String.format("鏀粯閲戦涓庤鍗曢噾棰濅笉涓�鑷达細%s-%d", money, dyOrderDto.getPay_amount()));
+                    }
+                    // 楠岃瘉璁㈠崟鍙锋槸鍚﹀凡缁忓瓨鍦�
+                    KeyOrderMapper.DaoQuery query = new KeyOrderMapper.DaoQuery();
+                    query.orderNo = orderNo;
+                    query.orderType = orderType;
+                    if (count(query) > 1) {
+                        throw new KeyVerifyException(KeyVerifyException.CODE_ORDER_NO_REPEAT, "璁㈠崟鍙烽噸澶嶆彁浜�");
+                    }
+                }
+            } else {
+                throw new KeyOrderException("鎶栭煶璁㈠崟鑾峰彇澶辫触");
+            }
+        } catch (KeyOrderException e) {
+            // 鎶栭煶璁㈠崟鏈獙璇侀�氳繃锛屽尮閰嶉噾棰�
+            // 楠岃瘉鎻愪氦鐨勯噾棰濇槸鍚︽纭�
+            Set<String> moneySet = payMoneySettingService.listAllMoneyAsStr();
+            // 鍖归厤閲戦
+            if (!moneySet.contains(money)) {
+                throw new KeyVerifyException(KeyVerifyException.CODE_KEY_MONEY_NOT_MATCH, String.format("閲戦鏈湪绯荤粺璁剧疆涓細%s", money));
+            }
+        }
+
+        return dyOrderDto;
+    }
+
+    @Override
+    public void removeDistributedClient(String id) {
+        keyOrderMapper.removeDistributedClient(id);
+    }
+
+    @Override
+    public List<Long> listAgentId(KeyOrderMapper.DaoQuery query) {
+        return keyOrderMapper.listAgentId(query);
+    }
+
+    @Override
+    public long countAgentId(KeyOrderMapper.DaoQuery query) {
+        return keyOrderMapper.countAgentId(query);
+    }
+
+    @Override
+    public long countUserNotDoOrder(Long uid, Date minCreateTime) {
+        KeyOrderMapper.DaoQuery daoQuery = new KeyOrderMapper.DaoQuery();
+        daoQuery.uid = uid;
+        daoQuery.stateList = Arrays.asList(new Integer[]{KeyOrder.STATE_NOT_PROCESS, KeyOrder.STATE_NOT_PAY});
+        daoQuery.minCreateTime = minCreateTime;
+        return keyOrderMapper.count(daoQuery);
+    }
+
+    @Transactional(rollbackFor = Exception.class)
+    @Override
+    public void rejectPay(String id, String rejectMsg) {
+        KeyOrder keyOrder = new KeyOrder();
+        keyOrder.setId(id);
+        keyOrder.setState(KeyOrder.STATE_REJECT_PAY);
+        keyOrder.setStateDesc(rejectMsg);
+        update(keyOrder);
+    }
 }

--
Gitblit v1.8.0