Procházet zdrojové kódy

feat(withdraw): 提现系统重构——通道自动选择+税务计算+夜间批处理+管理端点

liaoxg před 5 měsíci
rodič
revize
cfe50745e0

+ 70 - 6
num-server/src/main/java/com/etotem/num/controller/WithdrawController.java

@@ -22,16 +22,19 @@ public class WithdrawController {
     }
     }
 
 
     @PostMapping("/apply")
     @PostMapping("/apply")
-    public Result<?> apply(HttpServletRequest request, @RequestBody Map<String, Integer> body) {
+    public Result<?> apply(HttpServletRequest request, @RequestBody Map<String, Object> body) {
         Long userId = (Long) request.getAttribute("userId");
         Long userId = (Long) request.getAttribute("userId");
-        int amount = body.get("amount");
-        return Result.success(withdrawService.apply(userId, amount));
+        int amount = ((Number) body.get("amount")).intValue();
+        String channel = (String) body.getOrDefault("channel", null);
+        return Result.success(withdrawService.apply(userId, amount, channel));
     }
     }
 
 
     @PostMapping("/list")
     @PostMapping("/list")
-    public Result<?> list(HttpServletRequest request) {
+    public Result<?> list(HttpServletRequest request, @RequestBody Map<String, Object> body) {
         Long userId = (Long) request.getAttribute("userId");
         Long userId = (Long) request.getAttribute("userId");
-        return Result.success(withdrawService.getMyWithdraws(userId));
+        int page = body.containsKey("page") ? ((Number) body.get("page")).intValue() : 0;
+        int size = body.containsKey("size") ? ((Number) body.get("size")).intValue() : 20;
+        return Result.success(withdrawService.getMyWithdraws(userId, page, size));
     }
     }
 
 
     @PostMapping("/balance")
     @PostMapping("/balance")
@@ -39,4 +42,65 @@ public class WithdrawController {
         Long userId = (Long) request.getAttribute("userId");
         Long userId = (Long) request.getAttribute("userId");
         return Result.success(Collections.singletonMap("balance", withdrawService.getAvailableBalance(userId)));
         return Result.success(Collections.singletonMap("balance", withdrawService.getAvailableBalance(userId)));
     }
     }
-}
+
+    // ==================== 管理后台 ====================
+
+    /**
+     * 管理后台:提现列表(全部,带分页)
+     * POST /api/withdraw/admin/list
+     */
+    @PostMapping("/admin/list")
+    public Result<?> adminList(@RequestBody Map<String, Object> body) {
+        int page = body.containsKey("page") ? ((Number) body.get("page")).intValue() : 0;
+        int size = body.containsKey("size") ? ((Number) body.get("size")).intValue() : 20;
+        return Result.success(withdrawService.getAllWithdraws(page, size));
+    }
+
+    /**
+     * 管理后台:审批通过
+     * POST /api/withdraw/admin/approve
+     */
+    @PostMapping("/admin/approve")
+    public Result<?> adminApprove(@RequestBody Map<String, Object> body) {
+        Long id = ((Number) body.get("id")).longValue();
+        Long adminId = body.containsKey("adminId") ? ((Number) body.get("adminId")).longValue() : 0L;
+        withdrawService.approve(id, adminId);
+        return Result.success(null);
+    }
+
+    /**
+     * 管理后台:驳回
+     * POST /api/withdraw/admin/reject
+     */
+    @PostMapping("/admin/reject")
+    public Result<?> adminReject(@RequestBody Map<String, Object> body) {
+        Long id = ((Number) body.get("id")).longValue();
+        String reason = (String) body.getOrDefault("reason", null);
+        withdrawService.reject(id, reason);
+        return Result.success(null);
+    }
+
+    /**
+     * 管理后台:冻结
+     * POST /api/withdraw/admin/freeze
+     */
+    @PostMapping("/admin/freeze")
+    public Result<?> adminFreeze(@RequestBody Map<String, Object> body) {
+        Long id = ((Number) body.get("id")).longValue();
+        withdrawService.freeze(id);
+        return Result.success(null);
+    }
+
+    // ==================== 用户侧 ====================
+
+    /**
+     * 用户侧:提现详情
+     * POST /api/withdraw/detail
+     */
+    @PostMapping("/detail")
+    public Result<?> detail(HttpServletRequest request, @RequestBody Map<String, Long> body) {
+        Long userId = (Long) request.getAttribute("userId");
+        Long id = body.get("id");
+        return Result.success(withdrawService.getDetail(userId, id));
+    }
+}

