BadgeService.java 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. package com.train.service;
  2. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  3. import com.train.entity.*;
  4. import com.train.mapper.*;
  5. import lombok.extern.slf4j.Slf4j;
  6. import org.springframework.stereotype.Service;
  7. import org.springframework.transaction.annotation.Transactional;
  8. import javax.annotation.Resource;
  9. import java.util.*;
  10. import java.util.stream.Collectors;
  11. /**
  12. * 徽章与成长体系服务:
  13. * - ensureCatalog():目录兜底同步(schema 种子 + 代码常量双保险)
  14. * - syncBadges(uid):自动判定并颁发符合条件的徽章
  15. * - grantBadge(uid, badgeKey, adminId, remark):手动颁发(幂等)
  16. * - mine(uid):查询学员全量徽章 + 段位
  17. */
  18. @Slf4j
  19. @Service
  20. public class BadgeService {
  21. @Resource
  22. private TrainBadgeMapper trainBadgeMapper;
  23. @Resource
  24. private TrainUserBadgeMapper trainUserBadgeMapper;
  25. @Resource
  26. private TrainCertificateMapper trainCertificateMapper;
  27. @Resource
  28. private TrainClassMapper trainClassMapper;
  29. @Resource
  30. private TrainCourseMapper trainCourseMapper;
  31. @Resource
  32. private TrainInviteMapper trainInviteMapper;
  33. @Resource
  34. private TrainRoadmapMapper trainRoadmapMapper;
  35. @Resource
  36. private TrainGroupMemberMapper trainGroupMemberMapper;
  37. @Resource
  38. private TrainVoteMapper trainVoteMapper;
  39. @Resource
  40. private TrainEnrollmentMapper trainEnrollmentMapper;
  41. // ========== 32 枚徽章常量(兜底) ==========
  42. private static final List<Map<String, String>> CATALOG = Arrays.asList(
  43. // module 1-12
  44. badge("mod_s1", "module", "启航·上", "#7C3AED", "电子", "完成 S1 家庭目录树检查", 1),
  45. badge("mod_s2", "module", "启航·下", "#7C3AED", "电子", "完成 S2 路演两轮投票", 2),
  46. badge("mod_a1", "module", "财富诊断", "#F59E0B", "电子", "完成 L1-A1 提交真实财富报告", 3),
  47. badge("mod_a2", "module", "财富系统", "#F59E0B", "电子", "完成 L1-A2 自动化生效", 4),
  48. badge("mod_h1", "module", "健康趋势", "#10B981", "电子", "完成 L1-H1 提交风险清单", 5),
  49. badge("mod_h2", "module", "健康系统", "#10B981", "电子", "完成 L1-H2 解读菌群报告", 6),
  50. badge("mod_g1", "module", "成长拆解", "#8B5CF6", "电子", "完成 L1-G1 习惯实验", 7),
  51. badge("mod_g2", "module", "成长系统", "#8B5CF6", "电子", "完成 L1-G2 学期计划", 8),
  52. badge("mod_b1", "module", "系统架构", "#1D4ED8", "电子", "完成 L2-B1 ≥5条联动规则", 9),
  53. badge("mod_b2", "module", "自动化工厂", "#1D4ED8", "电子", "完成 L2-B2 ≥8条自动化", 10),
  54. badge("mod_b3", "module", "仪表盘", "#1D4ED8", "电子", "完成 L2-B3 看板上线", 11),
  55. badge("mod_b4", "module", "季度闭环", "#1D4ED8", "电子", "完成 L2-B4 系统体检", 12),
  56. // course 13-17
  57. badge("course_start", "course", "启航徽章", "#7C3AED", "实体+证书", "L0 完课", 13),
  58. badge("course_wealth", "course", "财富专精徽章", "#F59E0B", "电子", "L1-A 完课", 14),
  59. badge("course_health", "course", "健康专精徽章", "#10B981", "电子", "L1-B 完课", 15),
  60. badge("course_growth", "course", "成长规划专精徽章", "#8B5CF6", "电子", "L1-C 完课", 16),
  61. badge("course_system", "course", "系统师徽章", "#14B8A6", "电子", "L2 完课+L3 结业", 17),
  62. // skill 18-23
  63. badge("skill_mask", "skill", "脱敏达人", "#64748B", "电子", "找茬赛满分/脱敏零问题", 18),
  64. badge("skill_prompt", "skill", "提示词匠人", "#64748B", "电子", "改编提示词≥10条被采用", 19),
  65. badge("skill_automation", "skill", "自动化搭建者", "#64748B", "电子", "自建自动化≥5条稳定1月", 20),
  66. badge("skill_pitch", "skill", "路演讲者", "#64748B", "电子", "L0路演获最想抄走票", 21),
  67. badge("skill_board", "skill", "看板设计师", "#64748B", "电子", "仪表盘获最佳", 22),
  68. badge("skill_retest", "skill", "复测坚持者", "#64748B", "电子", "连续2季度复测", 23),
  69. // milestone 24-28
  70. badge("ms_21day", "milestone", "21天全勤", "#F59E0B", "实体", "L3打卡≥21天", 24),
  71. badge("ms_light", "milestone", "传灯徽章", "#F97316", "实体", "成功转介≥3人报名", 25),
  72. badge("ms_repeat", "milestone", "回炉徽章", "#F97316", "电子", "复训≥3模块", 26),
  73. badge("ms_share", "milestone", "分享徽章", "#F97316", "实体", "沙龙案例分享≥1次", 27),
  74. badge("ms_review", "milestone", "年度复盘", "#F59E0B", "电子", "完成三本账年度复盘", 28),
  75. // lecturer 29-32
  76. badge("lec_t1", "lecturer", "讲师·铜", "#F97316", "实体+讲师证", "T1认证", 29),
  77. badge("lec_t2", "lecturer", "讲师·银", "#D4D4D8", "电子", "T2认证", 30),
  78. badge("lec_t3", "lecturer", "讲师·金", "#F59E0B", "电子", "T3认证", 31),
  79. badge("lec_t4", "lecturer", "讲师·珊瑚金", "#F97316", "电子", "T4认证", 32)
  80. );
  81. private static Map<String, String> badge(String key, String category, String name,
  82. String color, String carrier, String conditionDesc, int sort) {
  83. Map<String, String> m = new LinkedHashMap<>();
  84. m.put("badge_key", key);
  85. m.put("category", category);
  86. m.put("name", name);
  87. m.put("color", color);
  88. m.put("carrier", carrier);
  89. m.put("condition_desc", conditionDesc);
  90. m.put("sort", String.valueOf(sort));
  91. return m;
  92. }
  93. // ========== a) 目录兜底同步 ==========
  94. public void ensureCatalog() {
  95. Long count = trainBadgeMapper.selectCount(new LambdaQueryWrapper<TrainBadge>());
  96. if (count != null && count > 0) {
  97. return;
  98. }
  99. log.info("[BadgeService] 徽章目录为空,执行代码常量兜底插入 {} 条", CATALOG.size());
  100. for (Map<String, String> row : CATALOG) {
  101. try {
  102. TrainBadge b = new TrainBadge();
  103. b.setBadgeKey(row.get("badge_key"));
  104. b.setCategory(row.get("category"));
  105. b.setName(row.get("name"));
  106. b.setColor(row.get("color"));
  107. b.setCarrier(row.get("carrier"));
  108. b.setConditionDesc(row.get("condition_desc"));
  109. b.setSort(Integer.parseInt(row.get("sort")));
  110. b.setCreatedAt(new Date());
  111. trainBadgeMapper.insert(b);
  112. } catch (Exception e) {
  113. // 重复插入(badge_key UNIQUE)被吞,属预期
  114. log.debug("插入徽章 {} 失败(可能已存在): {}", row.get("badge_key"), e.getMessage());
  115. }
  116. }
  117. }
  118. // ========== b) 自动判定并颁发 ==========
  119. @Transactional(rollbackFor = Exception.class)
  120. public void syncBadges(Long uid) {
  121. ensureCatalog();
  122. // 已拥有的徽章 key 集合
  123. List<TrainUserBadge> existingList = trainUserBadgeMapper.selectList(
  124. new LambdaQueryWrapper<TrainUserBadge>().eq(TrainUserBadge::getUid, uid));
  125. Set<String> ownedKeys = existingList.stream()
  126. .map(TrainUserBadge::getBadgeKey)
  127. .collect(Collectors.toSet());
  128. // 证书列表
  129. List<TrainCertificate> certs = trainCertificateMapper.selectList(
  130. new LambdaQueryWrapper<TrainCertificate>().eq(TrainCertificate::getUid, uid));
  131. Set<String> certLevels = certs.stream()
  132. .map(TrainCertificate::getLevel)
  133. .filter(Objects::nonNull)
  134. .collect(Collectors.toSet());
  135. // 收集待颁发的徽章 key
  136. Set<String> toGrant = new LinkedHashSet<>();
  137. // --- L0 相关 ---
  138. if (certLevels.contains("L0")) {
  139. toGrant.add("mod_s1");
  140. toGrant.add("mod_s2");
  141. toGrant.add("course_start");
  142. }
  143. // --- L2 相关 ---
  144. if (certLevels.contains("L2")) {
  145. toGrant.add("mod_b1");
  146. toGrant.add("mod_b2");
  147. toGrant.add("mod_b3");
  148. toGrant.add("mod_b4");
  149. }
  150. // --- course_system:L2 + L3 ---
  151. if (certLevels.contains("L2") && certLevels.contains("L3")) {
  152. toGrant.add("course_system");
  153. }
  154. // --- L1 证书按课程名细分 ---
  155. // 对每张 level=L1 的证书,解析课程名(cert -> class -> course -> name)
  156. Set<String> l1CourseNames = new HashSet<>();
  157. for (TrainCertificate cert : certs) {
  158. if (!"L1".equals(cert.getLevel()) || cert.getClassId() == null) {
  159. continue;
  160. }
  161. TrainClass clazz = trainClassMapper.selectById(cert.getClassId());
  162. if (clazz == null || clazz.getCourseId() == null) {
  163. continue;
  164. }
  165. TrainCourse course = trainCourseMapper.selectById(clazz.getCourseId());
  166. if (course == null || course.getName() == null) {
  167. continue;
  168. }
  169. l1CourseNames.add(course.getName());
  170. }
  171. for (String courseName : l1CourseNames) {
  172. if (courseName.contains("财富")) {
  173. toGrant.add("mod_a1");
  174. toGrant.add("mod_a2");
  175. toGrant.add("course_wealth");
  176. }
  177. if (courseName.contains("健康")) {
  178. toGrant.add("mod_h1");
  179. toGrant.add("mod_h2");
  180. toGrant.add("course_health");
  181. }
  182. if (courseName.contains("成长")) {
  183. toGrant.add("mod_g1");
  184. toGrant.add("mod_g2");
  185. toGrant.add("course_growth");
  186. }
  187. }
  188. // --- skill_pitch(路演讲者)---
  189. // uid 所在的组 → 该组的 roadmap speaker_uid=uid → 该组在 round=2 投票中被投中
  190. if (!ownedKeys.contains("skill_pitch")) {
  191. List<TrainGroupMember> members = trainGroupMemberMapper.selectList(
  192. new LambdaQueryWrapper<TrainGroupMember>().eq(TrainGroupMember::getUid, uid));
  193. for (TrainGroupMember m : members) {
  194. if (m.getGroupId() == null) continue;
  195. // 查该组是否有 speaker_uid=uid 的路演记录
  196. TrainRoadmap roadmap = trainRoadmapMapper.selectOne(
  197. new LambdaQueryWrapper<TrainRoadmap>()
  198. .eq(TrainRoadmap::getGroupId, m.getGroupId())
  199. .eq(TrainRoadmap::getSpeakerUid, uid)
  200. .last("LIMIT 1"));
  201. if (roadmap == null) continue;
  202. // 该组在 round=2 投票中是否被投中
  203. Long voteCount = trainVoteMapper.selectCount(
  204. new LambdaQueryWrapper<TrainVote>()
  205. .eq(TrainVote::getRound, 2)
  206. .eq(TrainVote::getTargetGroupId, m.getGroupId()));
  207. if (voteCount != null && voteCount > 0) {
  208. toGrant.add("skill_pitch");
  209. break;
  210. }
  211. }
  212. }
  213. // --- ms_light(传灯):成功转介 >= 3 人 ---
  214. if (!ownedKeys.contains("ms_light")) {
  215. Long inviteCount = trainInviteMapper.selectCount(
  216. new LambdaQueryWrapper<TrainInvite>()
  217. .eq(TrainInvite::getInviterId, uid)
  218. .eq(TrainInvite::getSuccessful, 1));
  219. if (inviteCount != null && inviteCount >= 3) {
  220. toGrant.add("ms_light");
  221. }
  222. }
  223. // 批量颁发(幂等:已存在的跳过)
  224. for (String key : toGrant) {
  225. if (!ownedKeys.contains(key)) {
  226. insertUserBadge(uid, key, "系统自动判定", 0L);
  227. }
  228. }
  229. }
  230. // ========== c) 手动颁发(幂等) ==========
  231. @Transactional(rollbackFor = Exception.class)
  232. public boolean grantBadge(Long uid, String badgeKey, Long adminId, String remark) {
  233. ensureCatalog();
  234. // 检查徽章键是否在目录中
  235. TrainBadge badge = trainBadgeMapper.selectOne(
  236. new LambdaQueryWrapper<TrainBadge>().eq(TrainBadge::getBadgeKey, badgeKey).last("LIMIT 1"));
  237. if (badge == null) {
  238. return false;
  239. }
  240. // 幂等:已存在则直接返回
  241. Long exists = trainUserBadgeMapper.selectCount(
  242. new LambdaQueryWrapper<TrainUserBadge>()
  243. .eq(TrainUserBadge::getUid, uid)
  244. .eq(TrainUserBadge::getBadgeKey, badgeKey));
  245. if (exists != null && exists > 0) {
  246. return true;
  247. }
  248. String proof = (remark != null && !remark.trim().isEmpty()) ? remark.trim() : badge.getConditionDesc();
  249. insertUserBadge(uid, badgeKey, proof, adminId);
  250. return true;
  251. }
  252. // ========== d) 学员端查询 ==========
  253. public Map<String, Object> mine(Long uid) {
  254. // 先触发自动判定
  255. syncBadges(uid);
  256. // 全量徽章目录(按 sort 升序)
  257. List<TrainBadge> allBadges = trainBadgeMapper.selectList(
  258. new LambdaQueryWrapper<TrainBadge>().orderByAsc(TrainBadge::getSort));
  259. // 该用户已获得的徽章
  260. List<TrainUserBadge> userBadges = trainUserBadgeMapper.selectList(
  261. new LambdaQueryWrapper<TrainUserBadge>().eq(TrainUserBadge::getUid, uid));
  262. // 构建 badgeKey -> UserBadge 的 map
  263. Map<String, TrainUserBadge> earnedMap = userBadges.stream()
  264. .collect(Collectors.toMap(TrainUserBadge::getBadgeKey, ub -> ub, (a, b) -> a));
  265. // 构建 badge key -> badge catalog 的 map
  266. Map<String, TrainBadge> catalogMap = allBadges.stream()
  267. .collect(Collectors.toMap(TrainBadge::getBadgeKey, b -> b, (a, b) -> a));
  268. // badges 列表
  269. List<Map<String, Object>> badges = new ArrayList<>();
  270. int earnedCount = 0;
  271. for (TrainBadge b : allBadges) {
  272. Map<String, Object> item = new LinkedHashMap<>();
  273. item.put("badgeKey", b.getBadgeKey());
  274. item.put("category", b.getCategory());
  275. item.put("name", b.getName());
  276. item.put("color", b.getColor());
  277. item.put("carrier", b.getCarrier());
  278. item.put("condition", b.getConditionDesc());
  279. TrainUserBadge ub = earnedMap.get(b.getBadgeKey());
  280. boolean earned = (ub != null);
  281. item.put("earned", earned);
  282. item.put("earnedAt", ub != null ? ub.getEarnedAt() : null);
  283. if (earned) {
  284. earnedCount++;
  285. }
  286. badges.add(item);
  287. }
  288. // 段位计算(取最高档)
  289. Map<String, String> grade = calcGrade(uid, earnedMap);
  290. Map<String, Object> result = new LinkedHashMap<>();
  291. result.put("grade", grade);
  292. result.put("earnedCount", earnedCount);
  293. result.put("badges", badges);
  294. return result;
  295. }
  296. // ========== 段位计算 ==========
  297. private Map<String, String> calcGrade(Long uid, Map<String, TrainUserBadge> earnedMap) {
  298. Map<String, String> grade = new LinkedHashMap<>();
  299. // 讲师(任一 lec_t1..t4 已获)
  300. if (earnedMap.containsKey("lec_t1") || earnedMap.containsKey("lec_t2")
  301. || earnedMap.containsKey("lec_t3") || earnedMap.containsKey("lec_t4")) {
  302. grade.put("key", "lecturer");
  303. grade.put("name", "讲师");
  304. return grade;
  305. }
  306. // 系统师
  307. if (earnedMap.containsKey("course_system")) {
  308. grade.put("key", "system");
  309. grade.put("name", "系统师");
  310. return grade;
  311. }
  312. // 专精
  313. if (earnedMap.containsKey("course_wealth") || earnedMap.containsKey("course_health")
  314. || earnedMap.containsKey("course_growth")) {
  315. grade.put("key", "expert");
  316. grade.put("name", "专精");
  317. return grade;
  318. }
  319. // 启航
  320. if (earnedMap.containsKey("course_start")) {
  321. grade.put("key", "starter");
  322. grade.put("name", "启航");
  323. return grade;
  324. }
  325. // 见习(参加 ≥1 期活动:存在报名记录)
  326. Long enrollCount = trainEnrollmentMapper.selectCount(
  327. new LambdaQueryWrapper<TrainEnrollment>()
  328. .eq(TrainEnrollment::getUid, uid)
  329. .isNotNull(TrainEnrollment::getId));
  330. if (enrollCount != null && enrollCount > 0) {
  331. grade.put("key", "novice");
  332. grade.put("name", "见习");
  333. return grade;
  334. }
  335. // 未入门(无任何学习记录)
  336. return null;
  337. }
  338. // ========== 内部辅助 ==========
  339. private void insertUserBadge(Long uid, String badgeKey, String proof, Long grantedBy) {
  340. try {
  341. TrainUserBadge ub = new TrainUserBadge();
  342. ub.setUid(uid);
  343. ub.setBadgeKey(badgeKey);
  344. ub.setProof(proof);
  345. ub.setGrantedBy(grantedBy);
  346. ub.setEarnedAt(new Date());
  347. trainUserBadgeMapper.insert(ub);
  348. } catch (Exception e) {
  349. // 重复插入(uid+badge_key UNIQUE)被吞,属预期
  350. log.debug("用户 {} 颁发徽章 {} 失败(可能已存在): {}", uid, badgeKey, e.getMessage());
  351. }
  352. }
  353. }