CouponService.java 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656
  1. package com.etotem.cfc.service;
  2. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  3. import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
  4. import com.etotem.cfc.entity.Coupon;
  5. import com.etotem.cfc.entity.FamilyCoupon;
  6. import com.etotem.cfc.entity.FamilyCouponGrantLog;
  7. import com.etotem.cfc.entity.User;
  8. import com.etotem.cfc.mapper.CouponMapper;
  9. import com.etotem.cfc.mapper.FamilyCouponGrantLogMapper;
  10. import com.etotem.cfc.mapper.FamilyCouponMapper;
  11. import com.etotem.cfc.mapper.UserMapper;
  12. import org.springframework.context.annotation.Lazy;
  13. import org.springframework.stereotype.Service;
  14. import org.springframework.transaction.annotation.Transactional;
  15. import javax.annotation.Resource;
  16. import java.util.ArrayList;
  17. import java.util.Date;
  18. import java.util.HashMap;
  19. import java.util.List;
  20. import java.util.Map;
  21. import java.util.Objects;
  22. import org.slf4j.Logger;
  23. import org.slf4j.LoggerFactory;
  24. import com.etotem.cfc.util.SortUtil;
  25. @Service
  26. public class CouponService {
  27. private static final Logger logger = LoggerFactory.getLogger(CouponService.class);
  28. @Resource
  29. private CouponMapper couponMapper;
  30. @Resource
  31. private FamilyCouponMapper familyCouponMapper;
  32. @Resource
  33. private FamilyCouponGrantLogMapper familyCouponGrantLogMapper;
  34. @Resource
  35. private UserMapper userMapper;
  36. @Resource
  37. @Lazy
  38. private MembershipService membershipService;
  39. // ----------------------------------------------------------------
  40. // 内部辅助方法
  41. // ----------------------------------------------------------------
  42. /** userId → familyId(用于查询当前用户所在家庭) */
  43. private Long getFamilyId(Long userId) {
  44. User user = userMapper.selectById(userId);
  45. if (user == null || user.getFamilyId() == null) {
  46. return null;
  47. }
  48. return user.getFamilyId();
  49. }
  50. /** 构建与 CouponService.listMyCoupons 相同格式的响应 Map */
  51. private Map<String, Object> toCouponVO(FamilyCoupon fc) {
  52. Coupon coupon = couponMapper.selectById(fc.getCouponId());
  53. if (coupon == null) return null;
  54. Date now = new Date();
  55. String status = fc.getStatus();
  56. if ("AVAILABLE".equals(status) && !"ACTIVE".equals(coupon.getStatus())) {
  57. status = "DISABLED";
  58. } else if ("AVAILABLE".equals(status) && coupon.getValidUntil() != null && now.after(coupon.getValidUntil())) {
  59. status = "EXPIRED";
  60. }
  61. Map<String, Object> item = new HashMap<>();
  62. // 对外字段名保持 userCouponId / id 等原有契约,前端不感知内部实现变化
  63. item.put("userCouponId", fc.getId());
  64. item.put("id", fc.getId());
  65. item.put("couponId", coupon.getId());
  66. item.put("name", coupon.getName());
  67. item.put("type", coupon.getType());
  68. item.put("value", coupon.getValue());
  69. item.put("discountRate", coupon.getDiscountRate());
  70. item.put("minSpend", coupon.getMinSpend());
  71. item.put("applicableTo", coupon.getApplicableTo());
  72. item.put("validFrom", coupon.getValidFrom());
  73. item.put("validUntil", coupon.getValidUntil());
  74. item.put("status", status);
  75. item.put("receivedAt", fc.getReceivedAt());
  76. item.put("usedAt", fc.getUsedAt());
  77. item.put("orderId", fc.getOrderId());
  78. item.put("productId", coupon.getProductId());
  79. return item;
  80. }
  81. // ----------------------------------------------------------------
  82. // 对外保留接口(签名不变,内部改为读 family_coupon)
  83. // ----------------------------------------------------------------
  84. public List<Map<String, Object>> listAvailable(Long userId) {
  85. Long familyId = getFamilyId(userId);
  86. if (familyId == null) return new ArrayList<>();
  87. List<FamilyCoupon> familyCoupons = familyCouponMapper.selectList(
  88. new LambdaQueryWrapper<FamilyCoupon>()
  89. .eq(FamilyCoupon::getFamilyId, familyId)
  90. .eq(FamilyCoupon::getStatus, "AVAILABLE")
  91. .orderByAsc(FamilyCoupon::getId));
  92. if (familyCoupons.isEmpty()) {
  93. return new ArrayList<>();
  94. }
  95. Date now = new Date();
  96. List<Map<String, Object>> result = new ArrayList<>();
  97. for (FamilyCoupon fc : familyCoupons) {
  98. Coupon coupon = couponMapper.selectById(fc.getCouponId());
  99. if (coupon == null) continue;
  100. if (!"ACTIVE".equals(coupon.getStatus())) continue;
  101. if (coupon.getValidFrom() != null && now.before(coupon.getValidFrom())) continue;
  102. if (coupon.getValidUntil() != null && now.after(coupon.getValidUntil())) continue;
  103. Map<String, Object> vo = toCouponVO(fc);
  104. if (vo != null) result.add(vo);
  105. }
  106. result.sort((a, b) -> Integer.compare(
  107. ((Number) a.getOrDefault("value", 0)).intValue(),
  108. ((Number) b.getOrDefault("value", 0)).intValue()));
  109. return result;
  110. }
  111. @Transactional
  112. public String claim(Long userId, Long couponId) {
  113. Long familyId = getFamilyId(userId);
  114. if (familyId == null) return "未加入家庭";
  115. Coupon coupon = couponMapper.selectById(couponId);
  116. if (coupon == null) {
  117. return "优惠券不存在";
  118. }
  119. if (!"ACTIVE".equals(coupon.getStatus())) {
  120. return "优惠券已停用";
  121. }
  122. if (coupon.getTotalCount() != null && coupon.getUsedCount() != null
  123. && coupon.getUsedCount() >= coupon.getTotalCount()) {
  124. return "优惠券已领完";
  125. }
  126. Date now = new Date();
  127. if (coupon.getValidFrom() != null && now.before(coupon.getValidFrom())) {
  128. return "优惠券尚未开始";
  129. }
  130. if (coupon.getValidUntil() != null && now.after(coupon.getValidUntil())) {
  131. return "优惠券已过期";
  132. }
  133. // 去重:同一个家庭同一张券只发一次(同 grantType 的幂等也通过 grant 方法保证)
  134. Long count = familyCouponMapper.selectCount(
  135. new LambdaQueryWrapper<FamilyCoupon>()
  136. .eq(FamilyCoupon::getFamilyId, familyId)
  137. .eq(FamilyCoupon::getCouponId, couponId));
  138. if (count != null && count > 0) {
  139. return "已领取过该优惠券";
  140. }
  141. issueToFamily(couponId, familyId);
  142. coupon.setUsedCount(coupon.getUsedCount() == null ? 1 : coupon.getUsedCount() + 1);
  143. couponMapper.updateById(coupon);
  144. return "领取成功";
  145. }
  146. /**
  147. * 判断用户是否为有效会员(FAMILY 或 PREMIUM 且未过期)
  148. */
  149. private boolean isMember(Long userId) {
  150. if (userId == null) return false;
  151. String level = membershipService.getMemberLevel(userId);
  152. return "FAMILY".equals(level) || "PREMIUM".equals(level);
  153. }
  154. public Integer apply(Long userId, Long userCouponId, String orderType, Integer orderAmount) {
  155. Long familyId = getFamilyId(userId);
  156. if (familyId == null) return null;
  157. FamilyCoupon fc = familyCouponMapper.selectById(userCouponId);
  158. if (fc == null || !fc.getFamilyId().equals(familyId) || !"AVAILABLE".equals(fc.getStatus())) {
  159. return null;
  160. }
  161. Coupon coupon = couponMapper.selectById(fc.getCouponId());
  162. if (coupon == null) {
  163. return null;
  164. }
  165. if (!"ACTIVE".equals(coupon.getStatus())) {
  166. return null;
  167. }
  168. Date now = new Date();
  169. if (coupon.getValidFrom() != null && now.before(coupon.getValidFrom())) {
  170. return null;
  171. }
  172. if (coupon.getValidUntil() != null && now.after(coupon.getValidUntil())) {
  173. return null;
  174. }
  175. if (!"ALL".equals(coupon.getApplicableTo()) && !coupon.getApplicableTo().equals(orderType)) {
  176. return null;
  177. }
  178. // 新增:会员专属券(applicableTo=MEMBERSHIP)仅允许会员使用
  179. // 例外:手动发放的券(grantType=MANUAL)允许非会员使用,用于赠送升级场景
  180. if ("MEMBERSHIP".equals(coupon.getApplicableTo())
  181. && !Objects.equals(coupon.getGrantType(), "MANUAL")
  182. && !isMember(userId)) {
  183. return null;
  184. }
  185. // 无门槛券(CASH)忽略起用门槛;满减/折扣券校验
  186. if (!"CASH".equals(coupon.getType()) && coupon.getMinSpend() != null && orderAmount < coupon.getMinSpend()) {
  187. return null;
  188. }
  189. // 返回抵扣金额(调用方以 originalAmount - discount 计算最终价)
  190. if ("DISCOUNT".equals(coupon.getType())) {
  191. int rate = coupon.getDiscountRate() != null ? coupon.getDiscountRate() : 9000;
  192. int discount = orderAmount * (10000 - rate) / 10000;
  193. return Math.max(discount, 0);
  194. }
  195. return Math.min(coupon.getValue(), orderAmount);
  196. }
  197. @Transactional
  198. public void markUsed(Long userCouponId, Long orderId) {
  199. FamilyCoupon fc = familyCouponMapper.selectById(userCouponId);
  200. if (fc != null) {
  201. fc.setStatus("USED");
  202. fc.setUsedAt(new Date());
  203. fc.setOrderId(orderId);
  204. familyCouponMapper.updateById(fc);
  205. }
  206. }
  207. @Transactional
  208. public void revert(Long userCouponId) {
  209. FamilyCoupon fc = familyCouponMapper.selectById(userCouponId);
  210. if (fc != null) {
  211. fc.setStatus("AVAILABLE");
  212. fc.setUsedAt(null);
  213. fc.setOrderId(null);
  214. familyCouponMapper.updateById(fc);
  215. }
  216. }
  217. /**
  218. * 下单时立即占用券实例(pending/timeout 期间拒绝其他订单使用),并关联订单号。
  219. * 支付成功后 {@link #markUsed} 改为 USED;取消/超时后 {@link #revert} 回到 AVAILABLE。
  220. */
  221. @Transactional
  222. public void reserve(Long userCouponId, Long orderId) {
  223. FamilyCoupon fc = familyCouponMapper.selectById(userCouponId);
  224. if (fc != null) {
  225. fc.setStatus("RESERVED");
  226. fc.setOrderId(orderId);
  227. familyCouponMapper.updateById(fc);
  228. }
  229. }
  230. public List<Coupon> listAll() {
  231. return couponMapper.selectList(null);
  232. }
  233. public List<Coupon> listAll(List<Map<String, String>> sortSpecs) {
  234. if (sortSpecs == null || sortSpecs.isEmpty()) {
  235. return listAll();
  236. }
  237. QueryWrapper<Coupon> wrapper = new QueryWrapper<>();
  238. SortUtil.applySort(wrapper, sortSpecs, null);
  239. return couponMapper.selectList(wrapper);
  240. }
  241. public Coupon getById(Long couponId) {
  242. return couponMapper.selectById(couponId);
  243. }
  244. /**
  245. * 单条发放到家庭,返回券实例ID(family_coupon.id)。
  246. * 返回值供 CF 兑换等需要回溯券来源的场景绑定使用。
  247. */
  248. @Transactional
  249. public Long issueToFamily(Long couponId, Long familyId) {
  250. Coupon coupon = couponMapper.selectById(couponId);
  251. if (coupon == null || !"ACTIVE".equals(coupon.getStatus())) {
  252. return null;
  253. }
  254. FamilyCoupon fc = new FamilyCoupon();
  255. fc.setCouponId(couponId);
  256. fc.setFamilyId(familyId);
  257. fc.setStatus("AVAILABLE");
  258. fc.setReceivedAt(new Date());
  259. familyCouponMapper.insert(fc);
  260. return fc.getId();
  261. }
  262. /**
  263. * 发放单张券到家庭并落流水,返回券实例ID(family_coupon.id)。
  264. * 与 {@link #grantFamily} 的区别:固定数量 1 且返回券实例ID,供「CF 兑换」这类需要
  265. * 在退款时把券实例反查回兑换记录、退还 CF 值的场景使用。
  266. *
  267. * @param familyId 家庭ID
  268. * @param couponId 券模板ID
  269. * @param grantType 发放类型(如 CF_EXCHANGE)
  270. * @param source 触发来源
  271. * @return 券实例ID;券模板不存在/已停用时返回 null
  272. */
  273. @Transactional
  274. public Long grantFamilyOne(Long familyId, Long couponId, String grantType, String source) {
  275. Coupon coupon = couponMapper.selectById(couponId);
  276. if (coupon == null) {
  277. return null;
  278. }
  279. if (!"ACTIVE".equals(coupon.getStatus())) {
  280. return null;
  281. }
  282. Long familyCouponId = issueToFamily(couponId, familyId);
  283. FamilyCouponGrantLog log = new FamilyCouponGrantLog();
  284. log.setFamilyId(familyId);
  285. log.setCouponId(couponId);
  286. log.setGrantType(grantType);
  287. log.setQuantity(1);
  288. log.setSource(source);
  289. log.setCreatedAt(new Date());
  290. familyCouponGrantLogMapper.insert(log);
  291. return familyCouponId;
  292. }
  293. /**
  294. * 管理员定向发放「会员升级优惠券」给指定用户。
  295. * 流程:校验用户 → 取该用户所属家庭 → 自动创建会员专属券模板(type=CASH 无门槛、
  296. * applicableTo=MEMBERSHIP 仅限会员订单)→ 发放到该家庭 → 落发券流水
  297. * (grantType=MANUAL, source=userId:{id})。
  298. *
  299. * @param userId 目标用户ID(users.id)
  300. * @param amountFen 面额(分)
  301. * @param validUntil 有效期止(null 则默认 +30 天)
  302. * @param remark 备注(写入券名,便于区分)
  303. * @return {couponId, familyId, couponName, amountFen};用户不存在/未加入家庭时返回含 error 的 Map
  304. */
  305. @Transactional
  306. public Map<String, Object> grantMemberUpgradeCoupon(Long userId, Integer amountFen, Date validUntil, String remark) {
  307. Map<String, Object> result = new HashMap<>();
  308. User user = userMapper.selectById(userId);
  309. if (user == null) {
  310. result.put("error", "用户不存在");
  311. return result;
  312. }
  313. Long familyId = user.getFamilyId();
  314. if (familyId == null) {
  315. result.put("error", "该用户未加入家庭,无法发放家庭券");
  316. return result;
  317. }
  318. Date now = new Date();
  319. if (validUntil == null) {
  320. validUntil = new Date(now.getTime() + 30L * 24 * 3600 * 1000);
  321. }
  322. // 创建会员专属券模板(每次发放一张独立模板,便于追踪发放记录)
  323. Coupon coupon = new Coupon();
  324. coupon.setName(buildManualCouponName(amountFen, remark));
  325. coupon.setType("CASH");
  326. coupon.setValue(amountFen);
  327. coupon.setMinSpend(0);
  328. coupon.setApplicableTo("MEMBERSHIP");
  329. coupon.setValidFrom(now);
  330. coupon.setValidUntil(validUntil);
  331. coupon.setTotalCount(1);
  332. coupon.setUsedCount(0);
  333. coupon.setStatus("ACTIVE");
  334. coupon.setCreatedAt(now);
  335. couponMapper.insert(coupon);
  336. // 发放到用户所在家庭
  337. issueToFamily(coupon.getId(), familyId);
  338. // 落发券流水
  339. FamilyCouponGrantLog log = new FamilyCouponGrantLog();
  340. log.setFamilyId(familyId);
  341. log.setCouponId(coupon.getId());
  342. log.setGrantType("MANUAL");
  343. log.setQuantity(1);
  344. log.setSource("userId:" + userId);
  345. log.setCreatedAt(now);
  346. familyCouponGrantLogMapper.insert(log);
  347. logger.info("管理员定向发放会员升级券: userId={}, familyId={}, couponId={}, amountFen={}, remark={}",
  348. userId, familyId, coupon.getId(), amountFen, remark);
  349. result.put("couponId", coupon.getId());
  350. result.put("familyId", familyId);
  351. result.put("couponName", coupon.getName());
  352. result.put("amountFen", amountFen);
  353. return result;
  354. }
  355. /** 生成手动发放券名称:会员升级券{金额}元[-备注] */
  356. private String buildManualCouponName(Integer amountFen, String remark) {
  357. String yuan;
  358. if (amountFen % 100 == 0) {
  359. yuan = String.valueOf(amountFen / 100);
  360. } else {
  361. yuan = String.format("%.2f", amountFen / 100.0);
  362. }
  363. String base = "会员升级券" + yuan + "元";
  364. if (remark != null && !remark.trim().isEmpty()) {
  365. return base + "-" + remark.trim();
  366. }
  367. return base;
  368. }
  369. /**
  370. * 发放优惠券并落流水(幂等,家庭维度)。
  371. * period 非空时先查流水:已存在则跳过(PERIODIC 防重用);唯一键冲突由事务回滚保证一致性。
  372. */
  373. @Transactional
  374. public boolean grantFamily(Long familyId, Long couponId, String grantType, String period, String source) {
  375. Coupon coupon = couponMapper.selectById(couponId);
  376. if (coupon == null) {
  377. return false;
  378. }
  379. if (!"ACTIVE".equals(coupon.getStatus())) {
  380. return false;
  381. }
  382. if (period != null) {
  383. Long exists = familyCouponGrantLogMapper.selectCount(
  384. new LambdaQueryWrapper<FamilyCouponGrantLog>()
  385. .eq(FamilyCouponGrantLog::getFamilyId, familyId)
  386. .eq(FamilyCouponGrantLog::getCouponId, couponId)
  387. .eq(FamilyCouponGrantLog::getGrantType, grantType)
  388. .eq(FamilyCouponGrantLog::getPeriod, period));
  389. if (exists != null && exists > 0) {
  390. return false;
  391. }
  392. }
  393. int quantity = coupon.getGrantQuantity() != null && coupon.getGrantQuantity() > 0
  394. ? coupon.getGrantQuantity() : 1;
  395. for (int i = 0; i < quantity; i++) {
  396. issueToFamily(couponId, familyId);
  397. }
  398. FamilyCouponGrantLog log = new FamilyCouponGrantLog();
  399. log.setFamilyId(familyId);
  400. log.setCouponId(couponId);
  401. log.setGrantType(grantType);
  402. log.setPeriod(period);
  403. log.setQuantity(quantity);
  404. log.setSource(source);
  405. familyCouponGrantLogMapper.insert(log);
  406. return true;
  407. }
  408. /** JOIN: 开通/续费指定等级会员时发放 */
  409. @Transactional
  410. public void grantFamilyJoinCoupons(Long familyId, String levelCode, String source) {
  411. List<Coupon> coupons = couponMapper.selectList(
  412. new LambdaQueryWrapper<Coupon>()
  413. .eq(Coupon::getGrantType, "JOIN")
  414. .eq(Coupon::getGrantLevelCode, levelCode)
  415. .and(w -> w.isNull(Coupon::getStatus).or().eq(Coupon::getStatus, "ACTIVE")));
  416. if (coupons.isEmpty()) {
  417. logger.warn("未找到 JOIN 赠券模板: familyId={}, levelCode={}", familyId, levelCode);
  418. return;
  419. }
  420. for (Coupon c : coupons) {
  421. grantFamily(familyId, c.getId(), "JOIN", "JOIN", source);
  422. }
  423. logger.info("发放 JOIN 赠券完成: familyId={}, levelCode={}, count={}", familyId, levelCode, coupons.size());
  424. }
  425. /** 兼容旧签名(标记废弃,保留供降级) */
  426. @Deprecated
  427. public void grantJoinCoupons(Long userId, String levelCode, String source) {
  428. Long familyId = getFamilyId(userId);
  429. if (familyId != null) {
  430. grantFamilyJoinCoupons(familyId, levelCode, source);
  431. }
  432. }
  433. /** POPULATION: 新增家庭成员时发放 */
  434. @Transactional
  435. public void grantFamilyPopulationCoupons(Long familyId, Long memberId) {
  436. List<Coupon> coupons = couponMapper.selectList(
  437. new LambdaQueryWrapper<Coupon>()
  438. .eq(Coupon::getGrantType, "POPULATION")
  439. .and(w -> w.isNull(Coupon::getStatus).or().eq(Coupon::getStatus, "ACTIVE")));
  440. for (Coupon c : coupons) {
  441. grantFamily(familyId, c.getId(), "POPULATION", null, "member:" + memberId);
  442. }
  443. }
  444. /** 兼容旧签名(标记废弃,保留供降级) */
  445. @Deprecated
  446. public void grantPopulationCoupons(Long userId, Long memberId) {
  447. Long familyId = getFamilyId(userId);
  448. if (familyId != null) {
  449. grantFamilyPopulationCoupons(familyId, memberId);
  450. }
  451. }
  452. /** REGISTER: 新用户注册成功/绑定家庭时自动发放(2026-10-27 COUPON-REG)。
  453. * 发到家庭维度(family_coupon),走 grantFamily 幂等链路(uk_family_grant 防重),
  454. * period 固定为 "REGISTER" 非空常量,确保每家庭每模板只发一次。 */
  455. @Transactional
  456. public void grantFamilyRegisterCoupons(Long familyId, String source) {
  457. if (familyId == null) {
  458. return;
  459. }
  460. List<Coupon> coupons = couponMapper.selectList(
  461. new LambdaQueryWrapper<Coupon>()
  462. .eq(Coupon::getGrantType, "REGISTER")
  463. .and(w -> w.isNull(Coupon::getStatus).or().eq(Coupon::getStatus, "ACTIVE")));
  464. if (coupons.isEmpty()) {
  465. logger.warn("未找到 REGISTER 赠券模板: familyId={}", familyId);
  466. return;
  467. }
  468. for (Coupon c : coupons) {
  469. grantFamily(familyId, c.getId(), "REGISTER", "REGISTER", source);
  470. }
  471. logger.info("发放 REGISTER 赠券完成: familyId={}, count={}", familyId, coupons.size());
  472. }
  473. /**
  474. * 收回家庭人口券:成员被管理员踢出时,撤销该家庭发放给该成员的 POPULATION 券。
  475. * 仅作废仍为 AVAILABLE 的券(已 USED 的券不追溯)。
  476. */
  477. @Transactional
  478. public void revokeFamilyPopulationCoupons(Long familyId, Long memberId) {
  479. String source = "member:" + memberId;
  480. List<FamilyCouponGrantLog> logs = familyCouponGrantLogMapper.selectList(
  481. new LambdaQueryWrapper<FamilyCouponGrantLog>()
  482. .eq(FamilyCouponGrantLog::getFamilyId, familyId)
  483. .eq(FamilyCouponGrantLog::getGrantType, "POPULATION")
  484. .eq(FamilyCouponGrantLog::getSource, source));
  485. if (logs == null || logs.isEmpty()) {
  486. return;
  487. }
  488. for (FamilyCouponGrantLog grantLog : logs) {
  489. List<FamilyCoupon> coupons = familyCouponMapper.selectList(
  490. new LambdaQueryWrapper<FamilyCoupon>()
  491. .eq(FamilyCoupon::getFamilyId, familyId)
  492. .eq(FamilyCoupon::getCouponId, grantLog.getCouponId())
  493. .eq(FamilyCoupon::getStatus, "AVAILABLE"));
  494. for (FamilyCoupon fc : coupons) {
  495. fc.setStatus("REVOKED");
  496. familyCouponMapper.updateById(fc);
  497. }
  498. }
  499. logger.info("收回家庭人口券完成: familyId={}, memberId={}, 作废券数={}", familyId, memberId,
  500. logs.stream().mapToInt(l -> l.getQuantity() != null ? l.getQuantity() : 0).sum());
  501. }
  502. /** PERIODIC: 返回所有周期性补发券模板 */
  503. public List<Coupon> listPeriodicTemplates() {
  504. return couponMapper.selectList(
  505. new LambdaQueryWrapper<Coupon>()
  506. .eq(Coupon::getGrantType, "PERIODIC")
  507. .and(w -> w.isNull(Coupon::getStatus).or().eq(Coupon::getStatus, "ACTIVE")));
  508. }
  509. /** 积分兑换中心:所有可兑换券(points_price>0 且在有效期内) */
  510. public List<Coupon> listExchangeable() {
  511. Date now = new Date();
  512. return couponMapper.selectList(
  513. new LambdaQueryWrapper<Coupon>()
  514. .gt(Coupon::getPointsPrice, 0)
  515. .and(w -> w.isNull(Coupon::getStatus).or().eq(Coupon::getStatus, "ACTIVE"))
  516. .le(Coupon::getValidFrom, now)
  517. .ge(Coupon::getValidUntil, now)
  518. .orderByAsc(Coupon::getPointsPrice));
  519. }
  520. /** 商品详情:绑定该商品的兑换券 */
  521. public List<Coupon> listByProduct(Long productId) {
  522. Date now = new Date();
  523. return couponMapper.selectList(
  524. new LambdaQueryWrapper<Coupon>()
  525. .eq(Coupon::getProductId, productId)
  526. .gt(Coupon::getPointsPrice, 0)
  527. .and(w -> w.isNull(Coupon::getStatus).or().eq(Coupon::getStatus, "ACTIVE"))
  528. .le(Coupon::getValidFrom, now)
  529. .ge(Coupon::getValidUntil, now)
  530. .orderByAsc(Coupon::getPointsPrice));
  531. }
  532. /**
  533. * 查询家庭尚未拥有的可兑换优惠券(用于结算页直接兑换)
  534. * @param productId 商品ID,非空时只返回该商品绑定的券
  535. */
  536. public List<Coupon> listUnownedExchangeable(Long userId, Long productId) {
  537. Long familyId = getFamilyId(userId);
  538. if (familyId == null) return new ArrayList<>();
  539. Date now = new Date();
  540. List<Long> ownedIds = familyCouponMapper.selectList(
  541. new LambdaQueryWrapper<FamilyCoupon>()
  542. .eq(FamilyCoupon::getFamilyId, familyId)
  543. .eq(FamilyCoupon::getStatus, "AVAILABLE"))
  544. .stream().map(FamilyCoupon::getCouponId).collect(java.util.stream.Collectors.toList());
  545. LambdaQueryWrapper<Coupon> wrapper = new LambdaQueryWrapper<Coupon>()
  546. .gt(Coupon::getPointsPrice, 0)
  547. .and(w -> w.isNull(Coupon::getStatus).or().eq(Coupon::getStatus, "ACTIVE"))
  548. .le(Coupon::getValidFrom, now)
  549. .ge(Coupon::getValidUntil, now)
  550. .notIn(!ownedIds.isEmpty(), Coupon::getId, ownedIds)
  551. .orderByAsc(Coupon::getPointsPrice);
  552. if (productId != null) {
  553. // 商品券 + 全场通用券(product_id 为 NULL)都可兑换,与 ownedCoupons 的 ALL 判定保持一致
  554. wrapper.and(w -> w.isNull(Coupon::getProductId).or().eq(Coupon::getProductId, productId));
  555. }
  556. return couponMapper.selectList(wrapper);
  557. }
  558. /** JOIN 权益展示:所有加入赠券模板 */
  559. public List<Coupon> listJoinRules() {
  560. return couponMapper.selectList(
  561. new LambdaQueryWrapper<Coupon>()
  562. .eq(Coupon::getGrantType, "JOIN")
  563. .and(w -> w.isNull(Coupon::getStatus).or().eq(Coupon::getStatus, "ACTIVE")));
  564. }
  565. /**
  566. * 我的优惠券:返回 family_coupon + coupon 联合数据,含 status/receivedAt/usedAt
  567. * 对外字段名保持不变(userCouponId = family_coupon.id),前端不感知内部变化
  568. */
  569. public List<Map<String, Object>> listMyCoupons(Long userId) {
  570. Long familyId = getFamilyId(userId);
  571. if (familyId == null) return new ArrayList<>();
  572. List<FamilyCoupon> familyCoupons = familyCouponMapper.selectList(
  573. new LambdaQueryWrapper<FamilyCoupon>()
  574. .eq(FamilyCoupon::getFamilyId, familyId)
  575. .orderByDesc(FamilyCoupon::getReceivedAt));
  576. if (familyCoupons.isEmpty()) {
  577. return new ArrayList<>();
  578. }
  579. List<Map<String, Object>> result = new ArrayList<>();
  580. for (FamilyCoupon fc : familyCoupons) {
  581. Map<String, Object> vo = toCouponVO(fc);
  582. if (vo != null) result.add(vo);
  583. }
  584. return result;
  585. }
  586. /**
  587. * 过期券清理(单批):把「券实例 status=AVAILABLE 且券模板 valid_until 已过期」的记录置为 EXPIRED。
  588. * 每批最多处理 batchSize 条,由调用方循环调用以控制单事务影响行数。
  589. * 只处理 AVAILABLE;RESERVED(下单占用中)/USED/REVOKED 等状态一律不涉及。
  590. *
  591. * @param now 过期判定基准时间
  592. * @param batchSize 单批最大条数
  593. * @return 本批实际更新条数,0 表示已无待清理记录
  594. */
  595. @Transactional
  596. public int expireOverdueAvailableCoupons(Date now, int batchSize) {
  597. List<Long> ids = familyCouponMapper.selectExpiredAvailableIds(now, batchSize);
  598. if (ids == null || ids.isEmpty()) {
  599. return 0;
  600. }
  601. int updated = familyCouponMapper.expireAvailableByIds(ids);
  602. logger.info("过期券清理单批: 命中={}, 实际更新={}", ids.size(), updated);
  603. return updated;
  604. }
  605. /**
  606. * 查询指定会员等级的活跃家庭 ID 列表(供 CouponGrantTask 周期补发)
  607. */
  608. public List<Long> listActiveMemberFamilyIds(String levelCode) {
  609. return membershipService.listActiveMemberFamilyIds(levelCode);
  610. }
  611. }