+ 66 - 0
num-server/src/main/java/com/etotem/num/entity/Withdraw.java

@@ -25,6 +25,48 @@ public class Withdraw {
     @Column(name = "updated_at")
     @Column(name = "updated_at")
     private LocalDateTime updatedAt = LocalDateTime.now();
     private LocalDateTime updatedAt = LocalDateTime.now();
 
 
+    // 提现通道:REFUND(退费) / WECHAT_TRANSFER(企业付款) / THIRD_PARTY(第三方)
+    @Column(length = 30)
+    private String channel;
+
+    // 通道侧状态码
+    @Column(length = 30)
+    private String channelStatus;
+
+    // 税务字段
+    @Column(name = "tax_fen")
+    private Integer taxFen = 0; // 预扣税额(分)
+
+    @Column(name = "net_amount_fen")
+    private Integer netAmountFen; // 实际到账金额(分)
+
+    @Column(name = "tax_rate")
+    private Integer taxRate = 0; // 适用税率(万分比)
+
+    // 批处理字段
+    @Column(name = "batch_id", length = 50)
+    private String batchId; // 批次号
+
+    @Column(name = "processed_at")
+    private LocalDateTime processedAt; // 实际处理时间
+
+    // 微信/通道侧字段
+    @Column(name = "channel_order_no", length = 64)
+    private String channelOrderNo; // 微信付款单号
+
+    @Column(name = "channel_error", length = 200)
+    private String channelError; // 通道错误信息
+
+    // 审批字段
+    @Column(name = "approved_by")
+    private Long approvedBy; // 审批人用户ID
+
+    @Column(name = "approved_at")
+    private LocalDateTime approvedAt; // 审批时间
+
+    @Column(length = 200)
+    private String remark;
+
     public Long getId() { return id; }
     public Long getId() { return id; }
     public void setId(Long id) { this.id = id; }
     public void setId(Long id) { this.id = id; }
     public Long getUserId() { return userId; }
     public Long getUserId() { return userId; }
@@ -37,4 +79,28 @@ public class Withdraw {
     public void setCreatedAt(LocalDateTime createdAt) { this.createdAt = createdAt; }
     public void setCreatedAt(LocalDateTime createdAt) { this.createdAt = createdAt; }
     public LocalDateTime getUpdatedAt() { return updatedAt; }
     public LocalDateTime getUpdatedAt() { return updatedAt; }
     public void setUpdatedAt(LocalDateTime updatedAt) { this.updatedAt = updatedAt; }
     public void setUpdatedAt(LocalDateTime updatedAt) { this.updatedAt = updatedAt; }
+    public String getChannel() { return channel; }
+    public void setChannel(String channel) { this.channel = channel; }
+    public String getChannelStatus() { return channelStatus; }
+    public void setChannelStatus(String channelStatus) { this.channelStatus = channelStatus; }
+    public Integer getTaxFen() { return taxFen; }
+    public void setTaxFen(Integer taxFen) { this.taxFen = taxFen; }
+    public Integer getNetAmountFen() { return netAmountFen; }
+    public void setNetAmountFen(Integer netAmountFen) { this.netAmountFen = netAmountFen; }
+    public Integer getTaxRate() { return taxRate; }
+    public void setTaxRate(Integer taxRate) { this.taxRate = taxRate; }
+    public String getBatchId() { return batchId; }
+    public void setBatchId(String batchId) { this.batchId = batchId; }
+    public LocalDateTime getProcessedAt() { return processedAt; }
+    public void setProcessedAt(LocalDateTime processedAt) { this.processedAt = processedAt; }
+    public String getChannelOrderNo() { return channelOrderNo; }
+    public void setChannelOrderNo(String channelOrderNo) { this.channelOrderNo = channelOrderNo; }
+    public String getChannelError() { return channelError; }
+    public void setChannelError(String channelError) { this.channelError = channelError; }
+    public Long getApprovedBy() { return approvedBy; }
+    public void setApprovedBy(Long approvedBy) { this.approvedBy = approvedBy; }
+    public LocalDateTime getApprovedAt() { return approvedAt; }
+    public void setApprovedAt(LocalDateTime approvedAt) { this.approvedAt = approvedAt; }
+    public String getRemark() { return remark; }
+    public void setRemark(String remark) { this.remark = remark; }
 }
 }

