| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656 |
- package com.etotem.cfc.service;
- import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
- import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
- import com.etotem.cfc.entity.Coupon;
- 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.FamilyCouponGrantLogMapper;
- import com.etotem.cfc.mapper.FamilyCouponMapper;
- import com.etotem.cfc.mapper.UserMapper;
- import org.springframework.context.annotation.Lazy;
- import org.springframework.stereotype.Service;
- import org.springframework.transaction.annotation.Transactional;
- 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 org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import com.etotem.cfc.util.SortUtil;
- @Service
- public class CouponService {
- private static final Logger logger = LoggerFactory.getLogger(CouponService.class);
- @Resource
- private CouponMapper couponMapper;
- @Resource
- private FamilyCouponMapper familyCouponMapper;
- @Resource
- private FamilyCouponGrantLogMapper familyCouponGrantLogMapper;
- @Resource
- private UserMapper userMapper;
- @Resource
- @Lazy
- private MembershipService membershipService;
- // ----------------------------------------------------------------
- // 内部辅助方法
- // ----------------------------------------------------------------
- /** userId → familyId(用于查询当前用户所在家庭) */
- private Long getFamilyId(Long userId) {
- User user = userMapper.selectById(userId);
- if (user == null || user.getFamilyId() == null) {
- return null;
- }
- return user.getFamilyId();
- }
- /** 构建与 CouponService.listMyCoupons 相同格式的响应 Map */
- private Map<String, Object> toCouponVO(FamilyCoupon fc) {
- Coupon coupon = couponMapper.selectById(fc.getCouponId());
- if (coupon == null) return null;
- Date now = new Date();
- String status = fc.getStatus();
- if ("AVAILABLE".equals(status) && !"ACTIVE".equals(coupon.getStatus())) {
- status = "DISABLED";
- } else if ("AVAILABLE".equals(status) && coupon.getValidUntil() != null && now.after(coupon.getValidUntil())) {
- status = "EXPIRED";
- }
- Map<String, Object> item = new HashMap<>();
- // 对外字段名保持 userCouponId / id 等原有契约,前端不感知内部实现变化
- item.put("userCouponId", fc.getId());
- item.put("id", fc.getId());
- item.put("couponId", coupon.getId());
- item.put("name", coupon.getName());
- item.put("type", coupon.getType());
- item.put("value", coupon.getValue());
- item.put("discountRate", coupon.getDiscountRate());
- item.put("minSpend", coupon.getMinSpend());
- item.put("applicableTo", coupon.getApplicableTo());
- item.put("validFrom", coupon.getValidFrom());
- item.put("validUntil", coupon.getValidUntil());
- item.put("status", status);
- item.put("receivedAt", fc.getReceivedAt());
- item.put("usedAt", fc.getUsedAt());
- item.put("orderId", fc.getOrderId());
- item.put("productId", coupon.getProductId());
- return item;
- }
- // ----------------------------------------------------------------
- // 对外保留接口(签名不变,内部改为读 family_coupon)
- // ----------------------------------------------------------------
- public List<Map<String, Object>> listAvailable(Long userId) {
- Long familyId = getFamilyId(userId);
- if (familyId == null) return new ArrayList<>();
- List<FamilyCoupon> familyCoupons = familyCouponMapper.selectList(
- new LambdaQueryWrapper<FamilyCoupon>()
- .eq(FamilyCoupon::getFamilyId, familyId)
- .eq(FamilyCoupon::getStatus, "AVAILABLE")
- .orderByAsc(FamilyCoupon::getId));
- if (familyCoupons.isEmpty()) {
- return new ArrayList<>();
- }
- Date now = new Date();
- List<Map<String, Object>> result = new ArrayList<>();
- for (FamilyCoupon fc : familyCoupons) {
- Coupon coupon = couponMapper.selectById(fc.getCouponId());
- if (coupon == null) continue;
- if (!"ACTIVE".equals(coupon.getStatus())) continue;
- if (coupon.getValidFrom() != null && now.before(coupon.getValidFrom())) continue;
- if (coupon.getValidUntil() != null && now.after(coupon.getValidUntil())) continue;
- Map<String, Object> vo = toCouponVO(fc);
- if (vo != null) result.add(vo);
- }
- result.sort((a, b) -> Integer.compare(
- ((Number) a.getOrDefault("value", 0)).intValue(),
- ((Number) b.getOrDefault("value", 0)).intValue()));
- return result;
- }
- @Transactional
- public String claim(Long userId, Long couponId) {
- Long familyId = getFamilyId(userId);
- if (familyId == null) return "未加入家庭";
- Coupon coupon = couponMapper.selectById(couponId);
- if (coupon == null) {
- return "优惠券不存在";
- }
- if (!"ACTIVE".equals(coupon.getStatus())) {
- return "优惠券已停用";
- }
- if (coupon.getTotalCount() != null && coupon.getUsedCount() != null
- && coupon.getUsedCount() >= coupon.getTotalCount()) {
- return "优惠券已领完";
- }
- Date now = new Date();
- if (coupon.getValidFrom() != null && now.before(coupon.getValidFrom())) {
- return "优惠券尚未开始";
- }
- if (coupon.getValidUntil() != null && now.after(coupon.getValidUntil())) {
- return "优惠券已过期";
- }
- // 去重:同一个家庭同一张券只发一次(同 grantType 的幂等也通过 grant 方法保证)
- Long count = familyCouponMapper.selectCount(
- new LambdaQueryWrapper<FamilyCoupon>()
- .eq(FamilyCoupon::getFamilyId, familyId)
- .eq(FamilyCoupon::getCouponId, couponId));
- if (count != null && count > 0) {
- return "已领取过该优惠券";
- }
- issueToFamily(couponId, familyId);
- coupon.setUsedCount(coupon.getUsedCount() == null ? 1 : coupon.getUsedCount() + 1);
- couponMapper.updateById(coupon);
- return "领取成功";
- }
- /**
- * 判断用户是否为有效会员(FAMILY 或 PREMIUM 且未过期)
- */
- private boolean isMember(Long userId) {
- if (userId == null) return false;
- String level = membershipService.getMemberLevel(userId);
- return "FAMILY".equals(level) || "PREMIUM".equals(level);
- }
- public Integer apply(Long userId, Long userCouponId, String orderType, Integer orderAmount) {
- Long familyId = getFamilyId(userId);
- if (familyId == null) return null;
- FamilyCoupon fc = familyCouponMapper.selectById(userCouponId);
- if (fc == null || !fc.getFamilyId().equals(familyId) || !"AVAILABLE".equals(fc.getStatus())) {
- return null;
- }
- Coupon coupon = couponMapper.selectById(fc.getCouponId());
- if (coupon == null) {
- return null;
- }
- if (!"ACTIVE".equals(coupon.getStatus())) {
- return null;
- }
- Date now = new Date();
- if (coupon.getValidFrom() != null && now.before(coupon.getValidFrom())) {
- return null;
- }
- if (coupon.getValidUntil() != null && now.after(coupon.getValidUntil())) {
- return null;
- }
- if (!"ALL".equals(coupon.getApplicableTo()) && !coupon.getApplicableTo().equals(orderType)) {
- return null;
- }
- // 新增:会员专属券(applicableTo=MEMBERSHIP)仅允许会员使用
- // 例外:手动发放的券(grantType=MANUAL)允许非会员使用,用于赠送升级场景
- if ("MEMBERSHIP".equals(coupon.getApplicableTo())
- && !Objects.equals(coupon.getGrantType(), "MANUAL")
- && !isMember(userId)) {
- return null;
- }
- // 无门槛券(CASH)忽略起用门槛;满减/折扣券校验
- if (!"CASH".equals(coupon.getType()) && coupon.getMinSpend() != null && orderAmount < coupon.getMinSpend()) {
- return null;
- }
- // 返回抵扣金额(调用方以 originalAmount - discount 计算最终价)
- if ("DISCOUNT".equals(coupon.getType())) {
- int rate = coupon.getDiscountRate() != null ? coupon.getDiscountRate() : 9000;
- int discount = orderAmount * (10000 - rate) / 10000;
- return Math.max(discount, 0);
- }
- return Math.min(coupon.getValue(), orderAmount);
- }
- @Transactional
- public void markUsed(Long userCouponId, Long orderId) {
- FamilyCoupon fc = familyCouponMapper.selectById(userCouponId);
- if (fc != null) {
- fc.setStatus("USED");
- fc.setUsedAt(new Date());
- fc.setOrderId(orderId);
- familyCouponMapper.updateById(fc);
- }
- }
- @Transactional
- public void revert(Long userCouponId) {
- FamilyCoupon fc = familyCouponMapper.selectById(userCouponId);
- if (fc != null) {
- fc.setStatus("AVAILABLE");
- fc.setUsedAt(null);
- fc.setOrderId(null);
- familyCouponMapper.updateById(fc);
- }
- }
- /**
- * 下单时立即占用券实例(pending/timeout 期间拒绝其他订单使用),并关联订单号。
- * 支付成功后 {@link #markUsed} 改为 USED;取消/超时后 {@link #revert} 回到 AVAILABLE。
- */
- @Transactional
- public void reserve(Long userCouponId, Long orderId) {
- FamilyCoupon fc = familyCouponMapper.selectById(userCouponId);
- if (fc != null) {
- fc.setStatus("RESERVED");
- fc.setOrderId(orderId);
- familyCouponMapper.updateById(fc);
- }
- }
- public List<Coupon> listAll() {
- return couponMapper.selectList(null);
- }
- public List<Coupon> listAll(List<Map<String, String>> sortSpecs) {
- if (sortSpecs == null || sortSpecs.isEmpty()) {
- return listAll();
- }
- QueryWrapper<Coupon> wrapper = new QueryWrapper<>();
- SortUtil.applySort(wrapper, sortSpecs, null);
- return couponMapper.selectList(wrapper);
- }
- public Coupon getById(Long couponId) {
- return couponMapper.selectById(couponId);
- }
- /**
- * 单条发放到家庭,返回券实例ID(family_coupon.id)。
- * 返回值供 CF 兑换等需要回溯券来源的场景绑定使用。
- */
- @Transactional
- public Long issueToFamily(Long couponId, Long familyId) {
- Coupon coupon = couponMapper.selectById(couponId);
- if (coupon == null || !"ACTIVE".equals(coupon.getStatus())) {
- return null;
- }
- FamilyCoupon fc = new FamilyCoupon();
- fc.setCouponId(couponId);
- fc.setFamilyId(familyId);
- fc.setStatus("AVAILABLE");
- fc.setReceivedAt(new Date());
- familyCouponMapper.insert(fc);
- return fc.getId();
- }
- /**
- * 发放单张券到家庭并落流水,返回券实例ID(family_coupon.id)。
- * 与 {@link #grantFamily} 的区别:固定数量 1 且返回券实例ID,供「CF 兑换」这类需要
- * 在退款时把券实例反查回兑换记录、退还 CF 值的场景使用。
- *
- * @param familyId 家庭ID
- * @param couponId 券模板ID
- * @param grantType 发放类型(如 CF_EXCHANGE)
- * @param source 触发来源
- * @return 券实例ID;券模板不存在/已停用时返回 null
- */
- @Transactional
- public Long grantFamilyOne(Long familyId, Long couponId, String grantType, String source) {
- Coupon coupon = couponMapper.selectById(couponId);
- if (coupon == null) {
- return null;
- }
- if (!"ACTIVE".equals(coupon.getStatus())) {
- return null;
- }
- Long familyCouponId = issueToFamily(couponId, familyId);
- FamilyCouponGrantLog log = new FamilyCouponGrantLog();
- log.setFamilyId(familyId);
- log.setCouponId(couponId);
- log.setGrantType(grantType);
- log.setQuantity(1);
- log.setSource(source);
- log.setCreatedAt(new Date());
- familyCouponGrantLogMapper.insert(log);
- return familyCouponId;
- }
- /**
- * 管理员定向发放「会员升级优惠券」给指定用户。
- * 流程:校验用户 → 取该用户所属家庭 → 自动创建会员专属券模板(type=CASH 无门槛、
- * applicableTo=MEMBERSHIP 仅限会员订单)→ 发放到该家庭 → 落发券流水
- * (grantType=MANUAL, source=userId:{id})。
- *
- * @param userId 目标用户ID(users.id)
- * @param amountFen 面额(分)
- * @param validUntil 有效期止(null 则默认 +30 天)
- * @param remark 备注(写入券名,便于区分)
- * @return {couponId, familyId, couponName, amountFen};用户不存在/未加入家庭时返回含 error 的 Map
- */
- @Transactional
- public Map<String, Object> grantMemberUpgradeCoupon(Long userId, Integer amountFen, Date validUntil, String remark) {
- Map<String, Object> result = new HashMap<>();
- User user = userMapper.selectById(userId);
- if (user == null) {
- result.put("error", "用户不存在");
- return result;
- }
- Long familyId = user.getFamilyId();
- if (familyId == null) {
- result.put("error", "该用户未加入家庭,无法发放家庭券");
- return result;
- }
- Date now = new Date();
- if (validUntil == null) {
- validUntil = new Date(now.getTime() + 30L * 24 * 3600 * 1000);
- }
- // 创建会员专属券模板(每次发放一张独立模板,便于追踪发放记录)
- Coupon coupon = new Coupon();
- coupon.setName(buildManualCouponName(amountFen, remark));
- coupon.setType("CASH");
- coupon.setValue(amountFen);
- coupon.setMinSpend(0);
- coupon.setApplicableTo("MEMBERSHIP");
- coupon.setValidFrom(now);
- coupon.setValidUntil(validUntil);
- coupon.setTotalCount(1);
- coupon.setUsedCount(0);
- coupon.setStatus("ACTIVE");
- coupon.setCreatedAt(now);
- couponMapper.insert(coupon);
- // 发放到用户所在家庭
- issueToFamily(coupon.getId(), familyId);
- // 落发券流水
- FamilyCouponGrantLog log = new FamilyCouponGrantLog();
- log.setFamilyId(familyId);
- log.setCouponId(coupon.getId());
- log.setGrantType("MANUAL");
- log.setQuantity(1);
- log.setSource("userId:" + userId);
- log.setCreatedAt(now);
- familyCouponGrantLogMapper.insert(log);
- logger.info("管理员定向发放会员升级券: userId={}, familyId={}, couponId={}, amountFen={}, remark={}",
- userId, familyId, coupon.getId(), amountFen, remark);
- result.put("couponId", coupon.getId());
- result.put("familyId", familyId);
- result.put("couponName", coupon.getName());
- result.put("amountFen", amountFen);
- return result;
- }
- /** 生成手动发放券名称:会员升级券{金额}元[-备注] */
- private String buildManualCouponName(Integer amountFen, String remark) {
- String yuan;
- if (amountFen % 100 == 0) {
- yuan = String.valueOf(amountFen / 100);
- } else {
- yuan = String.format("%.2f", amountFen / 100.0);
- }
- String base = "会员升级券" + yuan + "元";
- if (remark != null && !remark.trim().isEmpty()) {
- return base + "-" + remark.trim();
- }
- return base;
- }
- /**
- * 发放优惠券并落流水(幂等,家庭维度)。
- * period 非空时先查流水:已存在则跳过(PERIODIC 防重用);唯一键冲突由事务回滚保证一致性。
- */
- @Transactional
- public boolean grantFamily(Long familyId, Long couponId, String grantType, String period, String source) {
- Coupon coupon = couponMapper.selectById(couponId);
- if (coupon == null) {
- return false;
- }
- if (!"ACTIVE".equals(coupon.getStatus())) {
- return false;
- }
- if (period != null) {
- Long exists = familyCouponGrantLogMapper.selectCount(
- new LambdaQueryWrapper<FamilyCouponGrantLog>()
- .eq(FamilyCouponGrantLog::getFamilyId, familyId)
- .eq(FamilyCouponGrantLog::getCouponId, couponId)
- .eq(FamilyCouponGrantLog::getGrantType, grantType)
- .eq(FamilyCouponGrantLog::getPeriod, period));
- if (exists != null && exists > 0) {
- return false;
- }
- }
- int quantity = coupon.getGrantQuantity() != null && coupon.getGrantQuantity() > 0
- ? coupon.getGrantQuantity() : 1;
- for (int i = 0; i < quantity; i++) {
- issueToFamily(couponId, familyId);
- }
- FamilyCouponGrantLog log = new FamilyCouponGrantLog();
- log.setFamilyId(familyId);
- log.setCouponId(couponId);
- log.setGrantType(grantType);
- log.setPeriod(period);
- log.setQuantity(quantity);
- log.setSource(source);
- familyCouponGrantLogMapper.insert(log);
- return true;
- }
- /** JOIN: 开通/续费指定等级会员时发放 */
- @Transactional
- public void grantFamilyJoinCoupons(Long familyId, String levelCode, String source) {
- List<Coupon> coupons = couponMapper.selectList(
- new LambdaQueryWrapper<Coupon>()
- .eq(Coupon::getGrantType, "JOIN")
- .eq(Coupon::getGrantLevelCode, levelCode)
- .and(w -> w.isNull(Coupon::getStatus).or().eq(Coupon::getStatus, "ACTIVE")));
- if (coupons.isEmpty()) {
- logger.warn("未找到 JOIN 赠券模板: familyId={}, levelCode={}", familyId, levelCode);
- return;
- }
- for (Coupon c : coupons) {
- grantFamily(familyId, c.getId(), "JOIN", "JOIN", source);
- }
- logger.info("发放 JOIN 赠券完成: familyId={}, levelCode={}, count={}", familyId, levelCode, coupons.size());
- }
- /** 兼容旧签名(标记废弃,保留供降级) */
- @Deprecated
- public void grantJoinCoupons(Long userId, String levelCode, String source) {
- Long familyId = getFamilyId(userId);
- if (familyId != null) {
- grantFamilyJoinCoupons(familyId, levelCode, source);
- }
- }
- /** POPULATION: 新增家庭成员时发放 */
- @Transactional
- public void grantFamilyPopulationCoupons(Long familyId, Long memberId) {
- List<Coupon> coupons = couponMapper.selectList(
- new LambdaQueryWrapper<Coupon>()
- .eq(Coupon::getGrantType, "POPULATION")
- .and(w -> w.isNull(Coupon::getStatus).or().eq(Coupon::getStatus, "ACTIVE")));
- for (Coupon c : coupons) {
- grantFamily(familyId, c.getId(), "POPULATION", null, "member:" + memberId);
- }
- }
- /** 兼容旧签名(标记废弃,保留供降级) */
- @Deprecated
- public void grantPopulationCoupons(Long userId, Long memberId) {
- Long familyId = getFamilyId(userId);
- if (familyId != null) {
- grantFamilyPopulationCoupons(familyId, memberId);
- }
- }
- /** REGISTER: 新用户注册成功/绑定家庭时自动发放(2026-10-27 COUPON-REG)。
- * 发到家庭维度(family_coupon),走 grantFamily 幂等链路(uk_family_grant 防重),
- * period 固定为 "REGISTER" 非空常量,确保每家庭每模板只发一次。 */
- @Transactional
- public void grantFamilyRegisterCoupons(Long familyId, String source) {
- if (familyId == null) {
- return;
- }
- List<Coupon> coupons = couponMapper.selectList(
- new LambdaQueryWrapper<Coupon>()
- .eq(Coupon::getGrantType, "REGISTER")
- .and(w -> w.isNull(Coupon::getStatus).or().eq(Coupon::getStatus, "ACTIVE")));
- if (coupons.isEmpty()) {
- logger.warn("未找到 REGISTER 赠券模板: familyId={}", familyId);
- return;
- }
- for (Coupon c : coupons) {
- grantFamily(familyId, c.getId(), "REGISTER", "REGISTER", source);
- }
- logger.info("发放 REGISTER 赠券完成: familyId={}, count={}", familyId, coupons.size());
- }
- /**
- * 收回家庭人口券:成员被管理员踢出时,撤销该家庭发放给该成员的 POPULATION 券。
- * 仅作废仍为 AVAILABLE 的券(已 USED 的券不追溯)。
- */
- @Transactional
- public void revokeFamilyPopulationCoupons(Long familyId, Long memberId) {
- String source = "member:" + memberId;
- List<FamilyCouponGrantLog> logs = familyCouponGrantLogMapper.selectList(
- new LambdaQueryWrapper<FamilyCouponGrantLog>()
- .eq(FamilyCouponGrantLog::getFamilyId, familyId)
- .eq(FamilyCouponGrantLog::getGrantType, "POPULATION")
- .eq(FamilyCouponGrantLog::getSource, source));
- if (logs == null || logs.isEmpty()) {
- return;
- }
- for (FamilyCouponGrantLog grantLog : logs) {
- List<FamilyCoupon> coupons = familyCouponMapper.selectList(
- new LambdaQueryWrapper<FamilyCoupon>()
- .eq(FamilyCoupon::getFamilyId, familyId)
- .eq(FamilyCoupon::getCouponId, grantLog.getCouponId())
- .eq(FamilyCoupon::getStatus, "AVAILABLE"));
- for (FamilyCoupon fc : coupons) {
- fc.setStatus("REVOKED");
- familyCouponMapper.updateById(fc);
- }
- }
- logger.info("收回家庭人口券完成: familyId={}, memberId={}, 作废券数={}", familyId, memberId,
- logs.stream().mapToInt(l -> l.getQuantity() != null ? l.getQuantity() : 0).sum());
- }
- /** PERIODIC: 返回所有周期性补发券模板 */
- public List<Coupon> listPeriodicTemplates() {
- return couponMapper.selectList(
- new LambdaQueryWrapper<Coupon>()
- .eq(Coupon::getGrantType, "PERIODIC")
- .and(w -> w.isNull(Coupon::getStatus).or().eq(Coupon::getStatus, "ACTIVE")));
- }
- /** 积分兑换中心:所有可兑换券(points_price>0 且在有效期内) */
- public List<Coupon> listExchangeable() {
- Date now = new Date();
- return couponMapper.selectList(
- new LambdaQueryWrapper<Coupon>()
- .gt(Coupon::getPointsPrice, 0)
- .and(w -> w.isNull(Coupon::getStatus).or().eq(Coupon::getStatus, "ACTIVE"))
- .le(Coupon::getValidFrom, now)
- .ge(Coupon::getValidUntil, now)
- .orderByAsc(Coupon::getPointsPrice));
- }
- /** 商品详情:绑定该商品的兑换券 */
- public List<Coupon> listByProduct(Long productId) {
- Date now = new Date();
- return couponMapper.selectList(
- new LambdaQueryWrapper<Coupon>()
- .eq(Coupon::getProductId, productId)
- .gt(Coupon::getPointsPrice, 0)
- .and(w -> w.isNull(Coupon::getStatus).or().eq(Coupon::getStatus, "ACTIVE"))
- .le(Coupon::getValidFrom, now)
- .ge(Coupon::getValidUntil, now)
- .orderByAsc(Coupon::getPointsPrice));
- }
- /**
- * 查询家庭尚未拥有的可兑换优惠券(用于结算页直接兑换)
- * @param productId 商品ID,非空时只返回该商品绑定的券
- */
- public List<Coupon> listUnownedExchangeable(Long userId, Long productId) {
- Long familyId = getFamilyId(userId);
- if (familyId == null) return new ArrayList<>();
- Date now = new Date();
- List<Long> ownedIds = familyCouponMapper.selectList(
- new LambdaQueryWrapper<FamilyCoupon>()
- .eq(FamilyCoupon::getFamilyId, familyId)
- .eq(FamilyCoupon::getStatus, "AVAILABLE"))
- .stream().map(FamilyCoupon::getCouponId).collect(java.util.stream.Collectors.toList());
- LambdaQueryWrapper<Coupon> wrapper = new LambdaQueryWrapper<Coupon>()
- .gt(Coupon::getPointsPrice, 0)
- .and(w -> w.isNull(Coupon::getStatus).or().eq(Coupon::getStatus, "ACTIVE"))
- .le(Coupon::getValidFrom, now)
- .ge(Coupon::getValidUntil, now)
- .notIn(!ownedIds.isEmpty(), Coupon::getId, ownedIds)
- .orderByAsc(Coupon::getPointsPrice);
- if (productId != null) {
- // 商品券 + 全场通用券(product_id 为 NULL)都可兑换,与 ownedCoupons 的 ALL 判定保持一致
- wrapper.and(w -> w.isNull(Coupon::getProductId).or().eq(Coupon::getProductId, productId));
- }
- return couponMapper.selectList(wrapper);
- }
- /** JOIN 权益展示:所有加入赠券模板 */
- public List<Coupon> listJoinRules() {
- return couponMapper.selectList(
- new LambdaQueryWrapper<Coupon>()
- .eq(Coupon::getGrantType, "JOIN")
- .and(w -> w.isNull(Coupon::getStatus).or().eq(Coupon::getStatus, "ACTIVE")));
- }
- /**
- * 我的优惠券:返回 family_coupon + coupon 联合数据,含 status/receivedAt/usedAt
- * 对外字段名保持不变(userCouponId = family_coupon.id),前端不感知内部变化
- */
- public List<Map<String, Object>> listMyCoupons(Long userId) {
- Long familyId = getFamilyId(userId);
- if (familyId == null) return new ArrayList<>();
- List<FamilyCoupon> familyCoupons = familyCouponMapper.selectList(
- new LambdaQueryWrapper<FamilyCoupon>()
- .eq(FamilyCoupon::getFamilyId, familyId)
- .orderByDesc(FamilyCoupon::getReceivedAt));
- if (familyCoupons.isEmpty()) {
- return new ArrayList<>();
- }
- List<Map<String, Object>> result = new ArrayList<>();
- for (FamilyCoupon fc : familyCoupons) {
- Map<String, Object> vo = toCouponVO(fc);
- if (vo != null) result.add(vo);
- }
- return result;
- }
- /**
- * 过期券清理(单批):把「券实例 status=AVAILABLE 且券模板 valid_until 已过期」的记录置为 EXPIRED。
- * 每批最多处理 batchSize 条,由调用方循环调用以控制单事务影响行数。
- * 只处理 AVAILABLE;RESERVED(下单占用中)/USED/REVOKED 等状态一律不涉及。
- *
- * @param now 过期判定基准时间
- * @param batchSize 单批最大条数
- * @return 本批实际更新条数,0 表示已无待清理记录
- */
- @Transactional
- public int expireOverdueAvailableCoupons(Date now, int batchSize) {
- List<Long> ids = familyCouponMapper.selectExpiredAvailableIds(now, batchSize);
- if (ids == null || ids.isEmpty()) {
- return 0;
- }
- int updated = familyCouponMapper.expireAvailableByIds(ids);
- logger.info("过期券清理单批: 命中={}, 实际更新={}", ids.size(), updated);
- return updated;
- }
- /**
- * 查询指定会员等级的活跃家庭 ID 列表(供 CouponGrantTask 周期补发)
- */
- public List<Long> listActiveMemberFamilyIds(String levelCode) {
- return membershipService.listActiveMemberFamilyIds(levelCode);
- }
- }
|