| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596 |
- package com.train.service.impl;
- import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
- import com.train.common.Result;
- import com.train.entity.TrainAttendance;
- import com.train.entity.TrainAttendanceCode;
- import com.train.entity.TrainCohort;
- import com.train.entity.TrainCohortSignup;
- import com.train.entity.TrainUser;
- import com.train.mapper.TrainAttendanceCodeMapper;
- import com.train.mapper.TrainAttendanceMapper;
- import com.train.mapper.TrainCohortMapper;
- import com.train.mapper.TrainCohortSignupMapper;
- import com.train.mapper.TrainUserMapper;
- import com.train.service.AttendanceService;
- import com.train.service.RoleGuard;
- import com.train.service.CreditService;
- import lombok.extern.slf4j.Slf4j;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.stereotype.Service;
- import org.springframework.transaction.annotation.Transactional;
- import javax.annotation.Resource;
- import java.security.SecureRandom;
- import java.text.SimpleDateFormat;
- import java.util.ArrayList;
- import java.util.Calendar;
- import java.util.Date;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- /**
- * 培训现场签到实现(动态码 + 反扫 + 台账入账)
- *
- * 关键口径:
- * - 一码=一场次(session);session_id = cohortId:seq,保证同批次多场次不串号
- * - 扫码校验:status='active' AND valid_to>=NOW()
- * - ★ scan 单事务:attendance(pending) + ledger(pending) 同事务;任一失败整体回滚
- * - 反扫幂等:attendance uk(user_id,session_id) 命中即返回,不重复入账
- */
- @Slf4j
- @Service
- public class AttendanceServiceImpl implements AttendanceService {
- private static final String ST_ACTIVE = "active";
- private static final String ST_ROTATED = "rotated";
- private static final String ST_REVOKE = "revoked";
- private static final String ST_PENDING = "pending";
- private static final String ST_EFFECTIVE = "effective";
- private static final String ST_OBJECTED = "objected";
- private static final String ST_REJECTED = "rejected";
- private static final String SRC_ATTENDANCE = "attendance";
- private static final String SIG_APPROVED = "approved";
- /** 契约错误码(proxy 字符串契约,勿改名):越权/不存在/并发冲突/同键异载荷 */
- private static final int CODE_FORBIDDEN = 403;
- private static final int CODE_NOT_FOUND = 404;
- private static final int CODE_VERSION_CONFLICT = 422;
- private static final int CODE_PAYLOAD_CONFLICT = 4092;
- private static final String CHAR_SET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"; // 去易混淆字符
- private static final SecureRandom RANDOM = new SecureRandom();
- @Resource
- private TrainAttendanceCodeMapper trainAttendanceCodeMapper;
- @Resource
- private TrainAttendanceMapper trainAttendanceMapper;
- @Resource
- private TrainCohortMapper trainCohortMapper;
- @Resource
- private TrainCohortSignupMapper trainCohortSignupMapper;
- @Resource
- private TrainUserMapper trainUserMapper;
- @Resource
- private CreditService creditService;
- @Resource
- private RoleGuard roleGuard;
- /** 签到码有效期(分钟,可配) */
- @Value("${app.attendance.code-valid-minutes:5}")
- private Integer codeValidMinutes;
- @Override
- @Transactional(rollbackFor = Exception.class)
- public Result<Map<String, Object>> issueCode(Boolean isAdmin, Long userId, String sessionId,
- Integer sessionHours, String category, String note) {
- // 权限三重校验:isAdmin | 任一 active 机构 org_admin/dispatcher | 该批次主讲讲师本人
- String noAuth = checkIssueAuth(isAdmin, userId, sessionId);
- if (noAuth != null) {
- return Result.error(CODE_FORBIDDEN, noAuth);
- }
- if (userId == null || sessionId == null || sessionId.trim().isEmpty()) {
- return Result.error("参数不完整");
- }
- // cohort_id 为 NOT NULL:sessionId 必须含可解析的 cohortId 前缀
- Long cohortId = parseCohortId(sessionId);
- if (cohortId == null) {
- return Result.error("场次ID格式不正确(应为 {批次ID}:{场次序号})");
- }
- if (trainCohortMapper.selectById(cohortId) == null) {
- return Result.error(CODE_NOT_FOUND, "批次不存在");
- }
- Date now = new Date();
- // 幂等:同 session 已有 active 且未过期 → 校验版本/载荷后复用,不重复发码
- TrainAttendanceCode active = trainAttendanceCodeMapper.selectOne(
- new LambdaQueryWrapper<TrainAttendanceCode>()
- .eq(TrainAttendanceCode::getSessionId, sessionId)
- .eq(TrainAttendanceCode::getStatus, ST_ACTIVE)
- .last("LIMIT 1"));
- boolean replacingExpired = false;
- if (active != null && active.getValidTo() != null && !active.getValidTo().before(now)) {
- Result<Map<String, Object>> conflict = checkReplayConflict(active, sessionHours, category, note);
- if (conflict != null) {
- return conflict;
- }
- return Result.success(codeVO(active));
- }
- if (active != null) {
- // 过期码不可幂等复用,必须轮换旧码并签发新码
- replacingExpired = true;
- }
- return doIssue(userId, sessionId, sessionHours, category, now, replacingExpired);
- }
- @Override
- @Transactional(rollbackFor = Exception.class)
- public Result<Map<String, Object>> rotateCode(Boolean isAdmin, Long userId, String sessionId,
- Integer sessionHours, String category, String note) {
- String noAuth = checkIssueAuth(isAdmin, userId, sessionId);
- if (noAuth != null) {
- return Result.error(noAuth);
- }
- if (userId == null || sessionId == null || sessionId.trim().isEmpty()) {
- return Result.error("参数不完整");
- }
- Long cohortId = parseCohortId(sessionId);
- if (cohortId == null) {
- return Result.error("场次ID格式不正确(应为 {批次ID}:{场次序号})");
- }
- if (trainCohortMapper.selectById(cohortId) == null) {
- return Result.error("批次不存在");
- }
- Date now = new Date();
- return doIssue(userId, sessionId, sessionHours, category, now, false);
- }
- /**
- * 发码权限校验(Service 方法内,非注解):
- * ① isAdmin=true 直接放行;
- * ② userId 是任一 active 机构成员(角色∈{org_admin,dispatcher},复用 RoleGuard.requireOrgManager);
- * ③ 或该 session 所属 batch 的 lecturer_id == userId(主讲讲师本人)。
- * 合法返回 null,越权返回中文 message。
- */
- private String checkIssueAuth(Boolean isAdmin, Long userId, String sessionId) {
- if (Boolean.TRUE.equals(isAdmin)) {
- return null;
- }
- if (userId == null) {
- return "需要登录";
- }
- Long cohortId = parseCohortId(sessionId);
- String orgErr = roleGuard.requireOrgManager(userId);
- if (orgErr == null) {
- return null;
- }
- // 兜底:主讲讲师本人
- if (cohortId != null) {
- TrainCohort cohort = trainCohortMapper.selectById(cohortId);
- if (cohort != null && cohort.getLecturerId() != null && cohort.getLecturerId().equals(userId)) {
- return null;
- }
- }
- return orgErr;
- }
- /**
- * 幂等重放冲突校验:同场次(幂等键)已有未过期 active 码时,重放必须维持相同载荷(C4092),
- * 且 note 携带的期望版本(version=N)必须与实体版本一致(C422)。合法返回 null。
- */
- private Result<Map<String, Object>> checkReplayConflict(TrainAttendanceCode active,
- Integer sessionHours, String category, String note) {
- Long expectedVersion = parseExpectedVersion(note);
- if (expectedVersion != null) {
- Long actualVersion = active.getVersion();
- if (actualVersion == null || !expectedVersion.equals(actualVersion)) {
- return Result.error(CODE_VERSION_CONFLICT, "签到码版本已变更,请重新发码");
- }
- }
- int hours = sessionHours == null || sessionHours <= 0 ? 480 : sessionHours;
- String cat = category == null || category.trim().isEmpty() ? "other" : category;
- int oldHours = active.getSessionHours() == null || active.getSessionHours() <= 0
- ? 480 : active.getSessionHours();
- String oldCat = active.getSessionCategory() == null || active.getSessionCategory().trim().isEmpty()
- ? "other" : active.getSessionCategory();
- if (oldHours != hours || !cat.equals(oldCat)) {
- return Result.error(CODE_PAYLOAD_CONFLICT, "同场次签到码学时/分类与本次请求不一致");
- }
- return null;
- }
- /** 从 note 解析期望版本号(version=N):未携带返回 null;携带但不可解析返回 -1(视为版本冲突)。 */
- private Long parseExpectedVersion(String note) {
- if (note == null) {
- return null;
- }
- int idx = note.indexOf("version=");
- if (idx < 0) {
- return null;
- }
- String tail = note.substring(idx + "version=".length()).trim();
- int end = 0;
- while (end < tail.length() && Character.isDigit(tail.charAt(end))) {
- end++;
- }
- if (end == 0) {
- return -1L;
- }
- try {
- return Long.valueOf(tail.substring(0, end));
- } catch (NumberFormatException e) {
- return -1L;
- }
- }
- /** 实际发码:轮换本 session 所有 active 旧码 + 新建 active 码 */
- private Result<Map<String, Object>> doIssue(Long userId, String sessionId, Integer sessionHours,
- String category, Date now, boolean replacingExpired) {
- Long cohortId = parseCohortId(sessionId);
- // 轮换旧码(active→rotated)
- List<TrainAttendanceCode> olds = trainAttendanceCodeMapper.selectList(
- new LambdaQueryWrapper<TrainAttendanceCode>()
- .eq(TrainAttendanceCode::getSessionId, sessionId)
- .eq(TrainAttendanceCode::getStatus, ST_ACTIVE));
- for (TrainAttendanceCode o : olds) {
- o.setStatus(ST_ROTATED);
- o.setRotatedBy(userId);
- o.setRotatedAt(now);
- o.setUpdatedAt(now);
- int affected = trainAttendanceCodeMapper.updateById(o);
- // 轮换未过期 active 码影响 0 行 = 并发丢失更新,必须 C422,不得静默发新码;
- // 过期码轮换影响 0 行可容忍(旧码本已失效,继续签发新码)。
- if (affected <= 0 && !replacingExpired
- && !(o.getValidTo() != null && o.getValidTo().before(now))) {
- return Result.error(CODE_VERSION_CONFLICT, "签到码轮换并发冲突,请重试");
- }
- }
- int hours = sessionHours == null || sessionHours <= 0 ? 480 : sessionHours; // 缺省 8h=480
- Date validTo = addMinutes(now, codeValidMinutes == null ? 5 : codeValidMinutes);
- TrainAttendanceCode c = build(sessionId, cohortId, hours,
- category == null || category.trim().isEmpty() ? "other" : category,
- userId, now, validTo);
- // 码碰撞重试(uk_session_status_code):极少发生,重试 3 次
- for (int i = 0; i < 3; i++) {
- try {
- trainAttendanceCodeMapper.insert(c);
- return Result.success(codeVO(c));
- } catch (Exception e) {
- log.debug("签到码碰撞重试: sessionId={}, attempt={}", sessionId, i + 1);
- c.setCode(generateCode());
- }
- }
- return Result.error("生成签到码失败,请重试");
- }
- @Override
- @Transactional(rollbackFor = Exception.class)
- public Result<Map<String, Object>> scan(Long userId, String code) {
- if (userId == null || code == null || code.trim().isEmpty()) {
- return Result.error("参数不完整");
- }
- Date now = new Date();
- // 1. 验码:status='active' AND valid_to>=NOW()
- TrainAttendanceCode c = trainAttendanceCodeMapper.selectOne(
- new LambdaQueryWrapper<TrainAttendanceCode>()
- .eq(TrainAttendanceCode::getCode, code.trim())
- .eq(TrainAttendanceCode::getStatus, ST_ACTIVE)
- .last("LIMIT 1"));
- if (c == null) {
- return Result.error("签到码无效");
- }
- if (c.getValidTo() != null && c.getValidTo().before(now)) {
- return Result.error("签到码已过期,请重新发码");
- }
- // 2. 校验报名:该用户须为所扫批次 approved 报名人
- TrainCohortSignup sig = trainCohortSignupMapper.selectOne(
- new LambdaQueryWrapper<TrainCohortSignup>()
- .eq(TrainCohortSignup::getUserId, userId)
- .eq(TrainCohortSignup::getCohortId, c.getCohortId())
- .eq(TrainCohortSignup::getStatus, SIG_APPROVED)
- .last("LIMIT 1"));
- if (sig == null) {
- return Result.error("未通过该批次报名审核,无法签到");
- }
- // 3. 反扫幂等:attendance uk(user_id,session_id)
- TrainAttendance exist = trainAttendanceMapper.selectOne(
- new LambdaQueryWrapper<TrainAttendance>()
- .eq(TrainAttendance::getUserId, userId)
- .eq(TrainAttendance::getSessionId, c.getSessionId())
- .eq(TrainAttendance::getDeleted, 0)
- .last("LIMIT 1"));
- if (exist != null) {
- // 已签到,返回已存在视图(幂等,不重复入账)
- return Result.success(attVO(exist, true));
- }
- // 4. 写 attendance(pending)
- int hours = c.getSessionHours() == null || c.getSessionHours() <= 0 ? 480 : c.getSessionHours();
- TrainAttendance att = new TrainAttendance();
- att.setUserId(userId);
- att.setCohortId(c.getCohortId());
- att.setSessionId(c.getSessionId());
- att.setCode(c.getCode());
- att.setSessionHours(hours);
- att.setSessionCategory(c.getSessionCategory() == null ? "other" : c.getSessionCategory());
- att.setAttendedAt(now);
- att.setSource("scan");
- att.setStatus(ST_PENDING);
- att.setDeleted(0);
- try {
- trainAttendanceMapper.insert(att);
- } catch (Exception e) {
- // uk 冲突(并发扫码)→ 幂等返回已存在
- TrainAttendance dup = trainAttendanceMapper.selectOne(
- new LambdaQueryWrapper<TrainAttendance>()
- .eq(TrainAttendance::getUserId, userId)
- .eq(TrainAttendance::getSessionId, c.getSessionId())
- .last("LIMIT 1"));
- if (dup != null) {
- return Result.success(attVO(dup, true));
- }
- return Result.error("签到失败,请重试");
- }
- // 5. 台账入账(pending,T+3 生效)—— 同事务
- creditService.ledgerPending(userId, SRC_ATTENDANCE, String.valueOf(att.getId()),
- att.getSessionCategory(), hours, "培训签到 " + c.getSessionId());
- return Result.success(attVO(att, false));
- }
- @Override
- public Result<List<Map<String, Object>>> mySessions(Long userId) {
- List<TrainAttendance> list = trainAttendanceMapper.selectList(
- new LambdaQueryWrapper<TrainAttendance>()
- .eq(TrainAttendance::getUserId, userId)
- .eq(TrainAttendance::getDeleted, 0)
- .orderByDesc(TrainAttendance::getAttendedAt));
- // 按 session 归并(同 session 多条取最新状态)
- Map<String, Map<String, Object>> merged = new HashMap<>();
- for (TrainAttendance a : list) {
- Map<String, Object> vo = attVO(a, false);
- merged.put(a.getSessionId(), vo);
- }
- List<Map<String, Object>> rows = new ArrayList<>(merged.values());
- return Result.success(rows);
- }
- @Override
- public Result<List<Map<String, Object>>> myAttendance(Long userId, Long cohortId) {
- LambdaQueryWrapper<TrainAttendance> q = new LambdaQueryWrapper<TrainAttendance>()
- .eq(TrainAttendance::getUserId, userId)
- .eq(TrainAttendance::getDeleted, 0)
- .orderByDesc(TrainAttendance::getAttendedAt);
- if (cohortId != null) {
- q.eq(TrainAttendance::getCohortId, cohortId);
- }
- List<TrainAttendance> list = trainAttendanceMapper.selectList(q);
- List<Map<String, Object>> rows = new ArrayList<>();
- for (TrainAttendance a : list) {
- rows.add(attVO(a, false));
- }
- return Result.success(rows);
- }
- @Override
- public Result<Map<String, Object>> pendingAttendance(Boolean isAdmin, Long cohortId, Integer page, Integer size) {
- String noAuth = roleGuard.requireAdminRole(isAdmin);
- if (noAuth != null) {
- return Result.error(noAuth);
- }
- int p = page == null || page < 1 ? 1 : page;
- int s = size == null || size < 1 ? 20 : Math.min(size, 100);
- int offset = (p - 1) * s;
- LambdaQueryWrapper<TrainAttendance> q = new LambdaQueryWrapper<TrainAttendance>()
- .eq(TrainAttendance::getStatus, ST_PENDING)
- .eq(TrainAttendance::getDeleted, 0);
- if (cohortId != null) {
- q.eq(TrainAttendance::getCohortId, cohortId);
- }
- Long total = trainAttendanceMapper.selectCount(q);
- List<TrainAttendance> list = trainAttendanceMapper.selectList(
- q.orderByDesc(TrainAttendance::getAttendedAt)
- .last("LIMIT " + offset + "," + s));
- List<Map<String, Object>> rows = new ArrayList<>();
- for (TrainAttendance a : list) {
- rows.add(attVO(a, false));
- }
- Map<String, Object> data = new HashMap<>();
- data.put("total", total == null ? 0 : total);
- data.put("page", p);
- data.put("size", s);
- data.put("list", rows);
- return Result.success(data);
- }
- @Override
- public Result<Map<String, Object>> adminList(Boolean isAdmin, Map<String, Object> body) {
- String noAuth = roleGuard.requireAdminRole(isAdmin);
- if (noAuth != null) {
- return Result.error(noAuth);
- }
- int p = body == null || toInt(body.get("page")) == null || toInt(body.get("page")) < 1 ? 1 : toInt(body.get("page"));
- int s = body == null || toInt(body.get("size")) == null || toInt(body.get("size")) < 1 ? 20 : Math.min(toInt(body.get("size")), 100);
- int offset = (p - 1) * s;
- Long cohortId = body == null ? null : toLong(body.get("cohortId"));
- String sessionId = body == null ? null : (body.get("sessionId") == null ? null : body.get("sessionId").toString().trim());
- String status = body == null ? null : (body.get("status") == null ? null : body.get("status").toString().trim());
- LambdaQueryWrapper<TrainAttendance> q = new LambdaQueryWrapper<TrainAttendance>()
- .eq(TrainAttendance::getDeleted, 0);
- if (cohortId != null) {
- q.eq(TrainAttendance::getCohortId, cohortId);
- }
- if (sessionId != null && !sessionId.isEmpty()) {
- q.eq(TrainAttendance::getSessionId, sessionId);
- }
- if (status != null && !status.isEmpty()) {
- q.eq(TrainAttendance::getStatus, status);
- }
- Long total = trainAttendanceMapper.selectCount(q);
- List<TrainAttendance> list = trainAttendanceMapper.selectList(
- q.orderByDesc(TrainAttendance::getAttendedAt).last("LIMIT " + offset + "," + s));
- List<Map<String, Object>> rows = new ArrayList<>();
- for (TrainAttendance a : list) {
- rows.add(adminAttVO(a));
- }
- Map<String, Object> data = new HashMap<>();
- data.put("total", total == null ? 0 : total);
- data.put("page", p);
- data.put("size", s);
- data.put("list", rows);
- return Result.success(data);
- }
- /** 管理端签到行 VO:复用 attVO(前端实际读取键)后补契约别名与联查字段 */
- private Map<String, Object> adminAttVO(TrainAttendance a) {
- Map<String, Object> m = attVO(a, false);
- m.put("id", a.getId());
- TrainUser u = a.getUserId() == null ? null : trainUserMapper.selectById(a.getUserId());
- m.put("userName", u == null ? null : u.getName());
- m.put("code", a.getCode());
- m.put("sessionHours", m.get("hours")); // 契约别名(=sessionHours)
- m.put("sessionCategory", m.get("category")); // 契约别名(=sessionCategory)
- return m;
- }
- // ============ helpers ============
- private Map<String, Object> attVO(TrainAttendance a, boolean alreadyExists) {
- Map<String, Object> m = new HashMap<>();
- m.put("attendanceId", a.getId());
- m.put("userId", a.getUserId());
- m.put("cohortId", a.getCohortId());
- m.put("sessionId", a.getSessionId());
- m.put("hours", a.getSessionHours() == null ? 0 : a.getSessionHours()); // 分钟
- m.put("category", a.getSessionCategory());
- m.put("attendedAt", a.getAttendedAt());
- // 修复2:前端契约键 attended(bool) / time('yyyy-MM-dd HH:mm'),保留 attendedAt
- m.put("attended", !ST_REJECTED.equals(a.getStatus())); // 非 rejected 视为已出勤
- m.put("time", formatTime(a.getAttendedAt()));
- m.put("status", a.getStatus());
- m.put("source", a.getSource());
- m.put("effectiveAt", a.getEffectiveAt());
- m.put("alreadyExists", alreadyExists);
- return m;
- }
- private Map<String, Object> codeVO(TrainAttendanceCode c) {
- Map<String, Object> m = new HashMap<>();
- m.put("codeId", c.getId());
- m.put("cohortId", c.getCohortId());
- m.put("sessionId", c.getSessionId());
- m.put("code", c.getCode());
- m.put("hours", c.getSessionHours() == null ? 0 : c.getSessionHours()); // 分钟
- m.put("category", c.getSessionCategory());
- m.put("validFrom", c.getValidFrom());
- m.put("validTo", c.getValidTo());
- m.put("expireAt", c.getValidTo());
- m.put("status", c.getStatus());
- // 修复3:展示辅助键(前端 qr.vue 绑定 name/cohortName/startAt/endAt)
- TrainCohort cohort = c.getCohortId() == null ? null : trainCohortMapper.selectById(c.getCohortId());
- if (cohort != null) {
- m.put("cohortName", cohort.getName() == null ? "" : cohort.getName());
- m.put("startAt", cohort.getStartAt());
- m.put("endAt", cohort.getEndAt());
- String seq = parseSeq(c.getSessionId());
- m.put("sessionName", cohort.getName() + (seq == null ? " 现场签到" : " 第" + seq + "次课"));
- } else {
- m.put("cohortName", "");
- m.put("startAt", null);
- m.put("endAt", null);
- m.put("sessionName", "现场签到");
- }
- return m;
- }
- /** 时间格式化为 'yyyy-MM-dd HH:mm'(可空) */
- private String formatTime(Date d) {
- if (d == null) {
- return null;
- }
- return new SimpleDateFormat("yyyy-MM-dd HH:mm").format(d);
- }
- /** 从 sessionId({cohortId}:{seq} 或 {cohortId}-{seq})取场次序号,解析失败返回 null */
- private String parseSeq(String sessionId) {
- if (sessionId == null) {
- return null;
- }
- int idx = sessionId.indexOf(':');
- if (idx < 0) {
- idx = sessionId.indexOf('-');
- }
- if (idx < 0 || idx + 1 >= sessionId.length()) {
- return null;
- }
- String tail = sessionId.substring(idx + 1).trim();
- return tail.isEmpty() ? null : tail;
- }
- private Long parseCohortId(String sessionId) {
- if (sessionId == null) {
- return null;
- }
- int idx = sessionId.indexOf(':');
- if (idx <= 0) {
- idx = sessionId.indexOf('-');
- }
- String head = idx > 0 ? sessionId.substring(0, idx) : sessionId;
- try {
- return Long.valueOf(head.trim());
- } catch (NumberFormatException e) {
- return null;
- }
- }
- private String generateCode() {
- StringBuilder sb = new StringBuilder(8);
- for (int i = 0; i < 8; i++) {
- sb.append(CHAR_SET.charAt(RANDOM.nextInt(CHAR_SET.length())));
- }
- return sb.toString();
- }
- private Long toLong(Object v) {
- if (v == null) {
- return null;
- }
- try {
- return Long.valueOf(v.toString().trim());
- } catch (NumberFormatException e) {
- return null;
- }
- }
- private Integer toInt(Object v) {
- if (v == null) {
- return null;
- }
- try {
- return Integer.valueOf(v.toString().trim());
- } catch (NumberFormatException e) {
- return null;
- }
- }
- private Date addMinutes(Date base, int minutes) {
- Calendar cal = Calendar.getInstance();
- cal.setTime(base);
- cal.add(Calendar.MINUTE, minutes);
- return cal.getTime();
- }
- private TrainAttendanceCode build(String sessionId, Long cohortId, int hours, String category,
- Long userId, Date from, Date to) {
- TrainAttendanceCode c = new TrainAttendanceCode();
- c.setSessionId(sessionId);
- c.setCohortId(cohortId);
- c.setCode(generateCode());
- c.setSessionHours(hours);
- c.setSessionCategory(category);
- c.setIssuedBy(userId);
- c.setValidFrom(from);
- c.setValidTo(to);
- c.setStatus(ST_ACTIVE);
- c.setVersion(0L); // 乐观锁初始版本
- return c;
- }
- }
|