+ 23 - 1
num-server/src/main/java/com/etotem/num/repository/WithdrawRepository.java

@@ -1,10 +1,32 @@
 package com.etotem.num.repository;
 package com.etotem.num.repository;
 
 
 import com.etotem.num.entity.Withdraw;
 import com.etotem.num.entity.Withdraw;
+import org.springframework.data.domain.Page;
+import org.springframework.data.domain.Pageable;
 import org.springframework.data.jpa.repository.JpaRepository;
 import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.Query;
+import org.springframework.data.repository.query.Param;
 
 
+import java.time.LocalDateTime;
 import java.util.List;
 import java.util.List;
 
 
 public interface WithdrawRepository extends JpaRepository<Withdraw, Long> {
 public interface WithdrawRepository extends JpaRepository<Withdraw, Long> {
     List<Withdraw> findByUserIdOrderByCreatedAtDesc(Long userId);
     List<Withdraw> findByUserIdOrderByCreatedAtDesc(Long userId);
-}
+
+    // 查询待批处理提现记录(status in list)
+    List<Withdraw> findByStatusIn(List<String> statuses);
+
+    // 按批次查询
+    List<Withdraw> findByBatchId(String batchId);
+
+    // 统计指定用户已提现总额
+    @Query("SELECT COALESCE(SUM(w.amount), 0) FROM Withdraw w WHERE w.userId = :userId AND w.status = 'success'")
+    long sumSuccessAmountByUserId(@Param("userId") Long userId);
+
+    // 查询用户首次提现时间(用于判断是否30天内首提)
+    @Query("SELECT w.createdAt FROM Withdraw w WHERE w.userId = :userId ORDER BY w.createdAt ASC")
+    List<LocalDateTime> findFirstWithdrawTime(@Param("userId") Long userId, Pageable pageable);
+
+    // 用户提现记录分页
+    Page<Withdraw> findByUserIdOrderByCreatedAtDesc(Long userId, Pageable pageable);
+}

+ 396 - 27
num-server/src/main/java/com/etotem/num/service/WithdrawService.java

@@ -1,71 +1,440 @@
 package com.etotem.num.service;
 package com.etotem.num.service;
 
 
 import com.etotem.num.common.BizException;
 import com.etotem.num.common.BizException;
+import com.etotem.num.entity.Commission;
 import com.etotem.num.entity.Withdraw;
 import com.etotem.num.entity.Withdraw;
-import com.etotem.num.repository.WithdrawRepository;
 import com.etotem.num.repository.CommissionRepository;
 import com.etotem.num.repository.CommissionRepository;
-import com.etotem.num.entity.Commission;
+import com.etotem.num.repository.WithdrawRepository;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.data.domain.Page;
+import org.springframework.data.domain.PageRequest;
+import org.springframework.scheduling.annotation.Scheduled;
 import org.springframework.stereotype.Service;
 import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
 
 
+import java.time.LocalDateTime;
+import java.time.format.DateTimeFormatter;
+import java.util.Collections;
 import java.util.List;
 import java.util.List;
