فهرست منبع

feat(coupon-share): 优惠券分享转赠 T02 后端接口+契约单测(commitTransfer 抽取 + CouponShareService + Controller 5 端点 + JwtInterceptor 放行)

Agnes Agent 14 ساعت پیش
والد
کامیت
2ceab5553e

+ 10 - 1
cfc-backend/src/main/java/com/etotem/cfc/config/JwtInterceptor.java

@@ -87,6 +87,8 @@ private static final String[] PUBLIC_PATHS = {
          "/api/activity/detail",
          "/api/activity/order/notify",
          "/api/content-sections/visible",
+         // 会员券分享转赠:落地领取页匿名可浏览(share/detail 公开;其余 4 接口见 LOGIN_REQUIRED_PATHS)
+         "/api/coupon/gift/share/detail",
          "/api/mcp/**"
      };
 
@@ -154,7 +156,14 @@ private static final String[] PUBLIC_PATHS = {
         // 登录,无 token 直接 401,controller 层再按 @RequestAttribute("role") 守卫拒绝非 admin,
         // 构成双层防线(契约:admin.article.create / S-cfc-153、admin.article.audit / S-cfc-154)。
         // 注意 /api/admin-auth/* 不匹配此前缀(admin-auth ≠ admin/),仍走 PUBLIC_PATHS,不受影响。
-        "/api/admin/"
+        "/api/admin/",
+        // 会员券分享转赠(ARCH-CFC-COUPON-SHARE-GIFT-001 §5):create/claim/revoke/list 为写数据/
+        // 私有数据操作,匿名(userId=-1)不得放行(否则业务 500 口径漂移),无 token 直接 401;
+        // detail 已在 PUBLIC_PATHS 公开(匿名可浏览)。
+        "/api/coupon/gift/share/create",
+        "/api/coupon/gift/share/claim",
+        "/api/coupon/gift/share/revoke",
+        "/api/coupon/gift/share/list"
     };
 
     /**

+ 66 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/CouponGiftController.java

@@ -2,6 +2,7 @@ package com.etotem.cfc.controller;
 
 import com.etotem.cfc.common.Result;
 import com.etotem.cfc.service.CouponGiftService;
+import com.etotem.cfc.service.CouponShareService;
 import com.etotem.cfc.util.ParamUtils;
 import org.springframework.web.bind.annotation.PostMapping;
 import org.springframework.web.bind.annotation.RequestAttribute;
@@ -24,6 +25,9 @@ public class CouponGiftController {
     @Resource
     private CouponGiftService couponGiftService;
 
+    @Resource
+    private CouponShareService couponShareService;
+
     /** 可接收转赠的推荐下级列表(直推 + 隔级) */
     @PostMapping("/recipients")
     public Result<List<Map<String, Object>>> recipients(@RequestAttribute("userId") Long userId) {
@@ -78,4 +82,66 @@ public class CouponGiftController {
     public Result<List<Map<String, Object>>> received(@RequestAttribute("userId") Long userId) {
         return Result.success(couponGiftService.listReceived(userId));
     }
+
+    // ==================== 分享转赠(/api/coupon/gift/share/*,ARCH-CFC-COUPON-SHARE-GIFT-001 §5) ====================
+
+    /** 创建分享:生成 shareToken(幂等:同 giver+familyCouponId 已有 PENDING 返回既有 token) */
+    @PostMapping("/share/create")
+    public Result<Map<String, Object>> shareCreate(@RequestAttribute("userId") Long userId,
+                                                   @RequestBody Map<String, Object> params) {
+        Long familyCouponId = ParamUtils.getLong(params.get("familyCouponId"));
+        try {
+            return Result.success(couponShareService.create(userId, familyCouponId));
+        } catch (IllegalArgumentException e) {
+            return Result.error(e.getMessage());
+        }
+    }
+
+    /** 分享详情(公开接口,匿名可浏览;JwtInterceptor 已放行 detail,不注入 userId) */
+    @PostMapping("/share/detail")
+    public Result<Map<String, Object>> shareDetail(@RequestBody Map<String, Object> params) {
+        String shareToken = ParamUtils.getString(params.get("shareToken"));
+        try {
+            return Result.success(couponShareService.detail(shareToken, null));
+        } catch (IllegalArgumentException e) {
+            if (CouponShareService.MSG_SHARE_NOT_FOUND.equals(e.getMessage())) {
+                return Result.notFound(e.getMessage());
+            }
+            return Result.error(e.getMessage());
+        }
+    }
+
+    /** 领取分享:条件更新防重领,成功返回 transferId */
+    @PostMapping("/share/claim")
+    public Result<Map<String, Object>> shareClaim(@RequestAttribute("userId") Long userId,
+                                                  @RequestBody Map<String, Object> params) {
+        String shareToken = ParamUtils.getString(params.get("shareToken"));
+        try {
+            Long transferId = couponShareService.claim(userId, shareToken);
+            Map<String, Object> data = new java.util.HashMap<>();
+            data.put("transferId", transferId);
+            return Result.success(data);
+        } catch (IllegalArgumentException e) {
+            return Result.error(e.getMessage());
+        }
+    }
+
+    /** 撤回一笔 PENDING 分享(不动券实例) */
+    @PostMapping("/share/revoke")
+    public Result<Map<String, Object>> shareRevoke(@RequestAttribute("userId") Long userId,
+                                                   @RequestBody Map<String, Object> params) {
+        String shareToken = ParamUtils.getString(params.get("shareToken"));
+        try {
+            couponShareService.revoke(userId, shareToken);
+            return Result.success(java.util.Collections.singletonMap("message", "已撤回"));
+        } catch (IllegalArgumentException e) {
+            return Result.error(e.getMessage());
+        }
+    }
+
+    /** 我的分享记录(created_at DESC) */
+    @PostMapping("/share/list")
+    public Result<List<Map<String, Object>>> shareList(@RequestAttribute("userId") Long userId) {
+        return Result.success(couponShareService.list(userId));
+    }
 }

+ 54 - 7
cfc-backend/src/main/java/com/etotem/cfc/service/CouponGiftService.java

@@ -251,20 +251,67 @@ public class CouponGiftService {
             throw new IllegalArgumentException("只能转赠给自己的直推或隔级推荐人");
         }
 
+        // 券实例转移 + transfer 记录 + 通知 + 审计:统一下沉到 commitTransfer(分享转赠复用,行为不变)
+        return commitTransfer(giverUserId, giverFamilyId, receiverUserId, receiver.getFamilyId(),
+                coupon.getId(), fc.getId(), referral.getLevel(), "DIRECT", null, remark);
+    }
+
+    /**
+     * 提交券实例转移 + transfer 记录 + 通知 + 审计流水(定向转赠与分享转赠共有的尾段)。
+     *
+     * <p>调用方必须在事务中({@code @Transactional} 传播 REQUIRED 合并):定向转赠
+     * {@link #transfer} 与分享转赠 {@code CouponShareService.claim} 均在本方法内完成
+     * 「券实例归属转移(family_coupon.family_id + is_gift=1)→ coupon_gift_transfer 记录 →
+     * 通知(模板 coupon_gift)→ grant log(GIFT_TRANSFER, source=transfer:id)」,任一失败整体回滚。</p>
+     *
+     * @param giverUserId     赠送人 users.id
+     * @param giverFamilyId   赠送人家庭
+     * @param receiverUserId  接收人 users.id(券最终归属人)
+     * @param receiverFamilyId 接收人家庭(券实例最终归属)
+     * @param couponId        券模板 id
+     * @param familyCouponId  family_coupon 实例 id
+     * @param giftLevel       推荐层级(定向:1=直推/2=隔级;分享:0=无推荐层级,见 SHARE_GIFT_LEVEL)
+     * @param claimMethod     领取方式:"DIRECT"=定向转赠 / "SHARE"=分享转赠(null 兜底 DIRECT)
+     * @param shareToken      分享领取时回写 coupon_gift_transfer.share_token(定向为 null)
+     * @param remark          留言(可空)
+     * @return transferId
+     */
+    @Transactional
+    public Long commitTransfer(Long giverUserId, Long giverFamilyId,
+                               Long receiverUserId, Long receiverFamilyId,
+                               Long couponId, Long familyCouponId,
+                               Integer giftLevel, String claimMethod,
+                               String shareToken, String remark) {
+        if (giverUserId == null || receiverUserId == null || familyCouponId == null
+                || couponId == null || receiverFamilyId == null) {
+            throw new IllegalArgumentException("参数不完整");
+        }
+        Coupon coupon = couponMapper.selectById(couponId);
+        if (coupon == null) {
+            throw new IllegalArgumentException("优惠券已失效");
+        }
+
         // 转移券实例到接收方家庭,并打 is_gift 标记(接收方非会员也可用其购买会员)
-        fc.setFamilyId(receiver.getFamilyId());
+        FamilyCoupon fc = familyCouponMapper.selectById(familyCouponId);
+        if (fc == null) {
+            throw new IllegalArgumentException("该优惠券不可用或不属于你");
+        }
+        fc.setFamilyId(receiverFamilyId);
         fc.setIsGift(1);
         familyCouponMapper.updateById(fc);
 
+        Date now = new Date();
         CouponGiftTransfer transfer = new CouponGiftTransfer();
         transfer.setGiverUserId(giverUserId);
         transfer.setGiverFamilyId(giverFamilyId);
         transfer.setReceiverUserId(receiverUserId);
-        transfer.setReceiverFamilyId(receiver.getFamilyId());
+        transfer.setReceiverFamilyId(receiverFamilyId);
         transfer.setCouponId(coupon.getId());
         transfer.setFamilyCouponId(fc.getId());
-        transfer.setGiftLevel(referral.getLevel());
+        transfer.setGiftLevel(giftLevel);
         transfer.setStatus("GIFTED");
+        transfer.setClaimMethod(claimMethod != null ? claimMethod : "DIRECT");
+        transfer.setShareToken(shareToken);
         transfer.setRemark(remark);
         transfer.setCreatedAt(now);
         couponGiftTransferMapper.insert(transfer);
@@ -289,9 +336,9 @@ public class CouponGiftService {
                     transfer.getId(), e.getMessage());
         }
 
