AttendanceServiceImpl.java 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  1. package com.train.service.impl;
  2. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  3. import com.train.common.Result;
  4. import com.train.entity.TrainAttendance;
  5. import com.train.entity.TrainAttendanceCode;
  6. import com.train.entity.TrainCohort;
  7. import com.train.entity.TrainCohortSignup;
  8. import com.train.entity.TrainUser;
  9. import com.train.mapper.TrainAttendanceCodeMapper;
  10. import com.train.mapper.TrainAttendanceMapper;
  11. import com.train.mapper.TrainCohortMapper;
  12. import com.train.mapper.TrainCohortSignupMapper;
  13. import com.train.mapper.TrainUserMapper;
  14. import com.train.service.AttendanceService;
  15. import com.train.service.RoleGuard;
  16. import com.train.service.CreditService;
  17. import lombok.extern.slf4j.Slf4j;
  18. import org.springframework.beans.factory.annotation.Value;
  19. import org.springframework.stereotype.Service;
  20. import org.springframework.transaction.annotation.Transactional;
  21. import javax.annotation.Resource;
  22. import java.security.SecureRandom;
  23. import java.text.SimpleDateFormat;
  24. import java.util.ArrayList;
  25. import java.util.Calendar;
  26. import java.util.Date;
  27. import java.util.HashMap;
  28. import java.util.List;
  29. import java.util.Map;
  30. /**
  31. * 培训现场签到实现(动态码 + 反扫 + 台账入账)
  32. *
  33. * 关键口径:
  34. * - 一码=一场次(session);session_id = cohortId:seq,保证同批次多场次不串号
  35. * - 扫码校验:status='active' AND valid_to>=NOW()
  36. * - ★ scan 单事务:attendance(pending) + ledger(pending) 同事务;任一失败整体回滚
  37. * - 反扫幂等:attendance uk(user_id,session_id) 命中即返回,不重复入账
  38. */
  39. @Slf4j
  40. @Service
  41. public class AttendanceServiceImpl implements AttendanceService {
  42. private static final String ST_ACTIVE = "active";
  43. private static final String ST_ROTATED = "rotated";
  44. private static final String ST_REVOKE = "revoked";
  45. private static final String ST_PENDING = "pending";
  46. private static final String ST_EFFECTIVE = "effective";
  47. private static final String ST_OBJECTED = "objected";
  48. private static final String ST_REJECTED = "rejected";
  49. private static final String SRC_ATTENDANCE = "attendance";
  50. private static final String SIG_APPROVED = "approved";
  51. /** 契约错误码(proxy 字符串契约,勿改名):越权/不存在/并发冲突/同键异载荷 */
  52. private static final int CODE_FORBIDDEN = 403;
  53. private static final int CODE_NOT_FOUND = 404;
  54. private static final int CODE_VERSION_CONFLICT = 422;
  55. private static final int CODE_PAYLOAD_CONFLICT = 4092;
  56. private static final String CHAR_SET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"; // 去易混淆字符
  57. private static final SecureRandom RANDOM = new SecureRandom();
  58. @Resource
  59. private TrainAttendanceCodeMapper trainAttendanceCodeMapper;
  60. @Resource
  61. private TrainAttendanceMapper trainAttendanceMapper;
  62. @Resource
  63. private TrainCohortMapper trainCohortMapper;
  64. @Resource
  65. private TrainCohortSignupMapper trainCohortSignupMapper;
  66. @Resource
  67. private TrainUserMapper trainUserMapper;
  68. @Resource
  69. private CreditService creditService;
  70. @Resource
  71. private RoleGuard roleGuard;
  72. /** 签到码有效期(分钟,可配) */
  73. @Value("${app.attendance.code-valid-minutes:5}")
  74. private Integer codeValidMinutes;
  75. @Override
  76. @Transactional(rollbackFor = Exception.class)
  77. public Result<Map<String, Object>> issueCode(Boolean isAdmin, Long userId, String sessionId,
  78. Integer sessionHours, String category, String note) {
  79. // 权限三重校验:isAdmin | 任一 active 机构 org_admin/dispatcher | 该批次主讲讲师本人
  80. String noAuth = checkIssueAuth(isAdmin, userId, sessionId);
  81. if (noAuth != null) {
  82. return Result.error(CODE_FORBIDDEN, noAuth);
  83. }
  84. if (userId == null || sessionId == null || sessionId.trim().isEmpty()) {
  85. return Result.error("参数不完整");
  86. }
  87. // cohort_id 为 NOT NULL:sessionId 必须含可解析的 cohortId 前缀
  88. Long cohortId = parseCohortId(sessionId);
  89. if (cohortId == null) {
  90. return Result.error("场次ID格式不正确(应为 {批次ID}:{场次序号})");
  91. }
  92. if (trainCohortMapper.selectById(cohortId) == null) {
  93. return Result.error(CODE_NOT_FOUND, "批次不存在");
  94. }
  95. Date now = new Date();
  96. // 幂等:同 session 已有 active 且未过期 → 校验版本/载荷后复用,不重复发码
  97. TrainAttendanceCode active = trainAttendanceCodeMapper.selectOne(
  98. new LambdaQueryWrapper<TrainAttendanceCode>()
  99. .eq(TrainAttendanceCode::getSessionId, sessionId)
  100. .eq(TrainAttendanceCode::getStatus, ST_ACTIVE)
  101. .last("LIMIT 1"));
  102. boolean replacingExpired = false;
  103. if (active != null && active.getValidTo() != null && !active.getValidTo().before(now)) {
  104. Result<Map<String, Object>> conflict = checkReplayConflict(active, sessionHours, category, note);
  105. if (conflict != null) {
  106. return conflict;
  107. }
  108. return Result.success(codeVO(active));
  109. }
  110. if (active != null) {
  111. // 过期码不可幂等复用,必须轮换旧码并签发新码
  112. replacingExpired = true;
  113. }
  114. return doIssue(userId, sessionId, sessionHours, category, now, replacingExpired);
  115. }
  116. @Override
  117. @Transactional(rollbackFor = Exception.class)
  118. public Result<Map<String, Object>> rotateCode(Boolean isAdmin, Long userId, String sessionId,
  119. Integer sessionHours, String category, String note) {
  120. String noAuth = checkIssueAuth(isAdmin, userId, sessionId);
  121. if (noAuth != null) {
  122. return Result.error(noAuth);
  123. }
  124. if (userId == null || sessionId == null || sessionId.trim().isEmpty()) {
  125. return Result.error("参数不完整");
  126. }
  127. Long cohortId = parseCohortId(sessionId);
  128. if (cohortId == null) {
  129. return Result.error("场次ID格式不正确(应为 {批次ID}:{场次序号})");
  130. }
  131. if (trainCohortMapper.selectById(cohortId) == null) {
  132. return Result.error("批次不存在");
  133. }
  134. Date now = new Date();
  135. return doIssue(userId, sessionId, sessionHours, category, now, false);
  136. }
  137. /**
  138. * 发码权限校验(Service 方法内,非注解):
  139. * ① isAdmin=true 直接放行;
  140. * ② userId 是任一 active 机构成员(角色∈{org_admin,dispatcher},复用 RoleGuard.requireOrgManager);
  141. * ③ 或该 session 所属 batch 的 lecturer_id == userId(主讲讲师本人)。
  142. * 合法返回 null,越权返回中文 message。
  143. */
  144. private String checkIssueAuth(Boolean isAdmin, Long userId, String sessionId) {
  145. if (Boolean.TRUE.equals(isAdmin)) {
  146. return null;
  147. }
  148. if (userId == null) {
  149. return "需要登录";
  150. }
  151. Long cohortId = parseCohortId(sessionId);
  152. String orgErr = roleGuard.requireOrgManager(userId);
  153. if (orgErr == null) {
  154. return null;
  155. }
  156. // 兜底:主讲讲师本人
  157. if (cohortId != null) {
  158. TrainCohort cohort = trainCohortMapper.selectById(cohortId);
  159. if (cohort != null && cohort.getLecturerId() != null && cohort.getLecturerId().equals(userId)) {
  160. return null;
  161. }
  162. }
  163. return orgErr;
  164. }
  165. /**
  166. * 幂等重放冲突校验:同场次(幂等键)已有未过期 active 码时,重放必须维持相同载荷(C4092),
  167. * 且 note 携带的期望版本(version=N)必须与实体版本一致(C422)。合法返回 null。
  168. */
  169. private Result<Map<String, Object>> checkReplayConflict(TrainAttendanceCode active,
  170. Integer sessionHours, String category, String note) {
  171. Long expectedVersion = parseExpectedVersion(note);
  172. if (expectedVersion != null) {
  173. Long actualVersion = active.getVersion();
  174. if (actualVersion == null || !expectedVersion.equals(actualVersion)) {
  175. return Result.error(CODE_VERSION_CONFLICT, "签到码版本已变更,请重新发码");
  176. }
  177. }
  178. int hours = sessionHours == null || sessionHours <= 0 ? 480 : sessionHours;
  179. String cat = category == null || category.trim().isEmpty() ? "other" : category;
  180. int oldHours = active.getSessionHours() == null || active.getSessionHours() <= 0
  181. ? 480 : active.getSessionHours();
  182. String oldCat = active.getSessionCategory() == null || active.getSessionCategory().trim().isEmpty()
  183. ? "other" : active.getSessionCategory();
  184. if (oldHours != hours || !cat.equals(oldCat)) {
  185. return Result.error(CODE_PAYLOAD_CONFLICT, "同场次签到码学时/分类与本次请求不一致");
  186. }
  187. return null;
  188. }
  189. /** 从 note 解析期望版本号(version=N):未携带返回 null;携带但不可解析返回 -1(视为版本冲突)。 */
  190. private Long parseExpectedVersion(String note) {
  191. if (note == null) {
  192. return null;
  193. }
  194. int idx = note.indexOf("version=");
  195. if (idx < 0) {
  196. return null;
  197. }
  198. String tail = note.substring(idx + "version=".length()).trim();
  199. int end = 0;
  200. while (end < tail.length() && Character.isDigit(tail.charAt(end))) {
  201. end++;
  202. }
  203. if (end == 0) {
  204. return -1L;
  205. }
  206. try {
  207. return Long.valueOf(tail.substring(0, end));
  208. } catch (NumberFormatException e) {
  209. return -1L;
  210. }
  211. }
  212. /** 实际发码:轮换本 session 所有 active 旧码 + 新建 active 码 */
  213. private Result<Map<String, Object>> doIssue(Long userId, String sessionId, Integer sessionHours,
  214. String category, Date now, boolean replacingExpired) {
  215. Long cohortId = parseCohortId(sessionId);
  216. // 轮换旧码(active→rotated)
  217. List<TrainAttendanceCode> olds = trainAttendanceCodeMapper.selectList(
  218. new LambdaQueryWrapper<TrainAttendanceCode>()
  219. .eq(TrainAttendanceCode::getSessionId, sessionId)
  220. .eq(TrainAttendanceCode::getStatus, ST_ACTIVE));
  221. for (TrainAttendanceCode o : olds) {
  222. o.setStatus(ST_ROTATED);
  223. o.setRotatedBy(userId);
  224. o.setRotatedAt(now);
  225. o.setUpdatedAt(now);
  226. int affected = trainAttendanceCodeMapper.updateById(o);
  227. // 轮换未过期 active 码影响 0 行 = 并发丢失更新,必须 C422,不得静默发新码;
  228. // 过期码轮换影响 0 行可容忍(旧码本已失效,继续签发新码)。
  229. if (affected <= 0 && !replacingExpired
  230. && !(o.getValidTo() != null && o.getValidTo().before(now))) {
  231. return Result.error(CODE_VERSION_CONFLICT, "签到码轮换并发冲突,请重试");
  232. }
  233. }
  234. int hours = sessionHours == null || sessionHours <= 0 ? 480 : sessionHours; // 缺省 8h=480
  235. Date validTo = addMinutes(now, codeValidMinutes == null ? 5 : codeValidMinutes);
  236. TrainAttendanceCode c = build(sessionId, cohortId, hours,
  237. category == null || category.trim().isEmpty() ? "other" : category,
  238. userId, now, validTo);
  239. // 码碰撞重试(uk_session_status_code):极少发生,重试 3 次
  240. for (int i = 0; i < 3; i++) {
  241. try {
  242. trainAttendanceCodeMapper.insert(c);
  243. return Result.success(codeVO(c));
  244. } catch (Exception e) {
  245. log.debug("签到码碰撞重试: sessionId={}, attempt={}", sessionId, i + 1);
  246. c.setCode(generateCode());
  247. }
  248. }
  249. return Result.error("生成签到码失败,请重试");
  250. }
  251. @Override
  252. @Transactional(rollbackFor = Exception.class)
  253. public Result<Map<String, Object>> scan(Long userId, String code) {
  254. if (userId == null || code == null || code.trim().isEmpty()) {
  255. return Result.error("参数不完整");
  256. }
  257. Date now = new Date();
  258. // 1. 验码:status='active' AND valid_to>=NOW()
  259. TrainAttendanceCode c = trainAttendanceCodeMapper.selectOne(
  260. new LambdaQueryWrapper<TrainAttendanceCode>()
  261. .eq(TrainAttendanceCode::getCode, code.trim())
  262. .eq(TrainAttendanceCode::getStatus, ST_ACTIVE)
  263. .last("LIMIT 1"));
  264. if (c == null) {
  265. return Result.error("签到码无效");
  266. }
  267. if (c.getValidTo() != null && c.getValidTo().before(now)) {
  268. return Result.error("签到码已过期,请重新发码");
  269. }
  270. // 2. 校验报名:该用户须为所扫批次 approved 报名人
  271. TrainCohortSignup sig = trainCohortSignupMapper.selectOne(
  272. new LambdaQueryWrapper<TrainCohortSignup>()
  273. .eq(TrainCohortSignup::getUserId, userId)
  274. .eq(TrainCohortSignup::getCohortId, c.getCohortId())
  275. .eq(TrainCohortSignup::getStatus, SIG_APPROVED)
  276. .last("LIMIT 1"));
  277. if (sig == null) {
  278. return Result.error("未通过该批次报名审核,无法签到");
  279. }
  280. // 3. 反扫幂等:attendance uk(user_id,session_id)
  281. TrainAttendance exist = trainAttendanceMapper.selectOne(
  282. new LambdaQueryWrapper<TrainAttendance>()
  283. .eq(TrainAttendance::getUserId, userId)
  284. .eq(TrainAttendance::getSessionId, c.getSessionId())
  285. .eq(TrainAttendance::getDeleted, 0)
  286. .last("LIMIT 1"));
  287. if (exist != null) {
  288. // 已签到,返回已存在视图(幂等,不重复入账)
  289. return Result.success(attVO(exist, true));
  290. }
  291. // 4. 写 attendance(pending)
  292. int hours = c.getSessionHours() == null || c.getSessionHours() <= 0 ? 480 : c.getSessionHours();
  293. TrainAttendance att = new TrainAttendance();
  294. att.setUserId(userId);
  295. att.setCohortId(c.getCohortId());
  296. att.setSessionId(c.getSessionId());
  297. att.setCode(c.getCode());
  298. att.setSessionHours(hours);
  299. att.setSessionCategory(c.getSessionCategory() == null ? "other" : c.getSessionCategory());
  300. att.setAttendedAt(now);
  301. att.setSource("scan");
  302. att.setStatus(ST_PENDING);
  303. att.setDeleted(0);
  304. try {
  305. trainAttendanceMapper.insert(att);
  306. } catch (Exception e) {
  307. // uk 冲突(并发扫码)→ 幂等返回已存在
  308. TrainAttendance dup = trainAttendanceMapper.selectOne(
  309. new LambdaQueryWrapper<TrainAttendance>()
  310. .eq(TrainAttendance::getUserId, userId)
  311. .eq(TrainAttendance::getSessionId, c.getSessionId())
  312. .last("LIMIT 1"));
  313. if (dup != null) {
  314. return Result.success(attVO(dup, true));
  315. }
  316. return Result.error("签到失败,请重试");
  317. }
  318. // 5. 台账入账(pending,T+3 生效)—— 同事务
  319. creditService.ledgerPending(userId, SRC_ATTENDANCE, String.valueOf(att.getId()),
  320. att.getSessionCategory(), hours, "培训签到 " + c.getSessionId());
  321. return Result.success(attVO(att, false));
  322. }
  323. @Override
  324. public Result<List<Map<String, Object>>> mySessions(Long userId) {
  325. List<TrainAttendance> list = trainAttendanceMapper.selectList(
  326. new LambdaQueryWrapper<TrainAttendance>()
  327. .eq(TrainAttendance::getUserId, userId)
  328. .eq(TrainAttendance::getDeleted, 0)
  329. .orderByDesc(TrainAttendance::getAttendedAt));
  330. // 按 session 归并(同 session 多条取最新状态)
  331. Map<String, Map<String, Object>> merged = new HashMap<>();
  332. for (TrainAttendance a : list) {
  333. Map<String, Object> vo = attVO(a, false);
  334. merged.put(a.getSessionId(), vo);
  335. }
  336. List<Map<String, Object>> rows = new ArrayList<>(merged.values());
  337. return Result.success(rows);
  338. }
  339. @Override
  340. public Result<List<Map<String, Object>>> myAttendance(Long userId, Long cohortId) {
  341. LambdaQueryWrapper<TrainAttendance> q = new LambdaQueryWrapper<TrainAttendance>()
  342. .eq(TrainAttendance::getUserId, userId)
  343. .eq(TrainAttendance::getDeleted, 0)
  344. .orderByDesc(TrainAttendance::getAttendedAt);
  345. if (cohortId != null) {
  346. q.eq(TrainAttendance::getCohortId, cohortId);
  347. }
  348. List<TrainAttendance> list = trainAttendanceMapper.selectList(q);
  349. List<Map<String, Object>> rows = new ArrayList<>();
  350. for (TrainAttendance a : list) {
  351. rows.add(attVO(a, false));
  352. }
  353. return Result.success(rows);
  354. }
  355. @Override
  356. public Result<Map<String, Object>> pendingAttendance(Boolean isAdmin, Long cohortId, Integer page, Integer size) {
  357. String noAuth = roleGuard.requireAdminRole(isAdmin);
  358. if (noAuth != null) {
  359. return Result.error(noAuth);
  360. }
  361. int p = page == null || page < 1 ? 1 : page;
  362. int s = size == null || size < 1 ? 20 : Math.min(size, 100);
  363. int offset = (p - 1) * s;
  364. LambdaQueryWrapper<TrainAttendance> q = new LambdaQueryWrapper<TrainAttendance>()
  365. .eq(TrainAttendance::getStatus, ST_PENDING)
  366. .eq(TrainAttendance::getDeleted, 0);
  367. if (cohortId != null) {
  368. q.eq(TrainAttendance::getCohortId, cohortId);
  369. }
  370. Long total = trainAttendanceMapper.selectCount(q);
  371. List<TrainAttendance> list = trainAttendanceMapper.selectList(
  372. q.orderByDesc(TrainAttendance::getAttendedAt)
  373. .last("LIMIT " + offset + "," + s));
  374. List<Map<String, Object>> rows = new ArrayList<>();
  375. for (TrainAttendance a : list) {
  376. rows.add(attVO(a, false));
  377. }
  378. Map<String, Object> data = new HashMap<>();
  379. data.put("total", total == null ? 0 : total);
  380. data.put("page", p);
  381. data.put("size", s);
  382. data.put("list", rows);
  383. return Result.success(data);
  384. }
  385. @Override
  386. public Result<Map<String, Object>> adminList(Boolean isAdmin, Map<String, Object> body) {
  387. String noAuth = roleGuard.requireAdminRole(isAdmin);
  388. if (noAuth != null) {
  389. return Result.error(noAuth);
  390. }
  391. int p = body == null || toInt(body.get("page")) == null || toInt(body.get("page")) < 1 ? 1 : toInt(body.get("page"));
  392. int s = body == null || toInt(body.get("size")) == null || toInt(body.get("size")) < 1 ? 20 : Math.min(toInt(body.get("size")), 100);
  393. int offset = (p - 1) * s;
  394. Long cohortId = body == null ? null : toLong(body.get("cohortId"));
  395. String sessionId = body == null ? null : (body.get("sessionId") == null ? null : body.get("sessionId").toString().trim());
  396. String status = body == null ? null : (body.get("status") == null ? null : body.get("status").toString().trim());
  397. LambdaQueryWrapper<TrainAttendance> q = new LambdaQueryWrapper<TrainAttendance>()
  398. .eq(TrainAttendance::getDeleted, 0);
  399. if (cohortId != null) {
  400. q.eq(TrainAttendance::getCohortId, cohortId);
  401. }
  402. if (sessionId != null && !sessionId.isEmpty()) {
  403. q.eq(TrainAttendance::getSessionId, sessionId);
  404. }
  405. if (status != null && !status.isEmpty()) {
  406. q.eq(TrainAttendance::getStatus, status);
  407. }
  408. Long total = trainAttendanceMapper.selectCount(q);
  409. List<TrainAttendance> list = trainAttendanceMapper.selectList(
  410. q.orderByDesc(TrainAttendance::getAttendedAt).last("LIMIT " + offset + "," + s));
  411. List<Map<String, Object>> rows = new ArrayList<>();
  412. for (TrainAttendance a : list) {
  413. rows.add(adminAttVO(a));
  414. }
  415. Map<String, Object> data = new HashMap<>();
  416. data.put("total", total == null ? 0 : total);
  417. data.put("page", p);
  418. data.put("size", s);
  419. data.put("list", rows);
  420. return Result.success(data);
  421. }
  422. /** 管理端签到行 VO:复用 attVO(前端实际读取键)后补契约别名与联查字段 */
  423. private Map<String, Object> adminAttVO(TrainAttendance a) {
  424. Map<String, Object> m = attVO(a, false);
  425. m.put("id", a.getId());
  426. TrainUser u = a.getUserId() == null ? null : trainUserMapper.selectById(a.getUserId());
  427. m.put("userName", u == null ? null : u.getName());
  428. m.put("code", a.getCode());
  429. m.put("sessionHours", m.get("hours")); // 契约别名(=sessionHours)
  430. m.put("sessionCategory", m.get("category")); // 契约别名(=sessionCategory)
  431. return m;
  432. }
  433. // ============ helpers ============
  434. private Map<String, Object> attVO(TrainAttendance a, boolean alreadyExists) {
  435. Map<String, Object> m = new HashMap<>();
  436. m.put("attendanceId", a.getId());
  437. m.put("userId", a.getUserId());
  438. m.put("cohortId", a.getCohortId());
  439. m.put("sessionId", a.getSessionId());
  440. m.put("hours", a.getSessionHours() == null ? 0 : a.getSessionHours()); // 分钟
  441. m.put("category", a.getSessionCategory());
  442. m.put("attendedAt", a.getAttendedAt());
  443. // 修复2:前端契约键 attended(bool) / time('yyyy-MM-dd HH:mm'),保留 attendedAt
  444. m.put("attended", !ST_REJECTED.equals(a.getStatus())); // 非 rejected 视为已出勤
  445. m.put("time", formatTime(a.getAttendedAt()));
  446. m.put("status", a.getStatus());
  447. m.put("source", a.getSource());
  448. m.put("effectiveAt", a.getEffectiveAt());
  449. m.put("alreadyExists", alreadyExists);
  450. return m;
  451. }
  452. private Map<String, Object> codeVO(TrainAttendanceCode c) {
  453. Map<String, Object> m = new HashMap<>();
  454. m.put("codeId", c.getId());
  455. m.put("cohortId", c.getCohortId());
  456. m.put("sessionId", c.getSessionId());
  457. m.put("code", c.getCode());
  458. m.put("hours", c.getSessionHours() == null ? 0 : c.getSessionHours()); // 分钟
  459. m.put("category", c.getSessionCategory());
  460. m.put("validFrom", c.getValidFrom());
  461. m.put("validTo", c.getValidTo());
  462. m.put("expireAt", c.getValidTo());
  463. m.put("status", c.getStatus());
  464. // 修复3:展示辅助键(前端 qr.vue 绑定 name/cohortName/startAt/endAt)
  465. TrainCohort cohort = c.getCohortId() == null ? null : trainCohortMapper.selectById(c.getCohortId());
  466. if (cohort != null) {
  467. m.put("cohortName", cohort.getName() == null ? "" : cohort.getName());
  468. m.put("startAt", cohort.getStartAt());
  469. m.put("endAt", cohort.getEndAt());
  470. String seq = parseSeq(c.getSessionId());
  471. m.put("sessionName", cohort.getName() + (seq == null ? " 现场签到" : " 第" + seq + "次课"));
  472. } else {
  473. m.put("cohortName", "");
  474. m.put("startAt", null);
  475. m.put("endAt", null);
  476. m.put("sessionName", "现场签到");
  477. }
  478. return m;
  479. }
  480. /** 时间格式化为 'yyyy-MM-dd HH:mm'(可空) */
  481. private String formatTime(Date d) {
  482. if (d == null) {
  483. return null;
  484. }
  485. return new SimpleDateFormat("yyyy-MM-dd HH:mm").format(d);
  486. }
  487. /** 从 sessionId({cohortId}:{seq} 或 {cohortId}-{seq})取场次序号,解析失败返回 null */
  488. private String parseSeq(String sessionId) {
  489. if (sessionId == null) {
  490. return null;
  491. }
  492. int idx = sessionId.indexOf(':');
  493. if (idx < 0) {
  494. idx = sessionId.indexOf('-');
  495. }
  496. if (idx < 0 || idx + 1 >= sessionId.length()) {
  497. return null;
  498. }
  499. String tail = sessionId.substring(idx + 1).trim();
  500. return tail.isEmpty() ? null : tail;
  501. }
  502. private Long parseCohortId(String sessionId) {
  503. if (sessionId == null) {
  504. return null;
  505. }
  506. int idx = sessionId.indexOf(':');
  507. if (idx <= 0) {
  508. idx = sessionId.indexOf('-');
  509. }
  510. String head = idx > 0 ? sessionId.substring(0, idx) : sessionId;
  511. try {
  512. return Long.valueOf(head.trim());
  513. } catch (NumberFormatException e) {
  514. return null;
  515. }
  516. }
  517. private String generateCode() {
  518. StringBuilder sb = new StringBuilder(8);
  519. for (int i = 0; i < 8; i++) {
  520. sb.append(CHAR_SET.charAt(RANDOM.nextInt(CHAR_SET.length())));
  521. }
  522. return sb.toString();
  523. }
  524. private Long toLong(Object v) {
  525. if (v == null) {
  526. return null;
  527. }
  528. try {
  529. return Long.valueOf(v.toString().trim());
  530. } catch (NumberFormatException e) {
  531. return null;
  532. }
  533. }
  534. private Integer toInt(Object v) {
  535. if (v == null) {
  536. return null;
  537. }
  538. try {
  539. return Integer.valueOf(v.toString().trim());
  540. } catch (NumberFormatException e) {
  541. return null;
  542. }
  543. }
  544. private Date addMinutes(Date base, int minutes) {
  545. Calendar cal = Calendar.getInstance();
  546. cal.setTime(base);
  547. cal.add(Calendar.MINUTE, minutes);
  548. return cal.getTime();
  549. }
  550. private TrainAttendanceCode build(String sessionId, Long cohortId, int hours, String category,
  551. Long userId, Date from, Date to) {
  552. TrainAttendanceCode c = new TrainAttendanceCode();
  553. c.setSessionId(sessionId);
  554. c.setCohortId(cohortId);
  555. c.setCode(generateCode());
  556. c.setSessionHours(hours);
  557. c.setSessionCategory(category);
  558. c.setIssuedBy(userId);
  559. c.setValidFrom(from);
  560. c.setValidTo(to);
  561. c.setStatus(ST_ACTIVE);
  562. c.setVersion(0L); // 乐观锁初始版本
  563. return c;
  564. }
  565. }