-import java.util.stream.Collectors;
+import java.util.concurrent.atomic.AtomicInteger;
 
 
 @Service
 @Service
 public class WithdrawService {
 public class WithdrawService {
 
 
+    private static final Logger log = LoggerFactory.getLogger(WithdrawService.class);
+
+    /** 最低提现金额:¥100 = 10000分 */
+    private static final int MIN_WITHDRAW_FEN = 10000;
+
+    /** 高额阈值:¥800 = 80000分(超过此金额走第三方通道) */
+    private static final int HIGH_AMOUNT_FEN = 80000;
+
+    /** 免征额度:¥800 = 80000分 */
+    private static final int TAX_FREE_FEN = 80000;
+
+    /** 预扣税率:20% = 2000‱ */
+    private static final int TAX_RATE_PERMILLE = 2000;
+
+    /** 首提30天窗口(天) */
+    private static final int FIRST_WITHDRAW_WINDOW_DAYS = 30;
+
+    /** 连续失败最大次数,超过自动冻结 */
+    private static final int MAX_FAIL_COUNT = 3;
+
     private final WithdrawRepository withdrawRepository;
     private final WithdrawRepository withdrawRepository;
     private final CommissionRepository commissionRepository;
     private final CommissionRepository commissionRepository;
 
 
+    /** 批次号自增序号(每日重置) */
+    private final AtomicInteger batchSequence = new AtomicInteger(0);
+    private String batchDate = "";
+
     public WithdrawService(WithdrawRepository withdrawRepository,
     public WithdrawService(WithdrawRepository withdrawRepository,
                            CommissionRepository commissionRepository) {
                            CommissionRepository commissionRepository) {
         this.withdrawRepository = withdrawRepository;
         this.withdrawRepository = withdrawRepository;
         this.commissionRepository = commissionRepository;
         this.commissionRepository = commissionRepository;
     }
     }
 
 
+    // ==================== 用户侧 ====================
+
+    /**
+     * 1. 申请提现(自动判断通道 + 税务计算)
+     *
+     * @param userId    用户ID
+     * @param amountFen 提现金额(分)
+     * @param channel   指定通道(可为null,自动判断)
+     * @return 新建的 Withdraw 记录
+     */
+    @Transactional
+    public Withdraw apply(Long userId, int amountFen, String channel) {
+        // 金额校验
+        if (amountFen < MIN_WITHDRAW_FEN) {
+            throw new BizException(1006, "最低提现金额为¥100");
+        }
+
+        // 余额校验
+        long balance = getAvailableBalance(userId);
+        if (amountFen > balance) {
+            throw new BizException(1007, "可用余额不足");
+        }
+
+        // 自动判断通道
+        String resolvedChannel = resolveChannel(userId, amountFen, channel);
+
+        // 计算预扣税额
+        int taxFen = calculateTax(userId, amountFen);
+        int netAmountFen = amountFen - taxFen;
+        int taxRate = taxFen > 0 ? TAX_RATE_PERMILLE : 0;
+
+        // 创建提现记录
+        Withdraw w = new Withdraw();
+        w.setUserId(userId);
+        w.setAmount(amountFen);
+        w.setChannel(resolvedChannel);
+        w.setTaxFen(taxFen);
+        w.setNetAmountFen(netAmountFen);
+        w.setTaxRate(taxRate);
+        w.setStatus("pending");
+        return withdrawRepository.save(w);
+    }
+
+    /**
+     * 2. 查询可用余额
+     * 可用余额 = settled佣金总额 - 已成功提现总额
+     */
     public long getAvailableBalance(Long userId) {
     public long getAvailableBalance(Long userId) {
-        return commissionRepository.findByToUserIdOrderByCreatedAtDesc(userId)
+        long settledTotal = commissionRepository.findByToUserIdOrderByCreatedAtDesc(userId)
                 .stream()
                 .stream()
-                .filter(c -> "settled".equals(c.getStatus()))
+                .filter(c -> "settled".equals(c.getStatus()) || "available".equals(c.getStatus()))
                 .mapToLong(Commission::getAmount)
                 .mapToLong(Commission::getAmount)
                 .sum();
                 .sum();
+        long withdrawnTotal = withdrawRepository.sumSuccessAmountByUserId(userId);
+        return settledTotal - withdrawnTotal;
     }
     }
 
 
-    public Withdraw apply(Long userId, int amount) {
-        if (amount < 10000) {
-            throw new BizException(1006, "Minimum withdraw is ¥100");
+    /**
+     * 3. 查询提现记录(带分页)
+     */
+    public Page<Withdraw> getMyWithdraws(Long userId, int page, int size) {
+        return withdrawRepository.findByUserIdOrderByCreatedAtDesc(userId, PageRequest.of(page, size));
+    }
+
+    // ==================== 管理后台侧 ====================
+
+    /**
+     * 4. 审批通过(status: pending → approved → queued)
+     */
+    @Transactional
+    public void approve(Long id, Long adminId) {
+        Withdraw w = withdrawRepository.findById(id)
+                .orElseThrow(() -> new BizException(1002, "提现记录不存在"));
+        if (!"pending".equals(w.getStatus())) {
+            throw new BizException(1008, "当前状态不允许审批");
         }
         }
-        long balance = getAvailableBalance(userId);
-        if (amount > balance) {
-            throw new BizException(1007, "Insufficient balance");
+        w.setStatus("approved");
+        w.setApprovedBy(adminId);
+        w.setApprovedAt(LocalDateTime.now());
+        withdrawRepository.save(w);
+
+        // 审批通过后自动进入排队
+        w.setStatus("queued");
+        withdrawRepository.save(w);
+        log.info("提现记录 {} 审批通过并进入排队,审批人: {}", id, adminId);
+    }
+
+    /**
+     * 5. 驳回(status: pending → rejected)
+     */
+    @Transactional
+    public void reject(Long id, String reason) {
+        Withdraw w = withdrawRepository.findById(id)
+                .orElseThrow(() -> new BizException(1002, "提现记录不存在"));
+        if (!"pending".equals(w.getStatus())) {
+            throw new BizException(1008, "当前状态不允许驳回");
+        }
+        w.setStatus("rejected");
+        w.setRemark(reason);
+        w.setUpdatedAt(LocalDateTime.now());
+        withdrawRepository.save(w);
+        log.info("提现记录 {} 已驳回,原因: {}", id, reason);
+    }
+
+    /**
+     * 6. 冻结(status: any → frozen)
+     */
+    @Transactional
+    public void freeze(Long id) {
+        Withdraw w = withdrawRepository.findById(id)
+                .orElseThrow(() -> new BizException(1002, "提现记录不存在"));
+        String prevStatus = w.getStatus();
+        w.setStatus("frozen");
+        w.setUpdatedAt(LocalDateTime.now());
+        withdrawRepository.save(w);
+        log.info("提现记录 {} 已冻结,原状态: {}", id, prevStatus);
+    }
+
+    /**
+     * 7. 解冻(frozen → pending)
+     */
+    @Transactional
+    public void unfreeze(Long id) {
+        Withdraw w = withdrawRepository.findById(id)
+                .orElseThrow(() -> new BizException(1002, "提现记录不存在"));
+        if (!"frozen".equals(w.getStatus())) {
+            throw new BizException(1008, "当前状态不是冻结状态,无法解冻");
         }
         }
-        Withdraw w = new Withdraw();
-        w.setUserId(userId);
-        w.setAmount(amount);
         w.setStatus("pending");
         w.setStatus("pending");
-        return withdrawRepository.save(w);
+        w.setUpdatedAt(LocalDateTime.now());
+        withdrawRepository.save(w);
+        log.info("提现记录 {} 已解冻", id);
+    }
+
+    // ==================== 定时任务(夜间批处理) ====================
+
+    /**
+     * 8. 夜间 23:30 批量处理
+     * a) 查询所有 status='queued' 的记录
+     * b) 生成批次号(如 20260608-001)
+     * c) 逐条处理(先占位,调用微信/第三方API)
+     * d) 更新最终状态(success/failed)
+     * e) 失败记录错误信息,多次失败自动冻结
+     */
+    @Scheduled(cron = "0 30 23 * * ?")
+    @Transactional
+    public void batchProcessQueuedWithdraws() {
+        List<Withdraw> queuedList = withdrawRepository.findByStatusIn(Collections.singletonList("queued"));
+        if (queuedList.isEmpty()) {
+            log.info("[批处理] 无待处理提现记录");
+            return;
+        }
+
+        String batchId = generateBatchId();
+        log.info("[批处理] 开始处理批次 {},共 {} 条记录", batchId, queuedList.size());
+
+        for (Withdraw w : queuedList) {
+            try {
+                w.setBatchId(batchId);
+                w.setUpdatedAt(LocalDateTime.now());
+
+                // 根据通道调用不同API
+                processByChannel(w);
+
+                w.setProcessedAt(LocalDateTime.now());
+                w.setStatus("success");
+                withdrawRepository.save(w);
+                log.info("[批处理] 提现记录 {} 处理成功", w.getId());
+            } catch (Exception e) {
+                w.setChannelError(e.getMessage() != null && e.getMessage().length() > 200
+                        ? e.getMessage().substring(0, 200) : e.getMessage());
+                w.setUpdatedAt(LocalDateTime.now());
+
+                // 检查连续失败次数
+                int failCount = countRecentFailures(w.getUserId());
+                if (failCount >= MAX_FAIL_COUNT) {
+                    w.setStatus("frozen");
+                    log.warn("[批处理] 用户 {} 连续失败 {} 次,自动冻结提现记录 {}", w.getUserId(), failCount, w.getId());
+                } else {
+                    w.setStatus("failed");
+                }
+                withdrawRepository.save(w);
+                log.error("[批处理] 提现记录 {} 处理失败: {}", w.getId(), e.getMessage());
+            }
+        }
+
+        log.info("[批处理] 批次 {} 处理完成", batchId);
+    }
+
+    /**
+     * 管理后台:全部提现列表(带分页)
+     */
+    public Page<Withdraw> getAllWithdraws(int page, int size) {
+        return withdrawRepository.findAll(PageRequest.of(page, size));
+    }
+
+    /**
+     * 用户侧:提现详情(校验归属)
+     */
+    public Withdraw getDetail(Long userId, Long id) {
+        Withdraw w = withdrawRepository.findById(id)
+                .orElseThrow(() -> new BizException(1002, "提现记录不存在"));
+        if (!w.getUserId().equals(userId)) {
+            throw new BizException(1008, "无权查看该提现记录");
+        }
+        return w;
+    }
+
+    // ==================== 兼容旧接口 ====================
+
+    /** 旧版 apply(无通道参数) */
+    @Transactional
+    public Withdraw apply(Long userId, int amount) {
+        return apply(userId, amount, null);
     }
     }
 
 
+    /** 旧版 getMyWithdraws(无分页) */
     public List<Withdraw> getMyWithdraws(Long userId) {
     public List<Withdraw> getMyWithdraws(Long userId) {
         return withdrawRepository.findByUserIdOrderByCreatedAtDesc(userId);
         return withdrawRepository.findByUserIdOrderByCreatedAtDesc(userId);
     }
     }
 
 
+    /** 旧版 getAllPending */
     public List<Withdraw> getAllPending() {
     public List<Withdraw> getAllPending() {
-        return withdrawRepository.findAll().stream()
-                .filter(w -> "pending".equals(w.getStatus()))
-                .collect(Collectors.toList());
+        return withdrawRepository.findByStatusIn(Collections.singletonList("pending"));
     }
     }
 
 
+    /** 旧版 approve(无审批人) */
+    @Transactional
     public void approve(Long id) {
     public void approve(Long id) {
-        withdrawRepository.findById(id).ifPresent(w -> {
-            w.setStatus("approved");
-            withdrawRepository.save(w);
-        });
+        approve(id, 0L);
     }
     }
 
 
+    /** 旧版 reject(无原因) */
+    @Transactional
     public void reject(Long id) {
     public void reject(Long id) {
-        withdrawRepository.findById(id).ifPresent(w -> {
-            w.setStatus("rejected");
-            withdrawRepository.save(w);
-        });
+        reject(id, null);
+    }
+
+    // ==================== 内部方法 ====================
+
+    /**
+     * 自动判断提现通道
+     * a) 首提且订单<30天 → REFUND
+     * b) 金额>¥800 → THIRD_PARTY
+     * c) 否则 → WECHAT_TRANSFER
+     */
+    private String resolveChannel(Long userId, int amountFen, String specifiedChannel) {
+        // 如果指定了通道,优先使用
+        if (specifiedChannel != null && !specifiedChannel.isEmpty()) {
+            return specifiedChannel;
+        }
+
+        // a) 首提且订单<30天 → REFUND
+        List<LocalDateTime> firstWithdrawTimes = withdrawRepository.findFirstWithdrawTime(
+                userId, PageRequest.of(0, 1));
+        boolean isFirstWithdraw = firstWithdrawTimes.isEmpty();
+
+        if (isFirstWithdraw) {
+            // 检查是否有30天内的订单(通过佣金记录判断)
+            LocalDateTime thirtyDaysAgo = LocalDateTime.now().minusDays(FIRST_WITHDRAW_WINDOW_DAYS);
+            boolean hasRecentOrder = commissionRepository
+                    .findByToUserIdAndCreatedAtBetweenOrderByCreatedAtDesc(userId, thirtyDaysAgo, LocalDateTime.now())
+                    .stream().findAny().isPresent();
+            if (hasRecentOrder) {
+                return "REFUND";
+            }
+        }
+
+        // b) 金额>¥800 → THIRD_PARTY
+        if (amountFen > HIGH_AMOUNT_FEN) {
+            return "THIRD_PARTY";
+        }
+
+        // c) 否则 → WECHAT_TRANSFER
+        return "WECHAT_TRANSFER";
+    }
+
+    /**
+     * 计算预扣税额
+     * ≤¥800免征,>¥800按20%预扣
+     */
+    private int calculateTax(Long userId, int amountFen) {
+        // 查询用户累计提现金额(含本次),判断是否超过免征额
+        long previousWithdrawn = withdrawRepository.sumSuccessAmountByUserId(userId);
+        long totalIncludingThis = previousWithdrawn + amountFen;
+
+        if (totalIncludingThis <= TAX_FREE_FEN) {
+            return 0; // 全部在免征额内
+        }
+
+        // 部分在免征额内,部分需扣税
+        long taxableAmount;
+        if (previousWithdrawn >= TAX_FREE_FEN) {
+            // 之前已超过免征额,本次全额计税
+            taxableAmount = amountFen;
+        } else {
+            // 之前未超免征额,仅超出部分计税
+            taxableAmount = totalIncludingThis - TAX_FREE_FEN;
+        }
+
+        return (int) (taxableAmount * TAX_RATE_PERMILLE / 10000);
+    }
+
+    /**
+     * 生成批次号(如 20260608-001)
+     */
+    private String generateBatchId() {
+        String today = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
+        if (!today.equals(batchDate)) {
+            batchDate = today;
+            batchSequence.set(0);
+        }
+        int seq = batchSequence.incrementAndGet();
+        return String.format("%s-%03d", today, seq);
+    }
+
+    /**
+     * 根据通道处理提现
+     * TODO: 对接微信企业付款/第三方API后替换为真实调用
+     */
+    private void processByChannel(Withdraw w) {
+        switch (w.getChannel()) {
+            case "WECHAT_TRANSFER":
+                processWechatTransfer(w);
+                break;
+            case "REFUND":
+                processRefund(w);
+                break;
+            case "THIRD_PARTY":
+                processThirdParty(w);
+                break;
+            default:
+                throw new RuntimeException("未知提现通道: " + w.getChannel());
+        }
+    }
+
+    /**
+     * 微信企业付款到零钱
+     * TODO: 对接 WeChatService 企业付款API
+     */
+    private void processWechatTransfer(Withdraw w) {
+        // 预留:调用微信企业付款API
+        // String paymentNo = weChatService.transferToUser(w.getUserId(), w.getNetAmountFen());
+        // w.setChannelOrderNo(paymentNo);
+        // w.setChannelStatus("TRANSFER_SUCCESS");
+        log.info("[批处理] 微信企业付款 - 用户: {}, 金额: {}分 (暂为模拟)", w.getUserId(), w.getNetAmountFen());
+        w.setChannelStatus("TRANSFER_SUCCESS");
+    }
+
+    /**
+     * 退费通道处理
+     * TODO: 对接退费API
+     */
+    private void processRefund(Withdraw w) {
+        log.info("[批处理] 退费通道 - 用户: {}, 金额: {}分 (暂为模拟)", w.getUserId(), w.getNetAmountFen());
+        w.setChannelStatus("REFUND_SUCCESS");
+    }
+
+    /**
+     * 第三方通道处理
+     * TODO: 对接第三方支付API
+     */
+    private void processThirdParty(Withdraw w) {
+        log.info("[批处理] 第三方通道 - 用户: {}, 金额: {}分 (暂为模拟)", w.getUserId(), w.getNetAmountFen());
+        w.setChannelStatus("THIRD_PARTY_SUCCESS");
+    }
+
+    /**
+     * 统计用户最近连续失败次数
+     */
+    private int countRecentFailures(Long userId) {
+        List<Withdraw> recent = withdrawRepository.findByUserIdOrderByCreatedAtDesc(userId);
+        int count = 0;
+        for (Withdraw w : recent) {
+            if ("failed".equals(w.getStatus())) {
+                count++;
+            } else {
+                break; // 遇到非失败记录即停止
+            }
+        }
+        return count;
     }
     }
-}
+}