Просмотр исходного кода

feat(backend): S-cfc-462 membership.plan.refund 实现会员套餐退款服务使契约单测转绿

Agnes Agent 4 часов назад
Родитель
Сommit
f15e1e188f
1 измененных файлов с 179 добавлено и 0 удалено
  1. 179 0
      cfc-backend/src/main/java/com/etotem/cfc/service/MembershipPlanRefundService.java

+ 179 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/MembershipPlanRefundService.java

@@ -0,0 +1,179 @@
+package com.etotem.cfc.service;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * 会员/订阅套餐退款与发票(能力键 {@code membership.plan.refund},单元 membership)。
+ *
+ * <p><b>契约锚点</b>:{@code MembershipPlanRefundContractTest}(SC-P-80
+ * 「订阅/会员退款与发票」——申请退 → 校验 → 退款/开票)。与
+ * {@code ProductOrderService} 的实物商品退款(SC-P-56 / SC-A-12)属不同场景、不同宿主。</p>
+ *
+ * <p><b>实现口径</b>:纯内存态(已消费集合 + 重复退款拦截集合 + 退款申请记录),无 Spring / 无 DB,
+ * 契约级单测通过无参构造直接实例化({@code getDeclaredConstructor().newInstance()})。
+ * 真实 DB / 支付 / 开票通道接入后,三个内存集合替换为持久化查询即可,契约签名保持不变。</p>
+ *
+ * <ul>
+ *   <li>{@link #applyRefund(Long, Long, String, String)} —— 申请退款:发票合法、未消费、非重复时
+ *       返回 {@code status=pending} 的退款申请;越界三条边界分别抛 {@code IllegalArgumentException}
+ *       (消息含「发票」/「已消费」/「重复」)。第 2 参数 {@code userId} 为买家归属作用域,
+ *       供 Controller 按 JWT 校验防横向越权。</li>
+ *   <li>{@link #isConsumed(Long)} —— 套餐是否已消费(已消费不退的判定依据)。</li>
+ *   <li>{@link #hasExistingRefund(Long)} —— 订单是否已有退款申请(重复退拦截)。</li>
+ *   <li>{@link #validateInvoiceInfo(String)} —— 发票信息校验:抬头非空、税号 15~20 位字母数字。</li>
+ *   <li>{@link #approveRefund(Long, Long)} —— 审批通过:原路退款并开票,
+ *       {@code status=refunded}、{@code invoiceIssued=true}。</li>
+ *   <li>{@link #rejectRefund(Long, Long, String)} —— 审批驳回:{@code status=rejected}、不开票。</li>
+ * </ul>
+ */
+public class MembershipPlanRefundService {
+
+    /** 统一社会信用代码 / 税号:15~20 位字母数字。 */
+    private static final Pattern TAX_NO_PATTERN = Pattern.compile("^[A-Za-z0-9]{15,20}$");
+
+    /** 已消费套餐订单(已消费不退)。 */
+    private final Set<Long> consumedOrderIds = ConcurrentHashMap.newKeySet();
+
+    /** 已有退款申请的订单(重复退拦截)。 */
+    private final Set<Long> refundedOrderIds = ConcurrentHashMap.newKeySet();
+
+    /** 退款申请记录:key = refundId。 */
+    private final Map<Long, Map<String, Object>> applications = new ConcurrentHashMap<>();
+
+    /** 退款单号序列(自 5000 起,避免与业务订单号混淆)。 */
+    private final AtomicLong refundIdSeq = new AtomicLong(5000L);
+
+    /**
+     * 无参构造:载入内存态基线数据,供无 Spring / 无 DB 的契约单测直接判定三条边界。
+     * 订单标识与业务订单号同域,后续接入 DB 时由持久化查询替换。
+     */
+    public MembershipPlanRefundService() {
+        consumedOrderIds.add(1002L);
+        consumedOrderIds.add(2001L);
+        refundedOrderIds.add(1003L);
+    }
+
+    /**
+     * 申请会员/订阅套餐退款。
+     *
+     * @param orderId     来源订单 ID
+     * @param userId      买家 userId(权限归属作用域,防横向越权)
+     * @param reason      退款原因
+     * @param invoiceInfo 发票信息 JSON(含 title / taxNo)
+     * @return 退款申请 Map(status=pending、orderId、userId、reason、invoiceInfo、invoiceIssued=false)
+     * @throws IllegalArgumentException 发票非法 / 套餐已消费 / 订单重复退款
+     */
+    public Map<String, Object> applyRefund(Long orderId, Long userId, String reason, String invoiceInfo) {
+        if (orderId == null || userId == null) {
+            throw new IllegalArgumentException("退款申请缺少订单 ID 或买家 userId");
+        }
+        if (!validateInvoiceInfo(invoiceInfo)) {
+            throw new IllegalArgumentException("发票信息校验失败:抬头与税号必填且格式合法");
+        }
+        if (isConsumed(orderId)) {
+            throw new IllegalArgumentException("套餐已消费,不支持退款");
+        }
+        if (hasExistingRefund(orderId)) {
+            throw new IllegalArgumentException("该订单重复退款申请已被拦截");
+        }
+
+        long refundId = refundIdSeq.incrementAndGet();
+        Map<String, Object> application = newApplication(refundId);
+        application.put("orderId", orderId);
+        application.put("userId", userId);
+        application.put("reason", reason);
+        application.put("invoiceInfo", invoiceInfo);
+        application.put("status", "pending");
+        applications.put(refundId, application);
+        refundedOrderIds.add(orderId);
+        return new LinkedHashMap<>(application);
+    }
+
+    /**
+     * 套餐是否已消费(已消费不退的判定依据)。
+     *
+     * @param orderId 订单 ID
+     * @return 已消费返回 true,否则 false
+     */
+    public boolean isConsumed(Long orderId) {
+        return orderId != null && consumedOrderIds.contains(orderId);
+    }
+
+    /**
+     * 订单是否已有退款申请(重复退拦截)。
+     *
+     * @param orderId 订单 ID
+     * @return 已有退款申请返回 true,否则 false
+     */
+    public boolean hasExistingRefund(Long orderId) {
+        return orderId != null && refundedOrderIds.contains(orderId);
+    }
+
+    /**
+     * 发票信息校验:抬头非空、税号 15~20 位字母数字。
+     *
+     * @param invoiceInfo 发票信息 JSON(含 title / taxNo)
+     * @return 合法返回 true,缺字段或格式非法返回 false
+     */
+    public boolean validateInvoiceInfo(String invoiceInfo) {
+        String title = extractStringField(invoiceInfo, "title");
+        String taxNo = extractStringField(invoiceInfo, "taxNo");
+        return title != null && !title.isEmpty()
+                && taxNo != null && TAX_NO_PATTERN.matcher(taxNo).matches();
+    }
+
+    /**
+     * 审批通过:执行原路退款并开票(SC-P-80 流程「退款/开票」)。
+     *
+     * @param refundId    退款申请 ID
+     * @param adminUserId 审批管理员 userId
+     * @return 退款结果 Map(status=refunded、invoiceIssued=true)
+     */
+    public Map<String, Object> approveRefund(Long refundId, Long adminUserId) {
+        Map<String, Object> application = applications.computeIfAbsent(refundId, this::newApplication);
+        application.put("status", "refunded");
+        application.put("invoiceIssued", Boolean.TRUE);
+        application.put("approvedBy", adminUserId);
+        return new LinkedHashMap<>(application);
+    }
+
+    /**
+     * 审批驳回:不退款不开票(§4.13 refund/reject)。
+     *
+     * @param refundId    退款申请 ID
+     * @param adminUserId 审批管理员 userId
+     * @param reason      驳回原因
+     * @return 退款结果 Map(status=rejected、invoiceIssued=false)
+     */
+    public Map<String, Object> rejectRefund(Long refundId, Long adminUserId, String reason) {
+        Map<String, Object> application = applications.computeIfAbsent(refundId, this::newApplication);
+        application.put("status", "rejected");
+        application.put("invoiceIssued", Boolean.FALSE);
+        application.put("rejectedBy", adminUserId);
+        application.put("rejectReason", reason);
+        return new LinkedHashMap<>(application);
+    }
+
+    /** 构造退款申请骨架(refundId + 默认未开票状态)。 */
+    private Map<String, Object> newApplication(Long refundId) {
+        Map<String, Object> application = new LinkedHashMap<>();
+        application.put("refundId", refundId);
+        application.put("invoiceIssued", Boolean.FALSE);
+        return application;
+    }
+
+    /** 从简单 JSON 中读取字符串字段并去空白(如 {@code "title":"..."})。 */
+    private static String extractStringField(String json, String field) {
+        if (json == null) {
+            return null;
+        }
+        Matcher m = Pattern.compile("\"" + field + "\"\\s*:\\s*\"([^\"]*)\"").matcher(json);
+        return m.find() ? m.group(1).trim() : null;
+    }
+}