-        // 发放流水(审计)
+        // 发放流水(审计)——分享与定向统一 GIFT_TRANSFER,source 均记 transferId(对账口径一致)
         FamilyCouponGrantLog log = new FamilyCouponGrantLog();
-        log.setFamilyId(receiver.getFamilyId());
+        log.setFamilyId(receiverFamilyId);
         log.setCouponId(coupon.getId());
         log.setGrantType("GIFT_TRANSFER");
         log.setPeriod(null);
@@ -300,8 +347,8 @@ public class CouponGiftService {
         log.setCreatedAt(now);
         familyCouponGrantLogMapper.insert(log);
 
-        logger.info("会员券转赠成功: giver={}, receiver={}, familyCouponId={}, level={}, transferId={}",
-                giverUserId, receiverUserId, familyCouponId, referral.getLevel(), transfer.getId());
+        logger.info("会员券转赠提交: giver={}, receiver={}, familyCouponId={}, level={}, method={}, transferId={}",
+                giverUserId, receiverUserId, familyCouponId, giftLevel, transfer.getClaimMethod(), transfer.getId());
         return transfer.getId();
     }
 

+ 448 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/CouponShareService.java

@@ -0,0 +1,448 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
+import com.etotem.cfc.entity.Coupon;
+import com.etotem.cfc.entity.CouponShare;
+import com.etotem.cfc.entity.FamilyCoupon;
+import com.etotem.cfc.entity.FamilyCouponGrantLog;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.CouponMapper;
+import com.etotem.cfc.mapper.CouponShareMapper;
+import com.etotem.cfc.mapper.FamilyCouponGrantLogMapper;
+import com.etotem.cfc.mapper.FamilyCouponMapper;
+import com.etotem.cfc.mapper.UserMapper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+import org.springframework.util.StringUtils;
+
+import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.UUID;
+
+/**
+ * 会员券「分享转赠」服务(ARCH-CFC-COUPON-SHARE-GIFT-001 §6.2 + §5)。
+ *
+ * <p>在既有「定向转赠」({@link CouponGiftService})之上新增分享通道:
+ * <ul>
+ *   <li><b>create</b>:生成全局唯一 {@code shareToken}(两段式分享第一步),幂等——同
+ *       {@code giverUserId + familyCouponId} 已有 PENDING 分享直接返回既有 token,不新建;
+ *       事务内 {@code SELECT ... FOR UPDATE} 锁行防并发双 PENDING。</li>
+ *   <li><b>detail</b>:公开接口(JwtInterceptor 已放行),匿名可浏览,懒判定 EXPIRED。</li>
+ *   <li><b>claim</b>:单事务,核心「条件更新 PENDING→CLAIMED 影响 1 行」原子防重领,
+ *       成功后复用 {@link CouponGiftService#commitTransfer} 完成券实例转移 + transfer 记录 +
+ *       通知 + 审计流水(claimMethod=SHARE、shareToken 回写、giftLevel=0)。</li>
+ *   <li><b>revoke</b>:PENDING→REVOKED(券实例仍在赠送人名下,不动券);CLAIMED 终态不可撤回。</li>
+ *   <li><b>list</b>:我的分享记录,created_at DESC。</li>
+ * </ul></p>
+ *
+ * <p>错误文案统一使用本类 {@code MSG_*} 常量(§11 约定:集中定义,Controller 与测试复用)。</p>
+ */
+@Service
+public class CouponShareService {
+
+    private static final Logger logger = LoggerFactory.getLogger(CouponShareService.class);
+
+    // ---------------- 错误文案常量(§11:集中定义,Controller/测试复用) ----------------
+    public static final String MSG_PARAM_INCOMPLETE = "参数不完整";
+    public static final String MSG_NO_FAMILY = "请先加入家庭";
+    public static final String MSG_COUPON_UNAVAILABLE = "该优惠券不可用或不属于你";
+    public static final String MSG_COUPON_INVALID = "优惠券已失效";
+    public static final String MSG_COUPON_EXPIRED = "优惠券已过期";
+    public static final String MSG_ONLY_MEMBERSHIP = "仅会员专属券可分享";
+    public static final String MSG_SHARE_NOT_FOUND = "分享不存在或已失效";
+    public static final String MSG_SHARE_NOT_EXIST = "分享不存在";
+    public static final String MSG_ALREADY_CLAIMED = "该分享已被领取";
+    public static final String MSG_ALREADY_REVOKED = "该分享已撤回";
+    public static final String MSG_SHARE_EXPIRED = "该分享已过期";
+    public static final String MSG_SELF_CLAIM = "不能领取自己分享的券";
+    public static final String MSG_SAME_FAMILY = "不能领取同家庭成员的券";
+    public static final String MSG_CLAIM_FAILED = "领取失败,请联系客服";
+    public static final String MSG_NO_PERMISSION = "无权操作该分享";
+    public static final String MSG_CLAIMED_CANNOT_REVOKE = "该分享已被领取,无法撤回";
+
+    /** 分享链路无推荐层级:coupon_gift_transfer.gift_level 写 0(§4.2) */
+    public static final int SHARE_GIFT_LEVEL = 0;
+
+    /** 分享有效期天数,可配置 coupon.share.expire-days(本期落常量 + application.yml/db config 占位) */
+    public static final int DEFAULT_EXPIRE_DAYS = 7;
+
+    private static final long DAY_MILLIS = 24L * 3600 * 1000;
+
+    private static final String STATUS_PENDING = "PENDING";
+    private static final String STATUS_CLAIMED = "CLAIMED";
+    private static final String STATUS_REVOKED = "REVOKED";
+    private static final String STATUS_EXPIRED = "EXPIRED";
+    private static final String CLAIM_METHOD_SHARE = "SHARE";
+    private static final String GIFTABLE_APPLICABLE_TO = "MEMBERSHIP";
+    private static final String AVAILABLE = "AVAILABLE";
+    private static final String ACTIVE = "ACTIVE";
+    private static final String SHARE_PATH_PREFIX = "/pages/coupon/share-claim?shareToken=";
+
+    @Resource
+    private CouponShareMapper couponShareMapper;
+    @Resource
+    private FamilyCouponMapper familyCouponMapper;
+    @Resource
+    private CouponMapper couponMapper;
+    @Resource
+    private UserMapper userMapper;
+    @Resource
+    private CouponGiftService couponGiftService;   // 复用 commitTransfer(定向转赠尾段)
+    @Resource
+    private NotificationDispatchService notificationDispatchService;
+    @Resource
+    private FamilyCouponGrantLogMapper familyCouponGrantLogMapper;
+
+    // ----------------------------------------------------------------
+    // create(幂等 + 防并发双 PENDING)
+    // ----------------------------------------------------------------
+
+    /**
+     * 创建一笔分享,返回 {@code {shareToken, sharePath, expireAt}}。
+     *
+     * <p>幂等:同一 {@code giverUserId + familyCouponId} 已存在 PENDING 分享时直接返回既有
+     * token(不新建、不报错,§2.4)。并发双 PENDING 靠事务内 {@code SELECT ... FOR UPDATE}
+     * 锁行 serialize;token 另有 {@code uk_share_token} 全局唯一索引兜底。</p>
+     *
+     * @param giverUserId    赠送人 users.id(已登录)
+     * @param familyCouponId 被分享的 family_coupon 实例 ID
+     * @return {shareToken, sharePath, expireAt}
+     */
+    @Transactional
+    public Map<String, Object> create(Long giverUserId, Long familyCouponId) {
+        if (giverUserId == null || familyCouponId == null) {
+            throw new IllegalArgumentException(MSG_PARAM_INCOMPLETE);
+        }
+        Long giverFamilyId = getFamilyId(giverUserId);
+        if (giverFamilyId == null) {
+            throw new IllegalArgumentException(MSG_NO_FAMILY);
+        }
+        Date now = new Date();
+
+        // 幂等查询(锁行防并发双 PENDING):同 giver+familyCouponId 已有 PENDING → 复用既有分享
+        CouponShare existing = couponShareMapper.selectOne(
+                new LambdaQueryWrapper<CouponShare>()
+                        .eq(CouponShare::getGiverUserId, giverUserId)
+                        .eq(CouponShare::getFamilyCouponId, familyCouponId)
+                        .eq(CouponShare::getStatus, STATUS_PENDING)
+                        .last("LIMIT 1 FOR UPDATE"));
+        if (existing != null) {
+            logger.info("会员券分享创建幂等命中: giver={}, familyCouponId={}, token={}",
+                    giverUserId, familyCouponId, existing.getShareToken());
+            return buildCreateResult(existing);
+        }
+
+        // 券校验(属于赠送人家庭 && AVAILABLE && applicableTo=MEMBERSHIP && ACTIVE && 未过期)
+        FamilyCoupon fc = familyCouponMapper.selectById(familyCouponId);
+        if (fc == null || !Objects.equals(fc.getFamilyId(), giverFamilyId)
+                || !AVAILABLE.equals(fc.getStatus())) {
+            throw new IllegalArgumentException(MSG_COUPON_UNAVAILABLE);
+        }
+        Coupon coupon = couponMapper.selectById(fc.getCouponId());
+        if (coupon == null || !ACTIVE.equals(coupon.getStatus())) {
+            throw new IllegalArgumentException(MSG_COUPON_INVALID);
+        }
+        if (!GIFTABLE_APPLICABLE_TO.equals(coupon.getApplicableTo())) {
+            throw new IllegalArgumentException(MSG_ONLY_MEMBERSHIP);
+        }
+        if (coupon.getValidFrom() != null && now.before(coupon.getValidFrom())
+                || coupon.getValidUntil() != null && now.after(coupon.getValidUntil())) {
+            throw new IllegalArgumentException(MSG_COUPON_EXPIRED);
+        }
+
+        CouponShare share = new CouponShare();
+        share.setShareToken(generateShareToken());
+        share.setGiverUserId(giverUserId);
+        share.setGiverFamilyId(giverFamilyId);
+        share.setFamilyCouponId(familyCouponId);
+        share.setCouponId(coupon.getId());
+        share.setStatus(STATUS_PENDING);
+        share.setExpireAt(new Date(now.getTime() + DEFAULT_EXPIRE_DAYS * DAY_MILLIS));
+        share.setCreatedAt(now);
+        couponShareMapper.insert(share);
+
+        logger.info("会员券分享创建成功: giver={}, familyCouponId={}, token={}, expireAt={}",
+                giverUserId, familyCouponId, share.getShareToken(), share.getExpireAt());
+        return buildCreateResult(share);
+    }
+
+    // ----------------------------------------------------------------
+    // detail(公开——匿名可浏览,懒判定 EXPIRED)
+    // ----------------------------------------------------------------
+
+    /**
+     * 分享详情(ShareDetailVO,公开接口,匿名可调)。
+     *
+     * @param shareToken    分享令牌
+     * @param viewerUserId  浏览用户(可空;本期仅返回 claimable,不区分 viewerCanClaim)
+     * @return {shareToken, status, couponName, couponValue, couponType, minSpend,
+     *          validUntil, giverNickname, giverAvatar, expireAt, claimable}
+     */
+    public Map<String, Object> detail(String shareToken, Long viewerUserId) {
+        if (!StringUtils.hasText(shareToken)) {
+            throw new IllegalArgumentException(MSG_PARAM_INCOMPLETE);
+        }
+        CouponShare share = findShare(shareToken);
+        if (share == null) {
+            throw new IllegalArgumentException(MSG_SHARE_NOT_FOUND);
+        }
+        Date now = new Date();
+        Coupon coupon = couponMapper.selectById(share.getCouponId());
+        User giver = userMapper.selectById(share.getGiverUserId());
+
+        boolean couponActive = coupon != null
+                && ACTIVE.equals(coupon.getStatus())
+                && (coupon.getValidFrom() == null || !now.before(coupon.getValidFrom()))
+                && (coupon.getValidUntil() == null || !now.after(coupon.getValidUntil()));
+        boolean claimable = STATUS_PENDING.equals(share.getStatus())
+                && share.getExpireAt() != null && !now.after(share.getExpireAt())
+                && couponActive;
+
+        Map<String, Object> data = new HashMap<>();
+        data.put("shareToken", share.getShareToken());
+        data.put("status", resolveDisplayStatus(share, now));
+        data.put("couponName", coupon != null ? coupon.getName() : "优惠券");
+        data.put("couponValue", coupon != null ? coupon.getValue() : null);
+        data.put("couponType", coupon != null ? coupon.getType() : null);
+        data.put("minSpend", coupon != null ? coupon.getMinSpend() : null);
+        data.put("validUntil", coupon != null ? coupon.getValidUntil() : null);
+        data.put("giverNickname", giver != null && StringUtils.hasText(giver.getNickname())
+                ? giver.getNickname() : "微信用户");
+        data.put("giverAvatar", giver != null ? giver.getAvatar() : null);
+        data.put("expireAt", share.getExpireAt());
+        data.put("claimable", claimable);
+        return data;
+    }
+
+    // ----------------------------------------------------------------
+    // claim(并发防重领 = 核心,单事务)
+    // ----------------------------------------------------------------
+
+    /**
+     * 领取一笔分享,返回 transferId。
+     *
+     * <p>单事务(§5.3):① 校验(分享存在/非本人/非同家庭/状态/券可用)→
+     * ② 条件更新 PENDING→CLAIMED(影响 1 行才继续,原子防重领)→
+     * ③ 复用 {@link CouponGiftService#commitTransfer} 完成券实例转移 + transfer 记录 +
+     *    通知接收人 + 审计流水(claimMethod=SHARE、shareToken 回写、giftLevel=0)→
+     * ④ 通知赠送人 → ⑤ 分享链路审计流水(source=share:id)。②~⑤ 任一失败整体回滚。</p>
+     */
+    @Transactional
+    public Long claim(Long claimUserId, String shareToken) {
+        if (claimUserId == null || !StringUtils.hasText(shareToken)) {
+            throw new IllegalArgumentException(MSG_PARAM_INCOMPLETE);
+        }
+        CouponShare share = findShare(shareToken);
+        if (share == null) {
+            throw new IllegalArgumentException(MSG_SHARE_NOT_FOUND);
+        }
+        if (Objects.equals(share.getGiverUserId(), claimUserId)) {
+            throw new IllegalArgumentException(MSG_SELF_CLAIM);
+        }
+        User claimUser = userMapper.selectById(claimUserId);
+        if (claimUser == null || claimUser.getFamilyId() == null) {
+            throw new IllegalArgumentException(MSG_CLAIM_FAILED);
+        }
+        Long claimFamilyId = claimUser.getFamilyId();
+        if (Objects.equals(claimFamilyId, share.getGiverFamilyId())) {
+            throw new IllegalArgumentException(MSG_SAME_FAMILY);
+        }
+
+        Date now = new Date();
+        if (STATUS_REVOKED.equals(share.getStatus())) {
+            throw new IllegalArgumentException(MSG_ALREADY_REVOKED);
+        }
+        if (STATUS_CLAIMED.equals(share.getStatus())) {
+            throw new IllegalArgumentException(MSG_ALREADY_CLAIMED);
+        }
+        if (STATUS_EXPIRED.equals(share.getStatus())
+                || (share.getExpireAt() != null && now.after(share.getExpireAt()))) {
+            throw new IllegalArgumentException(MSG_SHARE_EXPIRED);
+        }
+        Coupon coupon = couponMapper.selectById(share.getCouponId());
+        if (coupon == null || !ACTIVE.equals(coupon.getStatus())) {
+            throw new IllegalArgumentException(MSG_COUPON_INVALID);
+        }
+        if (coupon.getValidFrom() != null && now.before(coupon.getValidFrom())
+                || coupon.getValidUntil() != null && now.after(coupon.getValidUntil())) {
+            throw new IllegalArgumentException(MSG_COUPON_EXPIRED);
+        }
+        // 券实例仍应在赠送人名下且可用(与 transfer 前置校验同口径)
+        FamilyCoupon fc = familyCouponMapper.selectById(share.getFamilyCouponId());
+        if (fc == null || !Objects.equals(fc.getFamilyId(), share.getGiverFamilyId())
+                || !AVAILABLE.equals(fc.getStatus())) {
+            throw new IllegalArgumentException(MSG_COUPON_INVALID);
+        }
+
+        // ② 条件更新 PENDING→CLAIMED:影响行数=1 才继续(并发第二个请求 / 已被领走 / 已撤回均 0 行)
+        int updated = couponShareMapper.update(null, new LambdaUpdateWrapper<CouponShare>()
+                .eq(CouponShare::getShareToken, shareToken)
+                .eq(CouponShare::getStatus, STATUS_PENDING)
+                .set(CouponShare::getStatus, STATUS_CLAIMED)
+                .set(CouponShare::getClaimUserId, claimUserId)
+                .set(CouponShare::getClaimFamilyId, claimFamilyId)
+                .set(CouponShare::getClaimTime, now));
+        if (updated != 1) {
+            throw new IllegalArgumentException(MSG_ALREADY_CLAIMED);
+        }
+
+        // ③+(commitTransfer 内部):券实例转移 + transfer 记录 + 通知接收人 + 审计流水
+        Long transferId = couponGiftService.commitTransfer(
+                share.getGiverUserId(), share.getGiverFamilyId(),
+                claimUserId, claimFamilyId,
+                share.getCouponId(), share.getFamilyCouponId(),
+                SHARE_GIFT_LEVEL, CLAIM_METHOD_SHARE, shareToken, null);
+
+        // ④ 通知赠送人(失败不影响领取主流程)
+        try {
+            String claimNickname = StringUtils.hasText(claimUser.getNickname())
+                    ? claimUser.getNickname() : "微信用户";
+            Map<String, Object> vars = NotificationDispatchService.vars("claimNickname", claimNickname);
+            vars.put("couponName", coupon.getName());
+            notificationDispatchService.sendByTemplate(
+                    "coupon_gift",
+                    share.getGiverUserId(),
+                    vars,
+                    "coupon_gift",
+                    share.getId(),
+                    "你的分享券已被领取",
+                    "{claimNickname} 领取了你分享的「{couponName}」会员券。");
+        } catch (Exception e) {
+            logger.warn("分享领取通知发送失败(不影响领取): shareId={}, error={}", share.getId(), e.getMessage());
+        }
+
+        // ⑤ 分享链路审计流水(source=share:id,与定向 transfer:id 并行可对账,均 GIFT_TRANSFER)
+        FamilyCouponGrantLog log = new FamilyCouponGrantLog();
+        log.setFamilyId(claimFamilyId);
+        log.setCouponId(share.getCouponId());
+        log.setGrantType("GIFT_TRANSFER");
+        log.setPeriod(null);
+        log.setQuantity(1);
+        log.setSource("share:" + share.getId());
+        log.setCreatedAt(now);
+        familyCouponGrantLogMapper.insert(log);
+
+        logger.info("会员券分享领取成功: shareId={}, token={}, claimUser={}, transferId={}",
+                share.getId(), shareToken, claimUserId, transferId);
+        return transferId;
+    }
+
+    // ----------------------------------------------------------------
+    // revoke(PENDING 阶段可撤回,不动券实例)
+    // ----------------------------------------------------------------
+
+    /**
+     * 撤回一笔分享(仅 PENDING 可撤回;CLAIMED 终态不可撤回)。
+     * PENDING 阶段券仍在赠送人名下,仅置 status=REVOKED,不动券实例。
+     */
+    public void revoke(Long giverUserId, String shareToken) {
+        if (giverUserId == null || !StringUtils.hasText(shareToken)) {
+            throw new IllegalArgumentException(MSG_PARAM_INCOMPLETE);
+        }
+        CouponShare share = findShare(shareToken);
+        if (share == null) {
+            throw new IllegalArgumentException(MSG_SHARE_NOT_EXIST);
+        }
+        if (!Objects.equals(share.getGiverUserId(), giverUserId)) {
+            throw new IllegalArgumentException(MSG_NO_PERMISSION);
+        }
+        if (STATUS_CLAIMED.equals(share.getStatus())) {
+            throw new IllegalArgumentException(MSG_CLAIMED_CANNOT_REVOKE);
+        }
+        if (STATUS_REVOKED.equals(share.getStatus())) {
+            throw new IllegalArgumentException(MSG_ALREADY_REVOKED);
+        }
+        // PENDING(含已过期未领)→ REVOKED;条件更新兜底并发领取竞态(0 行=已被领走/状态已变)
+        CouponShare update = new CouponShare();
+        update.setStatus(STATUS_REVOKED);
+        int updated = couponShareMapper.update(update, new LambdaUpdateWrapper<CouponShare>()
+                .eq(CouponShare::getShareToken, shareToken)
+                .eq(CouponShare::getStatus, STATUS_PENDING));
+        if (updated != 1) {
+            throw new IllegalArgumentException(MSG_ALREADY_REVOKED);
+        }
+        logger.info("会员券分享撤回成功: token={}, giver={}", shareToken, giverUserId);
+    }
+
+    // ----------------------------------------------------------------
+    // list(我的分享记录,created_at DESC)
+    // ----------------------------------------------------------------
+
+    /**
+     * 我的分享记录列表(created_at DESC)。
+     *
+     * @return [{shareToken, couponName, couponValue, status, expireAt, claimTime, createdAt, claimNickname}]
+     */
+    public List<Map<String, Object>> list(Long giverUserId) {
+        if (giverUserId == null) return new ArrayList<>();
+        List<CouponShare> shares = couponShareMapper.selectList(
+                new LambdaQueryWrapper<CouponShare>()
+                        .eq(CouponShare::getGiverUserId, giverUserId)
+                        .orderByDesc(CouponShare::getCreatedAt));
+        if (shares.isEmpty()) return new ArrayList<>();
+        Date now = new Date();
+        List<Map<String, Object>> result = new ArrayList<>();
+        for (CouponShare s : shares) {
+            Coupon coupon = couponMapper.selectById(s.getCouponId());
+            User claimUser = s.getClaimUserId() != null ? userMapper.selectById(s.getClaimUserId()) : null;
+            Map<String, Object> m = new HashMap<>();
+            m.put("shareToken", s.getShareToken());
+            m.put("couponName", coupon != null ? coupon.getName() : "优惠券");
+            m.put("couponValue", coupon != null ? coupon.getValue() : null);
+            m.put("status", resolveDisplayStatus(s, now));
+            m.put("expireAt", s.getExpireAt());
+            m.put("claimTime", s.getClaimTime());
+            m.put("createdAt", s.getCreatedAt());
+            m.put("claimNickname", claimUser != null && StringUtils.hasText(claimUser.getNickname())
+                    ? claimUser.getNickname() : null);
+            result.add(m);
+        }
+        return result;
+    }
+
+    // ----------------------------------------------------------------
+    // 内部辅助
+    // ----------------------------------------------------------------
+
+    private Long getFamilyId(Long userId) {
+        User user = userMapper.selectById(userId);
+        if (user == null || user.getFamilyId() == null) return null;
+        return user.getFamilyId();
+    }
+
+    private CouponShare findShare(String shareToken) {
+        return couponShareMapper.selectOne(new LambdaQueryWrapper<CouponShare>()
+                .eq(CouponShare::getShareToken, shareToken)
+                .last("LIMIT 1"));
+    }
+
+    /** 生成全局唯一分享令牌:CS- + UUID 片段(≤64 字符,uk_share_token 全局唯一兜底) */
+    private String generateShareToken() {
+        return "CS-" + UUID.randomUUID().toString().replace("-", "").substring(0, 12).toUpperCase();
+    }
+
+    private Map<String, Object> buildCreateResult(CouponShare share) {
+        Map<String, Object> data = new HashMap<>();
+        data.put("shareToken", share.getShareToken());
+        data.put("sharePath", SHARE_PATH_PREFIX + share.getShareToken());
+        data.put("expireAt", share.getExpireAt());
+        return data;
+    }
+
+    /** 懒判定 EXPIRED:PENDING 但已过 expireAt 时对外展示 EXPIRED(DB 行保持 PENDING,detail/claim 判定) */
+    private String resolveDisplayStatus(CouponShare share, Date now) {
+        if (STATUS_PENDING.equals(share.getStatus())
+                && (share.getExpireAt() == null || now.after(share.getExpireAt()))) {
+            return STATUS_EXPIRED;
+        }
+        return share.getStatus();
+    }
+}

+ 12 - 0
cfc-backend/src/main/java/com/etotem/cfc/util/ParamUtils.java

@@ -49,6 +49,18 @@ public final class ParamUtils {
         return parsed != null ? parsed : defaultVal;
     }
 
+    /**
+     * 安全解析 String:null / 空字符串 / 空白 => null(视为"未传")。
+     * 其余情况返回 {@code value.toString().trim()}(去除首尾空白,统一为 null 或干净字符串)。
+     */
+    public static String getString(Object value) {
+        if (value == null) {
+            return null;
+        }
+        String s = value.toString().trim();
+        return s.isEmpty() ? null : s;
+    }
+
     /**
      * 安全解析 Boolean:null / 空字符串 / 空白 => null(视为"未传")。
      * 支持 true/false、1/0、yes/no、on/off(忽略大小写);其余值 => null。

+ 592 - 0
cfc-backend/src/test/java/com/etotem/cfc/unit/CouponShareClaimContractTest.java

@@ -0,0 +1,592 @@
+package com.etotem.cfc.unit;
+
+import com.baomidou.mybatisplus.core.MybatisConfiguration;
+import com.baomidou.mybatisplus.core.conditions.Wrapper;
+import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
+import com.etotem.cfc.entity.Coupon;
+import com.etotem.cfc.entity.CouponGiftTransfer;
+import com.etotem.cfc.entity.CouponShare;
+import com.etotem.cfc.entity.FamilyCoupon;
+import com.etotem.cfc.entity.FamilyCouponGrantLog;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.CouponMapper;
+import com.etotem.cfc.mapper.CouponShareMapper;
+import com.etotem.cfc.mapper.FamilyCouponGrantLogMapper;
+import com.etotem.cfc.mapper.FamilyCouponMapper;
+import com.etotem.cfc.mapper.UserMapper;
+import com.etotem.cfc.service.CouponGiftService;
+import com.etotem.cfc.service.CouponShareService;
+import com.etotem.cfc.service.NotificationDispatchService;
+import org.apache.ibatis.builder.MapperBuilderAssistant;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+
+import java.lang.reflect.Field;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.ArgumentMatchers.anyMap;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.ArgumentMatchers.isNull;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/**
+ * 契约级单测:会员券「分享转赠」后端(ARCH-CFC-COUPON-SHARE-GIFT-001 §10.1 十场景)。
+ *
+ * <p>契约溯源:{@code docs/superpowers/api/API_REFERENCE.md} 会员券分享转赠
+ * {@code /api/coupon/gift/share/*}(§5 create/detail/claim/revoke/list);
+ * 实现承载:{@link CouponShareService}(create 幂等 + claim 条件更新防重领 + 复用
+ * {@link CouponGiftService#commitTransfer})。纯 Mockito 无 Spring 上下文 / 无 DB /
+ * 无外部服务,风格参考 {@code ShopCouponClaimContractTest}。</p>
+ *
+ * <p><b>覆盖流</b>:</p>
+ * <ul>
+ *   <li><b>create</b>:正常(token/path/expireAt,insert 1 行 PENDING,expireAt=now+7 天);
+ *       幂等(已有 PENDING → 返回既有 token 不新增);校验(券不属我 / 非 MEMBERSHIP /
+ *       非 ACTIVE / 已过期 → 对应文案);</li>
+ *   <li><b>detail</b>:正常(PENDING → 券信息 + claimable=true,匿名可调);失效态
+ *       (CLAIMED/REVOKED/EXPIRED 懒判定 / token 不存在 → claimable=false + 对应状态);</li>
+ *   <li><b>claim</b>:成功(条件更新 1 行 → commitTransfer 委托参数 giftLevel=0/claimMethod=SHARE/
+ *       shareToken 回写,通知赠送人与 grant log 各 1 次);并发防重领(条件更新 0 行 →
+ *       「该分享已被领取」,transfer 不重复写);校验(自己分享/同家庭/已撤回/已过期/
+ *       券失效/领取人无家庭 → 各自文案);</li>
+ *   <li><b>revoke</b>:PENDING→REVOKED(不动券实例);CLAIMED 终态不可撤回;非赠送人无权;</li>
+ *   <li><b>list</b>:仅本人记录,created_at 倒序。</li>
+ * </ul>
+ */
+class CouponShareClaimContractTest {
+
+    private static final String TOKEN = "CS-CONTRACT001";
+    private static final String AVATAR = "http://avatar/";
+
+    /** 纯 Mockito 无 Spring:为 Lambda 包装器预注册 TableInfo(否则 set()/getSqlSegment() 报 lambda cache 异常) */
+    @BeforeAll
+    static void initMpTableInfo() {
+        MapperBuilderAssistant assistant = new MapperBuilderAssistant(new MybatisConfiguration(), "");
+        TableInfoHelper.initTableInfo(assistant, CouponShare.class);
+        TableInfoHelper.initTableInfo(assistant, Coupon.class);
+        TableInfoHelper.initTableInfo(assistant, CouponGiftTransfer.class);
+        TableInfoHelper.initTableInfo(assistant, FamilyCoupon.class);
+        TableInfoHelper.initTableInfo(assistant, FamilyCouponGrantLog.class);
+        TableInfoHelper.initTableInfo(assistant, User.class);
+    }
+
+    private CouponShareService service;
+    private CouponShareMapper couponShareMapper;
+    private FamilyCouponMapper familyCouponMapper;
+    private CouponMapper couponMapper;
+    private UserMapper userMapper;
+    private CouponGiftService couponGiftService;
+    private NotificationDispatchService notificationDispatchService;
+    private FamilyCouponGrantLogMapper familyCouponGrantLogMapper;
+
+    @BeforeEach
+    void setUp() throws Exception {
+        service = new CouponShareService();
+        couponShareMapper = mock(CouponShareMapper.class);
+        familyCouponMapper = mock(FamilyCouponMapper.class);
+        couponMapper = mock(CouponMapper.class);
+        userMapper = mock(UserMapper.class);
+        couponGiftService = mock(CouponGiftService.class);
+        notificationDispatchService = mock(NotificationDispatchService.class);
+        familyCouponGrantLogMapper = mock(FamilyCouponGrantLogMapper.class);
+
+        inject(service, "couponShareMapper", couponShareMapper);
+        inject(service, "familyCouponMapper", familyCouponMapper);
+        inject(service, "couponMapper", couponMapper);
+        inject(service, "userMapper", userMapper);
+        inject(service, "couponGiftService", couponGiftService);
+        inject(service, "notificationDispatchService", notificationDispatchService);
+        inject(service, "familyCouponGrantLogMapper", familyCouponGrantLogMapper);
+    }
+
+    private static void inject(Object target, String field, Object value) throws Exception {
+        Field f = target.getClass().getDeclaredField(field);
+        f.setAccessible(true);
+        f.set(target, value);
+    }
+
+    // ==================== 桩数据 ====================
+
+    /** 用户:id=1 赠送人(家庭5)/ 其他 id 领取人(familyId 可指定) */
+    private User user(Long id, Long familyId) {
+        User u = new User();
+        u.setId(id);
+        u.setFamilyId(familyId);
+        u.setNickname(id == 1L ? "赠送人" : "领取人" + id);
+        u.setAvatar(AVATAR + id);
+        return u;
+    }
+
+    /** 有效期内、ACTIVE、MEMBERSHIP 的会员券模板 */
+    private Coupon membershipCoupon() {
+        Coupon c = new Coupon();
+        c.setId(100L);
+        c.setName("会员升级券");
+        c.setType("CASH");
+        c.setStatus("ACTIVE");
+        c.setApplicableTo("MEMBERSHIP");
+        c.setValue(2000);
+        c.setMinSpend(0);
+        c.setValidFrom(new Date(System.currentTimeMillis() - 86400000L * 7));
+        c.setValidUntil(new Date(System.currentTimeMillis() + 86400000L * 30));
+        return c;
+    }
+
+    private FamilyCoupon familyCoupon(Long id, Long familyId, Long couponId) {
+        FamilyCoupon fc = new FamilyCoupon();
+        fc.setId(id);
+        fc.setFamilyId(familyId);
+        fc.setCouponId(couponId);
+        fc.setStatus("AVAILABLE");
+        fc.setIsGift(0);
+        return fc;
+    }
+
+    /** 分享行:赠送人=1(家庭5),familyCoupon=500,coupon=100,expireAt=7 天后 */
+    private CouponShare pendingShare(String token) {
+        CouponShare s = new CouponShare();
+        s.setId(10L);
+        s.setShareToken(token);
+        s.setGiverUserId(1L);
+        s.setGiverFamilyId(5L);
+        s.setFamilyCouponId(500L);
+        s.setCouponId(100L);
+        s.setStatus("PENDING");
+        s.setExpireAt(new Date(System.currentTimeMillis() + 86400000L * 7));
+        s.setCreatedAt(new Date());
+        return s;
+    }
+
+    private String createError(Long giverUserId, Long familyCouponId) {
+        try {
+            service.create(giverUserId, familyCouponId);
+            return null;
+        } catch (IllegalArgumentException e) {
+            return e.getMessage();
+        }
+    }
+
+    private String detailError(String token) {
+        try {
+            service.detail(token, null);
+            return null;
+        } catch (IllegalArgumentException e) {
+            return e.getMessage();
+        }
+    }
+
+    private String claimError(Long userId, String token) {
+        try {
+            service.claim(userId, token);
+            return null;
+        } catch (IllegalArgumentException e) {
+            return e.getMessage();
+        }
+    }
+
+    private String revokeError(Long userId, String token) {
+        try {
+            service.revoke(userId, token);
+            return null;
+        } catch (IllegalArgumentException e) {
+            return e.getMessage();
+        }
+    }
+
+    // ==================== 场景1-3:create ====================
+
+    @Test
+    @DisplayName("create正常:返回 token/sharePath/expireAt,insert 1 行 PENDING,expireAt=now+7天")
+    void create_正常() {
+        when(userMapper.selectById(1L)).thenReturn(user(1L, 5L));
+        when(couponShareMapper.selectOne(any(Wrapper.class))).thenReturn(null);
+        when(familyCouponMapper.selectById(500L)).thenReturn(familyCoupon(500L, 5L, 100L));
+        when(couponMapper.selectById(100L)).thenReturn(membershipCoupon());
+        when(couponShareMapper.insert(any(CouponShare.class))).thenAnswer(inv -> {
+            CouponShare s = inv.getArgument(0);
+            s.setId(10L);
+            return 1;
+        });
+
+        Map<String, Object> data = service.create(1L, 500L);
+
+        String token = (String) data.get("shareToken");
+        assertNotNull(token, "应生成 shareToken");
+        assertTrue(((String) data.get("sharePath")).startsWith("/pages/coupon/share-claim?shareToken="),
+                "sharePath 应指向落地领取页并携带 token");
+        assertNotNull(data.get("expireAt"), "应返回失效时间");
+
+        ArgumentCaptor<CouponShare> captor = ArgumentCaptor.forClass(CouponShare.class);
+        verify(couponShareMapper).insert(captor.capture());
+        CouponShare inserted = captor.getValue();
+        assertEquals("PENDING", inserted.getStatus(), "新分享行状态应为 PENDING");
+        assertEquals(Long.valueOf(1L), inserted.getGiverUserId());
+        assertEquals(Long.valueOf(5L), inserted.getGiverFamilyId());
+        assertEquals(Long.valueOf(500L), inserted.getFamilyCouponId());
+        assertEquals(Long.valueOf(100L), inserted.getCouponId());
+        long diff = inserted.getExpireAt().getTime() - System.currentTimeMillis();
+        long expected = CouponShareService.DEFAULT_EXPIRE_DAYS * 86400000L;
+        assertTrue(diff > expected - 60000L && diff < expected + 60000L, "expireAt 应为 now + 7 天");
+    }
+
+    @Test
+    @DisplayName("create幂等:同 giver+familyCouponId 已有 PENDING → 返回既有 token,不新增行")
+    void create_幂等() {
+        when(userMapper.selectById(1L)).thenReturn(user(1L, 5L));
+        CouponShare existing = pendingShare("CS-EXISTING001");
+        when(couponShareMapper.selectOne(any(Wrapper.class))).thenReturn(existing);
+
+        Map<String, Object> data = service.create(1L, 500L);
+
+        assertEquals("CS-EXISTING001", data.get("shareToken"), "幂等命中应返回既有 token");
+        verify(couponShareMapper, never()).insert(any(CouponShare.class));
+        verify(familyCouponMapper, never()).selectById(anyLong());
+    }
+
+    @Test
+    @DisplayName("create校验-1:券不属于我(familyId 不符)→ 该优惠券不可用或不属于你")
+    void create_校验_券不属于我() {
+        when(userMapper.selectById(1L)).thenReturn(user(1L, 5L));
+        when(couponShareMapper.selectOne(any(Wrapper.class))).thenReturn(null);
+        when(familyCouponMapper.selectById(500L)).thenReturn(familyCoupon(500L, 99L, 100L));
+
+        assertEquals(CouponShareService.MSG_COUPON_UNAVAILABLE, createError(1L, 500L));
+        verify(couponShareMapper, never()).insert(any(CouponShare.class));
+    }
+
+    @Test
+    @DisplayName("create校验-2:非 MEMBERSHIP → 仅会员专属券可分享")
+    void create_校验_非会员券() {
+        when(userMapper.selectById(1L)).thenReturn(user(1L, 5L));
+        when(couponShareMapper.selectOne(any(Wrapper.class))).thenReturn(null);
+        when(familyCouponMapper.selectById(500L)).thenReturn(familyCoupon(500L, 5L, 100L));
+        Coupon coupon = membershipCoupon();
+        coupon.setApplicableTo("ALL");
+        when(couponMapper.selectById(100L)).thenReturn(coupon);
+
+        assertEquals(CouponShareService.MSG_ONLY_MEMBERSHIP, createError(1L, 500L));
+        verify(couponShareMapper, never()).insert(any(CouponShare.class));
+    }
+
+    @Test
+    @DisplayName("create校验-3:非 ACTIVE → 优惠券已失效")
+    void create_校验_券已失效() {
+        when(userMapper.selectById(1L)).thenReturn(user(1L, 5L));
+        when(couponShareMapper.selectOne(any(Wrapper.class))).thenReturn(null);
+        when(familyCouponMapper.selectById(500L)).thenReturn(familyCoupon(500L, 5L, 100L));
+        Coupon coupon = membershipCoupon();
+        coupon.setStatus("DISABLED");
+        when(couponMapper.selectById(100L)).thenReturn(coupon);
+
+        assertEquals(CouponShareService.MSG_COUPON_INVALID, createError(1L, 500L));
+        verify(couponShareMapper, never()).insert(any(CouponShare.class));
+    }
+
+    @Test
+    @DisplayName("create校验-4:已过券有效期 → 优惠券已过期")
+    void create_校验_券已过期() {
+        when(userMapper.selectById(1L)).thenReturn(user(1L, 5L));
+        when(couponShareMapper.selectOne(any(Wrapper.class))).thenReturn(null);
+        when(familyCouponMapper.selectById(500L)).thenReturn(familyCoupon(500L, 5L, 100L));
+        Coupon coupon = membershipCoupon();
+        coupon.setValidUntil(new Date(System.currentTimeMillis() - 86400000L));
+        when(couponMapper.selectById(100L)).thenReturn(coupon);
+
+        assertEquals(CouponShareService.MSG_COUPON_EXPIRED, createError(1L, 500L));
+        verify(couponShareMapper, never()).insert(any(CouponShare.class));
+    }
+
+    // ==================== 场景4-5:detail ====================
+
+    @Test
+    @DisplayName("detail正常:PENDING → 返回券信息 + claimable=true(匿名可调 viewerUserId=null)")
+    void detail_正常() {
+        CouponShare s = pendingShare(TOKEN);
+        when(couponShareMapper.selectOne(any(Wrapper.class))).thenReturn(s);
+        when(couponMapper.selectById(100L)).thenReturn(membershipCoupon());
+        when(userMapper.selectById(1L)).thenReturn(user(1L, 5L));
+
+        Map<String, Object> d = service.detail(TOKEN, null);
+
+        assertEquals(TOKEN, d.get("shareToken"));
+        assertEquals("PENDING", d.get("status"));
+        assertEquals(Boolean.TRUE, d.get("claimable"), "PENDING 且未过期且券可用 → 可领取");
+        assertEquals("会员升级券", d.get("couponName"));
+        assertEquals(Integer.valueOf(2000), d.get("couponValue"));
+        assertEquals("CASH", d.get("couponType"));
+        assertEquals(Integer.valueOf(0), d.get("minSpend"));
+        assertEquals("赠送人", d.get("giverNickname"));
+        assertEquals(AVATAR + "1", d.get("giverAvatar"));
+        assertNotNull(d.get("validUntil"));
+        assertNotNull(d.get("expireAt"));
+    }
+
+    @Test
+    @DisplayName("detail失效态-1:CLAIMED → claimable=false,status=CLAIMED")
+    void detail_失效态_已领取() {
+        CouponShare s = pendingShare(TOKEN);
+        s.setStatus("CLAIMED");
+        when(couponShareMapper.selectOne(any(Wrapper.class))).thenReturn(s);
+        when(couponMapper.selectById(100L)).thenReturn(membershipCoupon());
+        when(userMapper.selectById(1L)).thenReturn(user(1L, 5L));
+
+        Map<String, Object> d = service.detail(TOKEN, null);
+        assertEquals("CLAIMED", d.get("status"));
+        assertEquals(Boolean.FALSE, d.get("claimable"));
+    }
+
+    @Test
+    @DisplayName("detail失效态-2:REVOKED → claimable=false,status=REVOKED")
+    void detail_失效态_已撤回() {
+        CouponShare s = pendingShare(TOKEN);
+        s.setStatus("REVOKED");
+        when(couponShareMapper.selectOne(any(Wrapper.class))).thenReturn(s);
+        when(couponMapper.selectById(100L)).thenReturn(membershipCoupon());
+        when(userMapper.selectById(1L)).thenReturn(user(1L, 5L));
+
+        Map<String, Object> d = service.detail(TOKEN, null);
+        assertEquals("REVOKED", d.get("status"));
+        assertEquals(Boolean.FALSE, d.get("claimable"));
+    }
+
+    @Test
+    @DisplayName("detail失效态-3:PENDING 但已过 expireAt → 懒判定 EXPIRED,claimable=false")
+    void detail_失效态_过期懒判定() {
+        CouponShare s = pendingShare(TOKEN);
+        s.setExpireAt(new Date(System.currentTimeMillis() - 60000L)); // 1 分钟前过期
+        when(couponShareMapper.selectOne(any(Wrapper.class))).thenReturn(s);
+        when(couponMapper.selectById(100L)).thenReturn(membershipCoupon());
+        when(userMapper.selectById(1L)).thenReturn(user(1L, 5L));
+
+        Map<String, Object> d = service.detail(TOKEN, null);
+        assertEquals("EXPIRED", d.get("status"), "PENDING 且过期 → 展示 EXPIRED(懒判定)");
+        assertEquals(Boolean.FALSE, d.get("claimable"));
+    }
+
+    @Test
+    @DisplayName("detail失效态-4:token 无记录 → 分享不存在或已失效")
+    void detail_失效态_不存在() {
+        when(couponShareMapper.selectOne(any(Wrapper.class))).thenReturn(null);
+        assertEquals(CouponShareService.MSG_SHARE_NOT_FOUND, detailError("CS-NOT-FOUND"));
+    }
+
+    // ==================== 场景6-8:claim ====================
+
+    /** claim 成功前置:分享可领取(赠送人1/家庭5,领取人2/家庭6,券在赠送人名下且可用) */
+    private void stubClaimable() {
+        when(couponShareMapper.selectOne(any(Wrapper.class))).thenReturn(pendingShare(TOKEN));
+        when(userMapper.selectById(2L)).thenReturn(user(2L, 6L));
+        when(couponMapper.selectById(100L)).thenReturn(membershipCoupon());
+        when(familyCouponMapper.selectById(500L)).thenReturn(familyCoupon(500L, 5L, 100L));
+    }
+
+    @Test
+    @DisplayName("claim成功:条件更新 1 行 → 委托 commitTransfer(giftLevel=0,SHARE,token) + 通知赠送人 + grant log 各 1 次")
+    void claim_成功() {
+        stubClaimable();
+        when(couponShareMapper.update(isNull(), any(Wrapper.class))).thenReturn(1);
+        when(couponGiftService.commitTransfer(1L, 5L, 2L, 6L, 100L, 500L,
+                CouponShareService.SHARE_GIFT_LEVEL, "SHARE", TOKEN, null)).thenReturn(300L);
+
+        Long transferId = service.claim(2L, TOKEN);
+
+        assertEquals(Long.valueOf(300L), transferId, "应返回 commitTransfer 生成的 transferId");
+        // 条件更新恰好执行 1 次(防重领原子门)
+        verify(couponShareMapper).update(isNull(), any(Wrapper.class));
+        // 委托参数:giftLevel=0、claimMethod=SHARE、shareToken 回写、receiver=领取人家庭
+        verify(couponGiftService).commitTransfer(1L, 5L, 2L, 6L, 100L, 500L,
+                CouponShareService.SHARE_GIFT_LEVEL, "SHARE", TOKEN, null);
+        // 通知赠送人 1 次(模板 coupon_gift,目标 share.giverUserId=1)
+        verify(notificationDispatchService, times(1)).sendByTemplate(anyString(), eq(1L),
+                anyMap(), anyString(), anyLong(), anyString(), anyString());
+        // grant log 1 次(GIFT_TRANSFER, source=share:shareId)
+        ArgumentCaptor<FamilyCouponGrantLog> logCaptor = ArgumentCaptor.forClass(FamilyCouponGrantLog.class);
+        verify(familyCouponGrantLogMapper).insert(logCaptor.capture());
+        assertEquals("GIFT_TRANSFER", logCaptor.getValue().getGrantType());
+        assertEquals("share:10", logCaptor.getValue().getSource(), "分享链路审计 source=share:shareId");
+        assertEquals(Long.valueOf(6L), logCaptor.getValue().getFamilyId(), "流水落接收方家庭");
+        assertEquals(Long.valueOf(100L), logCaptor.getValue().getCouponId());
+    }
+
+    @Test
+    @DisplayName("claim并发防重领:条件更新影响 0 行(第二次/已被领走)→ 该分享已被领取,不重复写 transfer")
+    void claim_并发防重领() {
+        stubClaimable();
+        when(couponShareMapper.update(isNull(), any(Wrapper.class))).thenReturn(0); // 并发第二个请求
+
+        assertEquals(CouponShareService.MSG_ALREADY_CLAIMED, claimError(2L, TOKEN));
+        verify(couponGiftService, never()).commitTransfer(any(), any(), any(), any(),
+                any(), any(), any(), any(), any(), any());
+        verify(familyCouponGrantLogMapper, never()).insert(any(FamilyCouponGrantLog.class));
+        verify(notificationDispatchService, never()).sendByTemplate(anyString(), anyLong(),
+                anyMap(), anyString(), anyLong(), anyString(), anyString());
+    }
+
+    @Test
+    @DisplayName("claim校验-1:领取人=赠送人 → 不能领取自己分享的券")
+    void claim_校验_自己分享() {
+        CouponShare s = pendingShare(TOKEN);
+        when(couponShareMapper.selectOne(any(Wrapper.class))).thenReturn(s);
+        when(userMapper.selectById(1L)).thenReturn(user(1L, 5L));
+
+        assertEquals(CouponShareService.MSG_SELF_CLAIM, claimError(1L, TOKEN));
+        verify(couponShareMapper, never()).update(isNull(), any(Wrapper.class));
+    }
+
+    @Test
+    @DisplayName("claim校验-2:同家庭(领取人家庭=赠送人家庭)→ 不能领取同家庭成员的券")
+    void claim_校验_同家庭() {
+        CouponShare s = pendingShare(TOKEN);
+        when(couponShareMapper.selectOne(any(Wrapper.class))).thenReturn(s);
+        when(userMapper.selectById(2L)).thenReturn(user(2L, 5L)); // 与赠送人同家庭
+
+        assertEquals(CouponShareService.MSG_SAME_FAMILY, claimError(2L, TOKEN));
+        verify(couponShareMapper, never()).update(isNull(), any(Wrapper.class));
+    }
+
+    @Test
+    @DisplayName("claim校验-3:已撤回 → 该分享已撤回")
+    void claim_校验_已撤回() {
+        CouponShare s = pendingShare(TOKEN);
+        s.setStatus("REVOKED");
+        when(couponShareMapper.selectOne(any(Wrapper.class))).thenReturn(s);
+        when(userMapper.selectById(2L)).thenReturn(user(2L, 6L));
+
+        assertEquals(CouponShareService.MSG_ALREADY_REVOKED, claimError(2L, TOKEN));
+        verify(couponShareMapper, never()).update(isNull(), any(Wrapper.class));
+    }
+
+    @Test
+    @DisplayName("claim校验-4:已过期(PENDING 且过 expireAt)→ 该分享已过期")
+    void claim_校验_已过期() {
+        CouponShare s = pendingShare(TOKEN);
+        s.setExpireAt(new Date(System.currentTimeMillis() - 60000L));
+        when(couponShareMapper.selectOne(any(Wrapper.class))).thenReturn(s);
+        when(userMapper.selectById(2L)).thenReturn(user(2L, 6L));
+
+        assertEquals(CouponShareService.MSG_SHARE_EXPIRED, claimError(2L, TOKEN));
+        verify(couponShareMapper, never()).update(isNull(), any(Wrapper.class));
+    }
+
+    @Test
+    @DisplayName("claim校验-5:券模板失效 → 优惠券已失效")
+    void claim_校验_券失效() {
+        stubClaimable();
+        Coupon coupon = membershipCoupon();
+        coupon.setStatus("DISABLED");
+        when(couponMapper.selectById(100L)).thenReturn(coupon);
+
+        assertEquals(CouponShareService.MSG_COUPON_INVALID, claimError(2L, TOKEN));
+        verify(couponShareMapper, never()).update(isNull(), any(Wrapper.class));
+    }
+
+    @Test
+    @DisplayName("claim校验-6:领取人无家庭(familyId 空)→ 领取失败,请联系客服")
+    void claim_校验_无家庭() {
+        CouponShare s = pendingShare(TOKEN);
+        when(couponShareMapper.selectOne(any(Wrapper.class))).thenReturn(s);
+        when(userMapper.selectById(2L)).thenReturn(user(2L, null)); // 理论兜底:登录用户必有家庭
+
+        assertEquals(CouponShareService.MSG_CLAIM_FAILED, claimError(2L, TOKEN));
+        verify(couponShareMapper, never()).update(isNull(), any(Wrapper.class));
+    }
+
+    // ==================== 场景9:revoke ====================
+
+    @Test
+    @DisplayName("revoke:PENDING → REVOKED(条件更新 1 行),不动券实例")
+    void revoke_正常() {
+        when(couponShareMapper.selectOne(any(Wrapper.class))).thenReturn(pendingShare(TOKEN));
+        when(couponShareMapper.update(any(CouponShare.class), any(Wrapper.class))).thenReturn(1);
+
+        service.revoke(1L, TOKEN);
+
+        ArgumentCaptor<CouponShare> captor = ArgumentCaptor.forClass(CouponShare.class);
+        verify(couponShareMapper).update(captor.capture(), any(Wrapper.class));
+        assertEquals("REVOKED", captor.getValue().getStatus(), "仅置 status=REVOKED");
+        verify(familyCouponMapper, never()).updateById(any(FamilyCoupon.class));
+    }
+
+    @Test
+    @DisplayName("revoke:CLAIMED 终态 → 该分享已被领取,无法撤回")
+    void revoke_已领取不可撤回() {
+        CouponShare s = pendingShare(TOKEN);
+        s.setStatus("CLAIMED");
+        when(couponShareMapper.selectOne(any(Wrapper.class))).thenReturn(s);
+
+        assertEquals(CouponShareService.MSG_CLAIMED_CANNOT_REVOKE, revokeError(1L, TOKEN));
+        verify(couponShareMapper, never()).update(any(CouponShare.class), any(Wrapper.class));
+    }
+
+    @Test
+    @DisplayName("revoke:非赠送人 → 无权操作该分享")
+    void revoke_非赠送人() {
+        when(couponShareMapper.selectOne(any(Wrapper.class))).thenReturn(pendingShare(TOKEN));
+
+        assertEquals(CouponShareService.MSG_NO_PERMISSION, revokeError(2L, TOKEN));
+        verify(couponShareMapper, never()).update(any(CouponShare.class), any(Wrapper.class));
+    }
+
+    @Test
+    @DisplayName("revoke:已 REVOKED → 该分享已撤回(幂等兜底)")
+    void revoke_已撤回() {
+        CouponShare s = pendingShare(TOKEN);
+        s.setStatus("REVOKED");
+        when(couponShareMapper.selectOne(any(Wrapper.class))).thenReturn(s);
+
+        assertEquals(CouponShareService.MSG_ALREADY_REVOKED, revokeError(1L, TOKEN));
+        verify(couponShareMapper, never()).update(any(CouponShare.class), any(Wrapper.class));
+    }
+
+    // ==================== 场景10:list ====================
+
+    @Test
+    @DisplayName("list:仅返回本人分享记录,created_at 倒序,含领取人昵称")
+    void list_倒序() {
+        CouponShare newer = pendingShare("CS-LIST-A"); // 10s 前
+        newer.setCreatedAt(new Date(System.currentTimeMillis() - 10000L));
+        CouponShare older = pendingShare("CS-LIST-B"); // 60s 前
+        older.setCreatedAt(new Date(System.currentTimeMillis() - 60000L));
+        older.setClaimUserId(2L);
+        when(couponShareMapper.selectList(any(Wrapper.class))).thenReturn(Arrays.asList(newer, older));
+        when(couponMapper.selectById(100L)).thenReturn(membershipCoupon());
+        when(userMapper.selectById(2L)).thenReturn(user(2L, 6L));
+
+        List<Map<String, Object>> list = service.list(1L);
+
+        assertEquals(2, list.size());
+        assertEquals("CS-LIST-A", list.get(0).get("shareToken"), "列表应按 created_at 倒序");
+        assertEquals("CS-LIST-B", list.get(1).get("shareToken"));
+        assertEquals("会员升级券", list.get(0).get("couponName"));
+        assertEquals(Integer.valueOf(2000), list.get(0).get("couponValue"));
+        assertNotNull(list.get(0).get("expireAt"));
+        assertNotNull(list.get(0).get("createdAt"));
+        assertNull(list.get(0).get("claimNickname"), "未领取行 claimNickname 为 null");
+        assertEquals("领取人2", list.get(1).get("claimNickname"));
+
+        // 查询条件:giver_user_id=本人 + orderByDesc(createdAt)
+        ArgumentCaptor<Wrapper<CouponShare>> wrapperCaptor = ArgumentCaptor.forClass(Wrapper.class);
+        verify(couponShareMapper).selectList(wrapperCaptor.capture());
+        String sql = wrapperCaptor.getValue().getSqlSegment().toLowerCase();
+        assertTrue(sql.contains("giver_user_id"), "list 应按赠送人过滤");
+        assertTrue(sql.contains("desc"), "list 应按 created_at 倒序(ORDER BY ... DESC)");
+    }
+}