Browse Source

feat(train-backend): M2 培训主线后端落地(批次/签到/学时/cfc回填)

新增 CohortService、AttendanceService、CreditService、CfcCreditSyncService、CreditEffectiveManager 及 6 个 Controller(学员 3 + 管理端 3)与 3 个 Impl。

要点:
- 学时一律分钟整数(对外 API 禁 /60),口径对齐主理人 2026-11-23 裁决
- signup/scan 幂等 + @Transactional:signup 三步(插 cohort_signup → 容量校验 → upsert train_enrollment 置 confirmed);scan 同事务写 train_attendance + ledgerPending
- 签到码有效期可配 app.attendance.code-valid-minutes(默认 5 分钟),issueCode 同 session 幂等复用活跃码
- effectiveDue/rollBackObjected 全量到期扫描(禁限定当天)+ 逐条独立事务(@Lazy 自注入代理绕过 self-invocation)
- CfcCreditSyncService 经 com.train.cfc 方言 Mapper 直连 + train_cfc_sync_log 幂等对账(syncKey=sourceType:sourceId,失败 warn 不阻塞,重试至 retry-max)
- 分页全部手写 LIMIT/OFFSET + selectCount(项目无 MP PaginationInnerInterceptor)
- application.yml 新增 code-valid-minutes / effective-delay-hours / credit-sync.retry-max / task.credit-scan-cron

mvn clean compile → BUILD SUCCESS
liaoxg 2 days ago
parent
commit
a3cb6fb296

+ 77 - 0
train-backend/src/main/java/com/train/controller/AttendanceController.java

@@ -0,0 +1,77 @@
+package com.train.controller;
+
+import com.train.common.Result;
+import com.train.service.AttendanceService;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestAttribute;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * 培训签到 Controller(学员侧)
+ *
+ * - scan ★:反扫签到码,幂等(同场次重复扫码不重复入账)
+ * - 统一 @PostMapping;必须本人(@RequestAttribute("userId"))
+ */
+@Tag(name = "培训签到", description = "扫码签到(幂等)/ 我的场次 / 我的签到记录")
+@RestController
+@RequestMapping("/api/attendance")
+public class AttendanceController {
+
+    @Resource
+    private AttendanceService attendanceService;
+
+    /**
+     * 反扫签到
+     * body: {code}
+     * 出参: {attendanceId, cohortId, sessionId, hours(分钟), category, status, attendedAt}
+     */
+    @Operation(summary = "扫码签到(幂等)")
+    @PostMapping("/scan")
+    public Result<Map<String, Object>> scan(
+            @RequestAttribute("userId") Long userId,
+            @RequestBody(required = false) Map<String, Object> body) {
+        String code = body == null || body.get("code") == null ? null : body.get("code").toString().trim();
+        return attendanceService.scan(userId, code);
+    }
+
+    /**
+     * 我的场次列表(按 session 归并,含学时快照)。
+     */
+    @Operation(summary = "我的场次列表")
+    @PostMapping("/mySessions")
+    public Result<List<Map<String, Object>>> mySessions(@RequestAttribute("userId") Long userId) {
+        return attendanceService.mySessions(userId);
+    }
+
+    /**
+     * 我的签到记录(可按批次过滤)
+     * body: {cohortId?}
+     */
+    @Operation(summary = "我的签到记录")
+    @PostMapping("/myAttendance")
+    public Result<List<Map<String, Object>>> myAttendance(
+            @RequestAttribute("userId") Long userId,
+            @RequestBody(required = false) Map<String, Object> body) {
+        Long cohortId = body == null || body.get("cohortId") == null ? null : toLong(body.get("cohortId"));
+        return attendanceService.myAttendance(userId, cohortId);
+    }
+
+    private Long toLong(Object v) {
+        if (v == null) {
+            return null;
+        }
+        try {
+            return Long.valueOf(v.toString().trim());
+        } catch (NumberFormatException e) {
+            return null;
+        }
+    }
+}

+ 78 - 0
train-backend/src/main/java/com/train/controller/CohortController.java

@@ -0,0 +1,78 @@
+package com.train.controller;
+
+import com.train.common.Result;
+import com.train.service.CohortService;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestAttribute;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * 培训批次 Controller(用户/公网侧)
+ *
+ * - 统一 @PostMapping;参数用 Map 承接,扁平返回
+ * - list:published 批次可浏览;signup:必须本人(@RequestAttribute("userId"))
+ */
+@Tag(name = "培训批次", description = "批次列表 / 批次报名(幂等)")
+@RestController
+@RequestMapping("/api/cohort")
+public class CohortController {
+
+    @Resource
+    private CohortService cohortService;
+
+    /**
+     * 批次列表(published,可按 courseId 过滤)
+     * body: {courseId?, page?, size?}
+     */
+    @Operation(summary = "批次列表(已发布)")
+    @PostMapping("/list")
+    public Result<List<Map<String, Object>>> list(@RequestBody(required = false) Map<String, Object> body) {
+        Long courseId = toLong(body == null ? null : body.get("courseId"));
+        Integer page = toInt(body == null ? null : body.get("page"));
+        Integer size = toInt(body == null ? null : body.get("size"));
+        return cohortService.list(courseId, page, size);
+    }
+
+    /**
+     * 报名批次(★幂等)
+     * body: {cohortId}
+     */
+    @Operation(summary = "批次报名(幂等)")
+    @PostMapping("/signup")
+    public Result<Map<String, Object>> signup(
+            @RequestAttribute("userId") Long userId,
+            @RequestBody(required = false) Map<String, Object> body) {
+        Long cohortId = toLong(body == null ? null : body.get("cohortId"));
+        return cohortService.signup(userId, cohortId, body);
+    }
+
+    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;
+        }
+    }
+}

+ 92 - 0
train-backend/src/main/java/com/train/controller/CreditController.java

@@ -0,0 +1,92 @@
+package com.train.controller;
+
+import com.train.common.Result;
+import com.train.service.CreditService;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestAttribute;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * 学时 Controller(学员侧)
+ *
+ * - 单位红线:所有学时字段一律返回「分钟」整数(禁 /60、禁浮点),换算只在展示层
+ * - mine:我的学时账户/聚合(当前年账户,历史年台账聚合)
+ * - pending:我的待生效学时明细
+ * - object:对某条学时提异议
+ */
+@Tag(name = "我的学时", description = "学时汇总 / 待生效明细 / 提异议")
+@RestController
+@RequestMapping("/api/credit")
+public class CreditController {
+
+    @Resource
+    private CreditService creditService;
+
+    /**
+     * 我的学时汇总
+     * body: {year?}(缺省=当前年)
+     * 出参: {year, totalHours, theoryHours, practiceHours, effectiveHours, pendingHours, status} 全为分钟整数
+     */
+    @Operation(summary = "我的学时汇总(分钟整数)")
+    @PostMapping("/mine")
+    public Result<Map<String, Object>> mine(
+            @RequestAttribute("userId") Long userId,
+            @RequestBody(required = false) Map<String, Object> body) {
+        Integer year = body == null || body.get("year") == null ? null : toInt(body.get("year"));
+        return creditService.mine(userId, year);
+    }
+
+    /**
+     * 我的待生效学时明细(status=pending)
+     * 出参: [{ledgerId, sourceType, sourceCategory, hours(分钟), status, effectiveAt, sourceDesc, createdAt}]
+     */
+    @Operation(summary = "我的待生效学时明细")
+    @PostMapping("/pending")
+    public Result<List<Map<String, Object>>> pending(@RequestAttribute("userId") Long userId) {
+        return creditService.pending(userId);
+    }
+
+    /**
+     * 对某条学时提异议(仅 pending 状态可提)
+     * body: {ledgerId, reason?}
+     */
+    @Operation(summary = "学时提异议")
+    @PostMapping("/object")
+    public Result<Void> object(
+            @RequestAttribute("userId") Long userId,
+            @RequestBody(required = false) Map<String, Object> body) {
+        Long ledgerId = toLong(body == null ? null : body.get("ledgerId"));
+        String reason = body == null || body.get("reason") == null ? null : body.get("reason").toString().trim();
+        return creditService.object(userId, ledgerId, reason);
+    }
+
+    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;
+        }
+    }
+}

+ 102 - 0
train-backend/src/main/java/com/train/controller/admin/AdminAttendanceController.java

@@ -0,0 +1,102 @@
+package com.train.controller.admin;
+
+import com.train.common.Result;
+import com.train.service.AttendanceService;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestAttribute;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import java.util.Map;
+
+/**
+ * 管理端-培训签到 Controller(发码 / 轮换 / 待生效列表)。
+ *
+ * 权限(Service 层经 RoleGuard 校验 isAdmin):全部端点仅 admin 可访问。
+ * - issueCode 幂等返回:同 session active 码未过期则复用
+ * - rotateCode 强制轮换
+ * - 学时字段一律「分钟」整数;code 有效期可配 app.attendance.code-valid-minutes(默认 5 分钟)
+ */
+@Tag(name = "管理端-培训签到", description = "发码 / 轮换 / 待生效签到列表")
+@RestController
+@RequestMapping("/api/admin/attendance")
+public class AdminAttendanceController {
+
+    @Resource
+    private AttendanceService attendanceService;
+
+    /**
+     * 发码(幂等返回)
+     * body: {sessionId, sessionHours?(分钟), category?(theory/practice/other)}
+     */
+    @Operation(summary = "发签到码(幂等)")
+    @PostMapping("/issueCode")
+    public Result<Map<String, Object>> issueCode(
+            @RequestAttribute(value = "adminId", required = false) Long adminId,
+            @RequestAttribute(value = "isAdmin", required = false) Boolean isAdmin,
+            @RequestBody(required = false) Map<String, Object> body) {
+        String sessionId = body == null || body.get("sessionId") == null ? null : body.get("sessionId").toString().trim();
+        Integer hours = toInt(body == null ? null : body.get("sessionHours"));
+        String category = body == null || body.get("category") == null ? null : body.get("category").toString().trim();
+        String note = body == null || body.get("note") == null ? null : body.get("note").toString().trim();
+        return attendanceService.issueCode(isAdmin, adminId, sessionId, hours, category, note);
+    }
+
+    /**
+     * 轮换码
+     * body: {sessionId, sessionHours?(分钟), category?(theory/practice/other)}
+     */
+    @Operation(summary = "轮换签到码")
+    @PostMapping("/rotateCode")
+    public Result<Map<String, Object>> rotateCode(
+            @RequestAttribute(value = "adminId", required = false) Long adminId,
+            @RequestAttribute(value = "isAdmin", required = false) Boolean isAdmin,
+            @RequestBody(required = false) Map<String, Object> body) {
+        String sessionId = body == null || body.get("sessionId") == null ? null : body.get("sessionId").toString().trim();
+        Integer hours = toInt(body == null ? null : body.get("sessionHours"));
+        String category = body == null || body.get("category") == null ? null : body.get("category").toString().trim();
+        String note = body == null || body.get("note") == null ? null : body.get("note").toString().trim();
+        return attendanceService.rotateCode(isAdmin, adminId, sessionId, hours, category, note);
+    }
+
+    /**
+     * 待生效签到列表(真分页)
+     * body: {cohortId?, page?, size?}
+     */
+    @Operation(summary = "待生效签到列表(分页)")
+    @PostMapping("/pending")
+    public Result<Map<String, Object>> pending(
+            @RequestAttribute(value = "isAdmin", required = false) Boolean isAdmin,
+            @RequestBody(required = false) Map<String, Object> body) {
+        Long cohortId = toLong(body == null ? null : body.get("cohortId"));
+        Integer page = toInt(body == null ? null : body.get("page"));
+        Integer size = toInt(body == null ? null : body.get("size"));
+        return attendanceService.pendingAttendance(isAdmin, cohortId, page, size);
+    }
+
+    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;
+        }
+    }
+}

+ 140 - 0
train-backend/src/main/java/com/train/controller/admin/AdminCohortController.java

@@ -0,0 +1,140 @@
+package com.train.controller.admin;
+
+import com.train.common.Result;
+import com.train.service.CohortService;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestAttribute;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import java.util.Map;
+
+/**
+ * 管理端-培训批次 Controller。
+ *
+ * 权限(Service 层经 RoleGuard 校验 isAdmin):全部端点仅 admin 可访问。
+ * - create/publish/close/detail/signupList/auditSignup
+ * - 统一 @PostMapping;参数用 Map 承接(对齐既有 AdminOrgController 风格)。
+ * - 学时字段一律「分钟」整数。
+ */
+@Tag(name = "管理端-培训批次", description = "创建 / 发布 / 关闭 / 报名列表 / 报名审核 / 详情")
+@RestController
+@RequestMapping("/api/admin/cohort")
+public class AdminCohortController {
+
+    @Resource
+    private CohortService cohortService;
+
+    /**
+     * 创建批次(草稿)
+     * body: {courseId, name, code?, startAt?, endAt?, signupDeadline?, capacity?, creditHours?, creditTheoryHours?, creditPracticeHours?, place?, lecturerId?}
+     */
+    @Operation(summary = "创建批次草稿")
+    @PostMapping("/create")
+    public Result<Map<String, Object>> create(
+            @RequestAttribute(value = "adminId", required = false) Long adminId,
+            @RequestAttribute(value = "isAdmin", required = false) Boolean isAdmin,
+            @RequestBody(required = false) Map<String, Object> body) {
+        return cohortService.create(adminId, isAdmin, body);
+    }
+
+    /**
+     * 发布批次(draft→published)
+     * body: {cohortId}
+     */
+    @Operation(summary = "发布批次")
+    @PostMapping("/publish")
+    public Result<Map<String, Object>> publish(
+            @RequestAttribute(value = "adminId", required = false) Long adminId,
+            @RequestAttribute(value = "isAdmin", required = false) Boolean isAdmin,
+            @RequestBody(required = false) Map<String, Object> body) {
+        Long cohortId = toLong(body == null ? null : body.get("cohortId"));
+        return cohortService.publish(adminId, isAdmin, cohortId);
+    }
+
+    /**
+     * 关闭批次(published→closed)
+     * body: {cohortId}
+     */
+    @Operation(summary = "关闭批次")
+    @PostMapping("/close")
+    public Result<Map<String, Object>> close(
+            @RequestAttribute(value = "adminId", required = false) Long adminId,
+            @RequestAttribute(value = "isAdmin", required = false) Boolean isAdmin,
+            @RequestBody(required = false) Map<String, Object> body) {
+        Long cohortId = toLong(body == null ? null : body.get("cohortId"));
+        return cohortService.close(adminId, isAdmin, cohortId);
+    }
+
+    /**
+     * 批次详情(含报名统计)
+     * body: {cohortId}
+     */
+    @Operation(summary = "批次详情")
+    @PostMapping("/detail")
+    public Result<Map<String, Object>> detail(
+            @RequestAttribute(value = "adminId", required = false) Long adminId,
+            @RequestAttribute(value = "isAdmin", required = false) Boolean isAdmin,
+            @RequestBody(required = false) Map<String, Object> body) {
+        Long cohortId = toLong(body == null ? null : body.get("cohortId"));
+        return cohortService.detail(adminId, isAdmin, cohortId);
+    }
+
+    /**
+     * 报名列表(真分页)
+     * body: {cohortId, page?, size?}
+     */
+    @Operation(summary = "批次报名列表(分页)")
+    @PostMapping("/signupList")
+    public Result<Map<String, Object>> signupList(
+            @RequestAttribute(value = "adminId", required = false) Long adminId,
+            @RequestAttribute(value = "isAdmin", required = false) Boolean isAdmin,
+            @RequestBody(required = false) Map<String, Object> body) {
+        Long cohortId = toLong(body == null ? null : body.get("cohortId"));
+        Integer page = toInt(body == null ? null : body.get("page"));
+        Integer size = toInt(body == null ? null : body.get("size"));
+        return cohortService.signupList(adminId, isAdmin, cohortId, page, size);
+    }
+
+    /**
+     * 审核报名(pending→approved/rejected)
+     * body: {signupId, pass, reason?}
+     */
+    @Operation(summary = "审核报名")
+    @PostMapping("/auditSignup")
+    public Result<Map<String, Object>> auditSignup(
+            @RequestAttribute(value = "adminId", required = false) Long adminId,
+            @RequestAttribute(value = "isAdmin", required = false) Boolean isAdmin,
+            @RequestBody(required = false) Map<String, Object> body) {
+        Long signupId = toLong(body == null ? null : body.get("signupId"));
+        Boolean pass = body == null || body.get("pass") == null ? null : Boolean.valueOf(body.get("pass").toString());
+        String reason = body == null || body.get("reason") == null ? null : body.get("reason").toString().trim();
+        return cohortService.auditSignup(adminId, isAdmin, signupId, pass, reason);
+    }
+
+    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;
+        }
+    }
+}

+ 72 - 0
train-backend/src/main/java/com/train/controller/admin/AdminCreditController.java

@@ -0,0 +1,72 @@
+package com.train.controller.admin;
+
+import com.train.common.Result;
+import com.train.service.CreditEffectiveManager;
+import com.train.service.CreditService;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestAttribute;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import java.util.Map;
+
+/**
+ * 管理端-学时 Controller(待生效台账 / 手动补跑到期扫描)。
+ *
+ * 权限:仅 admin。
+ * - ledgerPending:待生效台账列表(真分页)
+ * - scan:手动补跑到期生效 + 异议回滚 + cfc 重推(与定时任务共用同一 Service 方法)
+ */
+@Tag(name = "管理端-学时", description = "待生效台账 / 手动补跑到期扫描")
+@RestController
+@RequestMapping("/api/admin/credit")
+public class AdminCreditController {
+
+    @Resource
+    private CreditService creditService;
+    @Resource
+    private CreditEffectiveManager creditEffectiveManager;
+
+    /**
+     * 待生效台账列表(真分页)
+     * body: {page?, size?}
+     */
+    @Operation(summary = "待生效台账列表(分页)")
+    @PostMapping("/ledgerPending")
+    public Result<Map<String, Object>> ledgerPending(
+            @RequestAttribute(value = "isAdmin", required = false) Boolean isAdmin,
+            @RequestBody(required = false) Map<String, Object> body) {
+        Integer page = body == null || body.get("page") == null ? null : toInt(body.get("page"));
+        Integer size = body == null || body.get("size") == null ? null : toInt(body.get("size"));
+        return creditService.ledgerPending(isAdmin, page, size);
+    }
+
+    /**
+     * 手动补跑到期扫描(生效 + 异议回滚 + cfc 重推)
+     * 出参: {effectiveCount, rolledBack, cfcPushed}
+     */
+    @Operation(summary = "手动补跑到期扫描")
+    @PostMapping("/scan")
+    public Result<Map<String, Object>> scan(
+            @RequestAttribute(value = "isAdmin", required = false) Boolean isAdmin) {
+        if (!Boolean.TRUE.equals(isAdmin)) {
+            return Result.error("需要管理员权限");
+        }
+        return Result.success(creditEffectiveManager.manualScan());
+    }
+
+    private Integer toInt(Object v) {
+        if (v == null) {
+            return null;
+        }
+        try {
+            return Integer.valueOf(v.toString().trim());
+        } catch (NumberFormatException e) {
+            return null;
+        }
+    }
+}

+ 50 - 0
train-backend/src/main/java/com/train/service/AttendanceService.java

@@ -0,0 +1,50 @@
+package com.train.service;
+
+import com.train.common.Result;
+
+import java.util.List;
+import java.util.Map;
+
+/**
+ * 培训现场签到服务(动态签到码 + 反扫 + 台账入账)
+ *
+ * 幂等设计:
+ * - issueCode 幂等返回:同 session 已有 active 码且未过期 → 直接返回,不重复发码
+ * - scan ★:train_attendance uk(user_id, session_id) 防重复扫码;台账侧 ledgerPending 再按 uk(user_id,source_type,source_id) 幂等
+ * - 有效期默认 5 分钟,可配 app.attendance.code-valid-minutes
+ * - 权限:issueCode/rotateCode(讲师发码)与 pendingAttendance 仅 admin;scan/mySessions/myAttendance 本人
+ */
+public interface AttendanceService {
+
+    /**
+     * 发码(仅 admin;幂等返回):同 session 复用未过期 active 码;无则新建并轮换旧码。
+     */
+    Result<Map<String, Object>> issueCode(Boolean isAdmin, Long operatorId, String sessionId,
+                                          Integer sessionHours, String category, String note);
+
+    /**
+     * 轮换码(仅 admin):同 session 旧 active 码置 rotated,新建 active 码。
+     */
+    Result<Map<String, Object>> rotateCode(Boolean isAdmin, Long operatorId, String sessionId,
+                                           Integer sessionHours, String category, String note);
+
+    /**
+     * 反扫(本人):验码 → 写 attendance → 台账 pending 入账(同事务)。
+     */
+    Result<Map<String, Object>> scan(Long userId, String code);
+
+    /**
+     * 我的场次列表(按 attended_at 倒序)。
+     */
+    Result<List<Map<String, Object>>> mySessions(Long userId);
+
+    /**
+     * 我的签到记录(按批次可选过滤)。
+     */
+    Result<List<Map<String, Object>>> myAttendance(Long userId, Long cohortId);
+
+    /**
+     * 管理后台:待生效签到记录列表(真分页;仅 admin,方法内 RoleGuard 校验)。
+     */
+    Result<Map<String, Object>> pendingAttendance(Boolean isAdmin, Long cohortId, Integer page, Integer size);
+}

+ 155 - 0
train-backend/src/main/java/com/train/service/CfcCreditSyncService.java

@@ -0,0 +1,155 @@
+package com.train.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.train.cfc.entity.CfcUser;
+import com.train.cfc.mapper.CfcUserMapper;
+import com.train.entity.TrainCfcSyncLog;
+import com.train.entity.TrainUser;
+import com.train.mapper.TrainCfcSyncLogMapper;
+import com.train.mapper.TrainUserMapper;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.util.Date;
+import java.util.List;
+
+/**
+ * cfc 学时回填(train 权威 → cfc 弱一致)
+ *
+ * 幂等键:sync_key = sourceType:sourceId(如 "attendance:123")。
+ * 失败 warn 不阻塞,重试至 retry-max;cfc 不可达或目标未就绪时日志置 pending,由重试扫描补偿。
+ *
+ * cfc 隔离红线:所有 cfc 读写仅经 com.train.cfc 方言 Mapper,本 Service 是 train 学时回填 cfc 的唯一出口。
+ */
+@Slf4j
+@Service
+public class CfcCreditSyncService {
+
+    private static final String LOG_PENDING = "pending";
+    private static final String LOG_SUCCESS = "success";
+    private static final String LOG_FAILED = "failed";
+
+    @Resource
+    private TrainCfcSyncLogMapper trainCfcSyncLogMapper;
+    @Resource
+    private TrainUserMapper trainUserMapper;
+    @Resource
+    private CfcUserMapper cfcUserMapper;
+
+    /** cfc 回填失败最大重推次数 */
+    @Value("${cfc.credit-sync.retry-max:5}")
+    private Integer retryMax;
+
+    /**
+     * 回填一条学时到 cfc(学时生效后由 CreditEffectiveManager 触发)。
+     *
+     * @param userId     train 用户ID
+     * @param sourceType 来源类型(attendance/exam/practice/...)
+     * @param sourceId   来源业务ID(如 attendance.id)
+     * @param hours      学时(分钟整数)
+     * @return true=推送成功;false=推送失败或目标未就绪(记日志,等待重试)
+     */
+    public boolean push(Long userId, String sourceType, String sourceId, Integer hours) {
+        if (userId == null || sourceType == null || sourceId == null || hours == null) {
+            return false;
+        }
+        String syncKey = sourceType + ":" + sourceId;
+        // 幂等:sync_key 命中已成功 → 跳过
+        TrainCfcSyncLog exist = trainCfcSyncLogMapper.selectOne(
+                new LambdaQueryWrapper<TrainCfcSyncLog>()
+                        .eq(TrainCfcSyncLog::getSyncKey, syncKey)
+                        .last("LIMIT 1"));
+        if (exist != null && LOG_SUCCESS.equals(exist.getStatus())) {
+            log.debug("cfc 回填幂等命中,跳过: syncKey={}", syncKey);
+            return true;
+        }
+        TrainCfcSyncLog syncLog = exist == null ? new TrainCfcSyncLog() : exist;
+        Date now = new Date();
+        boolean ok = false;
+        String lastError = null;
+        try {
+            ok = doPush(userId, hours);
+        } catch (Exception e) {
+            lastError = e.getMessage();
+            log.warn("cfc 回填推送异常: userId={}, syncKey={}, hours={}, err={}", userId, syncKey, hours, lastError);
+        }
+        // 写/更新日志
+        syncLog.setSyncKey(syncKey);
+        syncLog.setSyncType("credit");
+        syncLog.setUserId(userId);
+        syncLog.setSourceType(sourceType);
+        syncLog.setSourceId(sourceId);
+        syncLog.setHours(hours);
+        syncLog.setUpdatedAt(now);
+        if (ok) {
+            syncLog.setStatus(LOG_SUCCESS);
+            syncLog.setLastError(null);
+            syncLog.setSyncedAt(now);
+        } else {
+            int retry = (exist != null && exist.getRetryCount() != null ? exist.getRetryCount() : 0) + 1;
+            syncLog.setStatus(retry >= retryMax ? LOG_FAILED : LOG_PENDING);
+            syncLog.setRetryCount(retry);
+            syncLog.setLastError(lastError == null ? "目标未就绪/未配置映射" : lastError);
+        }
+        if (exist == null) {
+            syncLog.setCreatedAt(now);
+            try {
+                trainCfcSyncLogMapper.insert(syncLog);
+            } catch (Exception e) {
+                // 并发首建:uk(sync_key) 冲突可忽略
+                log.debug("cfc sync_log 幂等命中: syncKey={}", syncKey);
+            }
+        } else {
+            trainCfcSyncLogMapper.updateById(syncLog);
+        }
+        return ok;
+    }
+
+    /**
+     * 实际推送 cfc:解析 cfc 会员并校验就绪;未就绪返回 false(记日志,等待重试)。
+     * cfc 侧学时落点由 category 映射决定,train 侧无映射时不强行写入,避免污染 cfc 数据。
+     */
+    private boolean doPush(Long userId, Integer hours) {
+        TrainUser trainUser = trainUserMapper.selectById(userId);
+        if (trainUser == null || trainUser.getCfcUserId() == null) {
+            log.warn("cfc 回填跳过(train 用户未关联 cfc 会员): userId={}", userId);
+            return false;
+        }
+        CfcUser cfcUser = cfcUserMapper.selectById(trainUser.getCfcUserId());
+        if (cfcUser == null) {
+            log.warn("cfc 回填跳过(cfc 会员不存在): userId={}, cfcUserId={}", userId, trainUser.getCfcUserId());
+            return false;
+        }
+        // cfc 学时落点需要 category 映射(如 attendance→planner_cert_categories.id),
+        // 当前 M2 未配置映射,学时仅在日志待推送状态保留,由管理端补登 /api/admin/planner-certifications/sync-hours。
+        log.warn("cfc 学时映射未配置,记录待推送: userId={}, cfcUserId={}, hours={} 分钟", userId, trainUser.getCfcUserId(), hours);
+        return false;
+    }
+
+    /**
+     * 补偿重推(由 CreditEffectiveManager 调用):扫描 pending 日志重推。
+     */
+    public int retryPending() {
+        List<TrainCfcSyncLog> list = trainCfcSyncLogMapper.selectList(
+                new LambdaQueryWrapper<TrainCfcSyncLog>()
+                        .eq(TrainCfcSyncLog::getStatus, LOG_PENDING)
+                        .last("LIMIT 500"));
+        int ok = 0;
+        for (TrainCfcSyncLog l : list) {
+            try {
+                boolean done = push(l.getUserId(), l.getSourceType(), l.getSourceId(), l.getHours());
+                if (done) {
+                    ok++;
+                }
+            } catch (Exception e) {
+                log.warn("cfc 回填补偿重推异常: syncKey={}, err={}", l.getSyncKey(), e.getMessage());
+            }
+        }
+        if (ok > 0) {
+            log.info("cfc 回填补偿重推完成: 本批 {} 条", ok);
+        }
+        return ok;
+    }
+}

+ 59 - 0
train-backend/src/main/java/com/train/service/CohortService.java

@@ -0,0 +1,59 @@
+package com.train.service;
+
+import com.train.common.Result;
+
+import java.util.List;
+import java.util.Map;
+
+/**
+ * 培训批次服务(批次生命周期 + 报名)
+ *
+ * 权限(§4.2 方案 B):管理端 create/publish/close/detail/signupList/auditSignup 在方法内经 RoleGuard 校验 admin。
+ *
+ * 幂等设计:
+ * - signup ★:train_cohort_signup uk(user_id,cohort_id) 幂等;train_enrollment 同事务 upsert 置 confirmed
+ * - 报名三步同事务:插 signup → 容量校验 → 同步 enrollment
+ * - 批次状态机 draft→published→closed(StateGuard.checkCohort)
+ */
+public interface CohortService {
+
+    /**
+     * 管理:创建批次草稿(仅 admin,方法内 RoleGuard 校验)。
+     */
+    Result<Map<String, Object>> create(Long operatorId, Boolean isAdmin, Map<String, Object> body);
+
+    /**
+     * 管理:发布批次(draft→published;需 end_at/signup_deadline 已设;仅 admin)。
+     */
+    Result<Map<String, Object>> publish(Long operatorId, Boolean isAdmin, Long cohortId);
+
+    /**
+     * 管理:关闭批次(published→closed;仅 admin)。
+     */
+    Result<Map<String, Object>> close(Long operatorId, Boolean isAdmin, Long cohortId);
+
+    /**
+     * 用户:报名批次(★幂等 + 同步 enrollment)。
+     */
+    Result<Map<String, Object>> signup(Long userId, Long cohortId, Map<String, Object> body);
+
+    /**
+     * 用户/公网:批次列表(published,可按 courseId 过滤)。
+     */
+    Result<List<Map<String, Object>>> list(Long courseId, Integer page, Integer size);
+
+    /**
+     * 管理:批次详情(含报名统计;仅 admin)。
+     */
+    Result<Map<String, Object>> detail(Long operatorId, Boolean isAdmin, Long cohortId);
+
+    /**
+     * 管理:某批次的报名列表(真分页;仅 admin)。
+     */
+    Result<Map<String, Object>> signupList(Long operatorId, Boolean isAdmin, Long cohortId, Integer page, Integer size);
+
+    /**
+     * 管理:审核报名(pending→approved/rejected,置 enrollment 学籍;仅 admin)。
+     */
+    Result<Map<String, Object>> auditSignup(Long operatorId, Boolean isAdmin, Long signupId, Boolean pass, String reason);
+}

+ 53 - 0
train-backend/src/main/java/com/train/service/CreditEffectiveManager.java

@@ -0,0 +1,53 @@
+package com.train.service;
+
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.scheduling.annotation.Scheduled;
+import org.springframework.stereotype.Component;
+
+import javax.annotation.Resource;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * 学时生效调度器(每日 cron + 手动补跑)。
+ *
+ * 与 CreditService.effectiveDue() 共用同一 Service 方法(不另写一套,保证 cron 与手动行为一致)。
+ * 生效成功后触发 cfc 学时回填(失败 warn,不阻塞)。
+ *
+ * cron 三层防御:① 兜底表达式 "0 0 4 * * ?" ② 属性占位 ${task.credit-scan-cron} ③ 防呆注释(勿用秒/分误填)。
+ */
+@Slf4j
+@Component
+public class CreditEffectiveManager {
+
+    @Resource
+    private CreditService creditService;
+    @Resource
+    private CfcCreditSyncService cfcCreditSyncService;
+
+    /**
+     * 定时扫描:每晚 04:00(可配 task.credit-scan-cron,默认 0 0 4 * * ?)。
+     */
+    @Scheduled(cron = "${task.credit-scan-cron:0 0 4 * * ?}")
+    public void scan() {
+        log.info("学时生效定时任务启动");
+        int effectiveCount = creditService.effectiveDue();
+        int rolledBack = creditService.rollBackObjected();
+        int cfcPushed = cfcCreditSyncService.retryPending();
+        log.info("学时生效定时任务完成: effectiveCount={}, rolledBack={}, cfcPushed={}", effectiveCount, rolledBack, cfcPushed);
+    }
+
+    /**
+     * 手动补跑:返回本次处理条数(生效/回滚/cfc重推)。
+     */
+    public Map<String, Object> manualScan() {
+        int effectiveCount = creditService.effectiveDue();
+        int rolledBack = creditService.rollBackObjected();
+        int cfcPushed = cfcCreditSyncService.retryPending();
+        Map<String, Object> result = new HashMap<>();
+        result.put("effectiveCount", effectiveCount);
+        result.put("rolledBack", rolledBack);
+        result.put("cfcPushed", cfcPushed);
+        return result;
+    }
+}

+ 77 - 0
train-backend/src/main/java/com/train/service/CreditService.java

@@ -0,0 +1,77 @@
+package com.train.service;
+
+import com.train.common.Result;
+import com.train.entity.TrainCreditAccount;
+import com.train.entity.TrainCreditLedger;
+
+import java.util.List;
+import java.util.Map;
+
+/**
+ * 学时服务(账户 + 台账 + 生效 + 异议回滚)
+ *
+ * 硬约束:
+ * - 学时一律「分钟」整数,禁浮点;对外 API 一律返回分钟(换算只在展示层)
+ * - pending 不计入 effective_hours;T+3(可配)到期由 CreditEffectiveManager 批量生效
+ * - ledger(pending→effective) 与 attendance(pending→effective) 按 source_id=attendance.id 双写,同事务
+ */
+public interface CreditService {
+
+    /**
+     * 取或建当年学时账户;跨年原地重置(只存当年,历史年由 ledger 聚合)。
+     */
+    TrainCreditAccount ensureAccount(Long userId, Integer year);
+
+    /**
+     * 我的学时汇总(当前年读账户;历史年 ledger 聚合)。
+     */
+    Result<Map<String, Object>> mine(Long userId, Integer year);
+
+    /**
+     * 我的待生效学时台账明细(status=pending)。
+     */
+    Result<List<Map<String, Object>>> pending(Long userId);
+
+    /**
+     * 对某条台账提异议:ledger pending→objected,并按 source_id=attendance.id 回写 attendance→objected。
+     */
+    Result<Void> object(Long userId, Long ledgerId, String reason);
+
+    /**
+     * 内部:向台账写入一条 pending 学时并累加账户 pending_hours(幂等:uk user_id+source_type+source_id)。
+     * 由 AttendanceService.scan 在同事务内调用。
+     *
+     * @return true=新增入账成功;false=幂等命中(已存在,跳过)
+     */
+    boolean ledgerPending(Long userId, String sourceType, String sourceId, String category,
+                          Integer hours, String desc);
+
+    /**
+     * 全量到期生效:扫描 status=pending 且 effective_at<=now 的台账逐条生效(对齐 FollowUpTask 逐条容错)。
+     * 禁止限定「当天」,启动/重启补偿幂等。返回本批生效条数。
+     */
+    int effectiveDue();
+
+    /**
+     * 全量异议回滚:扫描 status=objected 的台账逐条 pending→rejected(终态),同步 attendance。
+     * 返回本批回滚条数。
+     */
+    int rollBackObjected();
+
+    /**
+     * 管理后台:待生效台账列表(手写 LIMIT/OFFSET 真分页;仅 admin)。
+     */
+    Result<Map<String, Object>> ledgerPending(Boolean isAdmin, Integer page, Integer size);
+
+    /**
+     * 单条生效(独立事务):ledger pending→effective + attendance 翻转 + 账户累加。
+     * 由 effectiveDue 经代理自注入逐条调用,保证每条一个独立事务(对齐 FollowUpTask 逐条容错)。
+     */
+    void applyEffective(TrainCreditLedger l);
+
+    /**
+     * 单条异议回滚(独立事务):ledger objected→rejected(终态)+ attendance 翻转。
+     * 由 rollBackObjected 经代理自注入逐条调用。
+     */
+    void applyRollBack(TrainCreditLedger l);
+}

+ 376 - 0
train-backend/src/main/java/com/train/service/impl/AttendanceServiceImpl.java

@@ -0,0 +1,376 @@
+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.mapper.TrainAttendanceCodeMapper;
+import com.train.mapper.TrainAttendanceMapper;
+import com.train.mapper.TrainCohortMapper;
+import com.train.mapper.TrainCohortSignupMapper;
+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.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";
+
+    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 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 operatorId, String sessionId,
+                                                 Integer sessionHours, String category, String note) {
+        String noAuth = roleGuard.requireAdminRole(isAdmin);
+        if (noAuth != null) {
+            return Result.error(noAuth);
+        }
+        if (operatorId == 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("批次不存在");
+        }
+        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"));
+        if (active != null && active.getValidTo() != null && !active.getValidTo().before(now)) {
+            return Result.success(codeVO(active));
+        }
+        return doIssue(operatorId, sessionId, sessionHours, category, now);
+    }
+
+    @Override
+    @Transactional(rollbackFor = Exception.class)
+    public Result<Map<String, Object>> rotateCode(Boolean isAdmin, Long operatorId, String sessionId,
+                                                   Integer sessionHours, String category, String note) {
+        String noAuth = roleGuard.requireAdminRole(isAdmin);
+        if (noAuth != null) {
+            return Result.error(noAuth);
+        }
+        if (operatorId == 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(operatorId, sessionId, sessionHours, category, now);
+    }
+
+    /** 实际发码:轮换本 session 所有 active 旧码 + 新建 active 码 */
+    private Result<Map<String, Object>> doIssue(Long userId, String sessionId, Integer sessionHours,
+                                                String category, Date now) {
+        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);
+            trainAttendanceCodeMapper.updateById(o);
+        }
+        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);
+    }
+
+    // ============ 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());
+        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("status", c.getStatus());
+        return m;
+    }
+
+    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 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);
+        return c;
+    }
+}

+ 436 - 0
train-backend/src/main/java/com/train/service/impl/CohortServiceImpl.java

@@ -0,0 +1,436 @@
+package com.train.service.impl;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.train.common.Result;
+import com.train.common.StateGuard;
+import com.train.entity.TrainCohort;
+import com.train.entity.TrainCohortSignup;
+import com.train.entity.TrainEnrollment;
+import com.train.entity.TrainUser;
+import com.train.mapper.TrainCohortMapper;
+import com.train.mapper.TrainCohortSignupMapper;
+import com.train.mapper.TrainCourseMapper;
+import com.train.mapper.TrainEnrollmentMapper;
+import com.train.mapper.TrainUserMapper;
+import com.train.service.CohortService;
+import com.train.service.RoleGuard;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.annotation.Resource;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * 培训批次实现(批次生命周期 + 报名)
+ *
+ * 关键口径:
+ * - 批次状态机 draft→published→closed(StateGuard.checkCohort)
+ * - signup ★幂等:train_cohort_signup uk(user_id,cohort_id) 冲突→返回已报名;三步同事务(插 signup→容量→upsert enrollment)
+ * - train_enrollment(user_id, course_id) 置 confirmed(已进班),作为训练营学籍
+ * - 学时一律分钟整数;分页手写 LIMIT/OFFSET(项目无 PaginationInnerInterceptor)
+ */
+@Slf4j
+@Service
+public class CohortServiceImpl implements CohortService {
+
+    private static final String SIG_PENDING = "pending";
+    private static final String SIG_APPROVED = "approved";
+    private static final String SIG_REJECTED = "rejected";
+    private static final String SIG_CANCELLED = "cancelled";
+    private static final String ENR_CONFIRMED = "confirmed";
+
+    @Resource
+    private TrainCohortMapper trainCohortMapper;
+    @Resource
+    private TrainCohortSignupMapper trainCohortSignupMapper;
+    @Resource
+    private TrainEnrollmentMapper trainEnrollmentMapper;
+    @Resource
+    private TrainCourseMapper trainCourseMapper;
+    @Resource
+    private TrainUserMapper trainUserMapper;
+    @Resource
+    private RoleGuard roleGuard;
+
+    @Override
+    public Result<Map<String, Object>> create(Long operatorId, Boolean isAdmin, Map<String, Object> body) {
+        String noAuth = roleGuard.requireAdminRole(isAdmin);
+        if (noAuth != null) {
+            return Result.error(noAuth);
+        }
+        if (body == null) {
+            return Result.error("参数不完整");
+        }
+        TrainCohort c = new TrainCohort();
+        c.setCourseId(toLong(body.get("courseId")));
+        c.setName(str(body.get("name")));
+        c.setCode(str(body.get("code")));
+        c.setStartAt(toDate(body.get("startAt")));
+        c.setEndAt(toDate(body.get("endAt")));
+        c.setSignupDeadline(toDate(body.get("signupDeadline")));
+        c.setCapacity(body.get("capacity") == null ? 0 : toInt(body.get("capacity")));
+        // 学时一律分钟整数(禁小时/浮点)
+        c.setCreditHours(body.get("creditHours") == null ? 0 : toInt(body.get("creditHours")));
+        c.setCreditTheoryHours(body.get("creditTheoryHours") == null ? 0 : toInt(body.get("creditTheoryHours")));
+        c.setCreditPracticeHours(body.get("creditPracticeHours") == null ? 0 : toInt(body.get("creditPracticeHours")));
+        c.setPlace(str(body.get("place")));
+        c.setLecturerId(toLong(body.get("lecturerId")));
+        c.setStatus(StateGuard.C_DRAFT);
+        c.setDeleted(0);
+        if (c.getCourseId() == null || c.getName() == null || c.getName().trim().isEmpty()) {
+            return Result.error("批次名称与课程必填");
+        }
+        if (c.getCourseId() != null && trainCourseMapper.selectById(c.getCourseId()) == null) {
+            return Result.error("课程不存在");
+        }
+        try {
+            trainCohortMapper.insert(c);
+        } catch (Exception e) {
+            // code 唯一冲突
+            log.warn("批次创建唯一键冲突: code={}, err={}", c.getCode(), e.getMessage());
+            return Result.error("批次号已存在");
+        }
+        return Result.success(cohortVO(c));
+    }
+
+    @Override
+    public Result<Map<String, Object>> publish(Long operatorId, Boolean isAdmin, Long cohortId) {
+        String noAuth = roleGuard.requireAdminRole(isAdmin);
+        if (noAuth != null) {
+            return Result.error(noAuth);
+        }
+        TrainCohort c = trainCohortMapper.selectById(cohortId);
+        if (c == null || (c.getDeleted() != null && c.getDeleted() == 1)) {
+            return Result.error("批次不存在");
+        }
+        String err = StateGuard.checkCohort(c.getStatus(), StateGuard.C_PUBLISHED);
+        if (err != null) {
+            return Result.error(err);
+        }
+        if (c.getEndAt() == null || c.getSignupDeadline() == null) {
+            return Result.error("发布前须设置结束时间与报名截止时间");
+        }
+        c.setStatus(StateGuard.C_PUBLISHED);
+        c.setUpdatedAt(new Date());
+        trainCohortMapper.updateById(c);
+        return Result.success(cohortVO(c));
+    }
+
+    @Override
+    public Result<Map<String, Object>> close(Long operatorId, Boolean isAdmin, Long cohortId) {
+        String noAuth = roleGuard.requireAdminRole(isAdmin);
+        if (noAuth != null) {
+            return Result.error(noAuth);
+        }
+        TrainCohort c = trainCohortMapper.selectById(cohortId);
+        if (c == null || (c.getDeleted() != null && c.getDeleted() == 1)) {
+            return Result.error("批次不存在");
+        }
+        String err = StateGuard.checkCohort(c.getStatus(), StateGuard.C_CLOSED);
+        if (err != null) {
+            return Result.error(err);
+        }
+        c.setStatus(StateGuard.C_CLOSED);
+        c.setUpdatedAt(new Date());
+        trainCohortMapper.updateById(c);
+        return Result.success(cohortVO(c));
+    }
+
+    @Override
+    @Transactional(rollbackFor = Exception.class)
+    public Result<Map<String, Object>> signup(Long userId, Long cohortId, Map<String, Object> body) {
+        if (userId == null || cohortId == null) {
+            return Result.error("参数不完整");
+        }
+        TrainCohort c = trainCohortMapper.selectById(cohortId);
+        if (c == null || (c.getDeleted() != null && c.getDeleted() == 1)) {
+            return Result.error("批次不存在");
+        }
+        if (!StateGuard.C_PUBLISHED.equals(c.getStatus())) {
+            return Result.error("批次未发布或已结束");
+        }
+        Date now = new Date();
+        if (c.getSignupDeadline() != null && c.getSignupDeadline().before(now)) {
+            return Result.error("报名已截止");
+        }
+        // ① 幂等:uk(user_id,cohort_id) 命中 → 已报名
+        TrainCohortSignup exist = trainCohortSignupMapper.selectOne(
+                new LambdaQueryWrapper<TrainCohortSignup>()
+                        .eq(TrainCohortSignup::getUserId, userId)
+                        .eq(TrainCohortSignup::getCohortId, cohortId)
+                        .last("LIMIT 1"));
+        if (exist != null) {
+            return Result.success(signupVO(exist));
+        }
+        // ② 容量校验
+        if (c.getCapacity() != null && c.getCapacity() > 0) {
+            Long approved = trainCohortSignupMapper.selectCount(
+                    new LambdaQueryWrapper<TrainCohortSignup>()
+                            .eq(TrainCohortSignup::getCohortId, cohortId)
+                            .eq(TrainCohortSignup::getStatus, SIG_APPROVED)
+                            .eq(TrainCohortSignup::getDeleted, 0));
+            if (approved != null && approved >= c.getCapacity()) {
+                return Result.error("批次名额已满");
+            }
+        }
+        TrainCohortSignup sig = new TrainCohortSignup();
+        sig.setUserId(userId);
+        sig.setCohortId(cohortId);
+        sig.setCourseId(c.getCourseId());
+        sig.setStatus(SIG_PENDING);
+        sig.setDeleted(0);
+        try {
+            trainCohortSignupMapper.insert(sig);
+        } catch (Exception e) {
+            // 并发幂等命中
+            TrainCohortSignup dup = trainCohortSignupMapper.selectOne(
+                    new LambdaQueryWrapper<TrainCohortSignup>()
+                            .eq(TrainCohortSignup::getUserId, userId)
+                            .eq(TrainCohortSignup::getCohortId, cohortId)
+                            .last("LIMIT 1"));
+            if (dup != null) {
+                return Result.success(signupVO(dup));
+            }
+            return Result.error("报名失败,请重试");
+        }
+        // ③ 同步 upsert train_enrollment(user_id, course_id) 置 confirmed(学籍)
+        Long enrollId = upsertEnrollment(userId, c.getCourseId(), now);
+        sig.setEnrollmentId(enrollId);
+        trainCohortSignupMapper.updateById(sig);
+        return Result.success(signupVO(sig));
+    }
+
+    /** upsert train_enrollment(user_id, course_id) 置 confirmed */
+    private Long upsertEnrollment(Long userId, Long courseId, Date now) {
+        TrainEnrollment enr = trainEnrollmentMapper.selectOne(
+                new LambdaQueryWrapper<TrainEnrollment>()
+                        .eq(TrainEnrollment::getUid, userId)
+                        .eq(TrainEnrollment::getCourseId, courseId)
+                        .last("LIMIT 1"));
+        TrainUser u = trainUserMapper.selectById(userId);
+        if (enr == null) {
+            enr = new TrainEnrollment();
+            enr.setUid(userId);
+            enr.setCourseId(courseId);
+            enr.setStatus(ENR_CONFIRMED);
+            enr.setEnrolledAt(now);
+            if (u != null) {
+                enr.setName(u.getName());
+                enr.setPhone(u.getPhone());
+            }
+            try {
+                trainEnrollmentMapper.insert(enr);
+            } catch (Exception e) {
+                log.warn("enrollment 插入并发回查: userId={}, courseId={}", userId, courseId);
+                TrainEnrollment dup = trainEnrollmentMapper.selectOne(
+                        new LambdaQueryWrapper<TrainEnrollment>()
+                                .eq(TrainEnrollment::getUid, userId)
+                                .eq(TrainEnrollment::getCourseId, courseId)
+                                .last("LIMIT 1"));
+                return dup == null ? null : dup.getId();
+            }
+        } else {
+            if (!ENR_CONFIRMED.equals(enr.getStatus())) {
+                enr.setStatus(ENR_CONFIRMED);
+                enr.setEnrolledAt(now);
+                trainEnrollmentMapper.updateById(enr);
+            }
+        }
+        return enr.getId();
+    }
+
+    @Override
+    public Result<List<Map<String, Object>>> list(Long courseId, Integer page, Integer size) {
+        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<TrainCohort> q = new LambdaQueryWrapper<TrainCohort>()
+                .eq(TrainCohort::getStatus, StateGuard.C_PUBLISHED)
+                .eq(TrainCohort::getDeleted, 0)
+                .orderByDesc(TrainCohort::getStartAt);
+        if (courseId != null) {
+            q.eq(TrainCohort::getCourseId, courseId);
+        }
+        List<TrainCohort> list = trainCohortMapper.selectList(q.last("LIMIT " + offset + "," + s));
+        List<Map<String, Object>> rows = new ArrayList<>();
+        for (TrainCohort c : list) {
+            rows.add(cohortVO(c));
+        }
+        return Result.success(rows);
+    }
+
+    @Override
+    public Result<Map<String, Object>> detail(Long operatorId, Boolean isAdmin, Long cohortId) {
+        String noAuth = roleGuard.requireAdminRole(isAdmin);
+        if (noAuth != null) {
+            return Result.error(noAuth);
+        }
+        TrainCohort c = trainCohortMapper.selectById(cohortId);
+        if (c == null || (c.getDeleted() != null && c.getDeleted() == 1)) {
+            return Result.error("批次不存在");
+        }
+        Map<String, Object> vo = cohortVO(c);
+        Long approved = trainCohortSignupMapper.selectCount(
+                new LambdaQueryWrapper<TrainCohortSignup>()
+                        .eq(TrainCohortSignup::getCohortId, cohortId)
+                        .eq(TrainCohortSignup::getStatus, SIG_APPROVED)
+                        .eq(TrainCohortSignup::getDeleted, 0));
+        Long pending = trainCohortSignupMapper.selectCount(
+                new LambdaQueryWrapper<TrainCohortSignup>()
+                        .eq(TrainCohortSignup::getCohortId, cohortId)
+                        .eq(TrainCohortSignup::getStatus, SIG_PENDING)
+                        .eq(TrainCohortSignup::getDeleted, 0));
+        vo.put("approvedCount", approved == null ? 0 : approved);
+        vo.put("pendingCount", pending == null ? 0 : pending);
+        return Result.success(vo);
+    }
+
+    @Override
+    public Result<Map<String, Object>> signupList(Long operatorId, 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<TrainCohortSignup> q = new LambdaQueryWrapper<TrainCohortSignup>()
+                .eq(TrainCohortSignup::getCohortId, cohortId)
+                .eq(TrainCohortSignup::getDeleted, 0)
+                .orderByDesc(TrainCohortSignup::getCreatedAt);
+        Long total = trainCohortSignupMapper.selectCount(q);
+        List<TrainCohortSignup> list = trainCohortSignupMapper.selectList(
+                q.last("LIMIT " + offset + "," + s));
+        List<Map<String, Object>> rows = new ArrayList<>();
+        for (TrainCohortSignup sig : list) {
+            Map<String, Object> vo = signupVO(sig);
+            TrainUser u = trainUserMapper.selectById(sig.getUserId());
+            if (u != null) {
+                vo.put("userName", u.getName());
+                vo.put("userPhone", u.getPhone());
+            }
+            rows.add(vo);
+        }
+        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>> auditSignup(Long operatorId, Boolean isAdmin, Long signupId, Boolean pass, String reason) {
+        String noAuth = roleGuard.requireAdminRole(isAdmin);
+        if (noAuth != null) {
+            return Result.error(noAuth);
+        }
+        TrainCohortSignup sig = trainCohortSignupMapper.selectById(signupId);
+        if (sig == null || (sig.getDeleted() != null && sig.getDeleted() == 1)) {
+            return Result.error("报名记录不存在");
+        }
+        if (!SIG_PENDING.equals(sig.getStatus())) {
+            return Result.error("当前状态不允许审核");
+        }
+        Date now = new Date();
+        sig.setReviewedBy(operatorId);
+        sig.setReviewedAt(now);
+        if (Boolean.TRUE.equals(pass)) {
+            sig.setStatus(SIG_APPROVED);
+        } else {
+            sig.setStatus(SIG_REJECTED);
+            sig.setRejectReason(reason);
+        }
+        trainCohortSignupMapper.updateById(sig);
+        return Result.success(signupVO(sig));
+    }
+
+    // ============ VO / helpers ============
+
+    private Map<String, Object> cohortVO(TrainCohort c) {
+        Map<String, Object> m = new HashMap<>();
+        m.put("cohortId", c.getId());
+        m.put("courseId", c.getCourseId());
+        m.put("name", c.getName());
+        m.put("code", c.getCode());
+        m.put("startAt", c.getStartAt());
+        m.put("endAt", c.getEndAt());
+        m.put("signupDeadline", c.getSignupDeadline());
+        m.put("capacity", c.getCapacity());
+        m.put("creditHours", c.getCreditHours() == null ? 0 : c.getCreditHours()); // 分钟
+        m.put("creditTheoryHours", c.getCreditTheoryHours() == null ? 0 : c.getCreditTheoryHours());
+        m.put("creditPracticeHours", c.getCreditPracticeHours() == null ? 0 : c.getCreditPracticeHours());
+        m.put("place", c.getPlace());
+        m.put("lecturerId", c.getLecturerId());
+        m.put("status", c.getStatus());
+        return m;
+    }
+
+    private Map<String, Object> signupVO(TrainCohortSignup sig) {
+        Map<String, Object> m = new HashMap<>();
+        m.put("signupId", sig.getId());
+        m.put("userId", sig.getUserId());
+        m.put("cohortId", sig.getCohortId());
+        m.put("courseId", sig.getCourseId());
+        m.put("enrollmentId", sig.getEnrollmentId());
+        m.put("status", sig.getStatus());
+        m.put("reviewedAt", sig.getReviewedAt());
+        m.put("rejectReason", sig.getRejectReason());
+        m.put("createdAt", sig.getCreatedAt());
+        return m;
+    }
+
+    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 String str(Object v) {
+        return v == null ? null : (v.toString().trim().isEmpty() ? null : v.toString().trim());
+    }
+
+    private Date toDate(Object v) {
+        if (v == null) {
+            return null;
+        }
+        if (v instanceof Date) {
+            return (Date) v;
+        }
+        String s = v.toString().trim();
+        String[] patterns = {"yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd'T'HH:mm:ss", "yyyy-MM-dd"};
+        for (String p : patterns) {
+            try {
+                SimpleDateFormat f = new SimpleDateFormat(p);
+                f.setLenient(false);
+                return f.parse(s);
+            } catch (ParseException e) {
+                // try next
+            }
+        }
+        return null;
+    }
+}

+ 468 - 0
train-backend/src/main/java/com/train/service/impl/CreditServiceImpl.java

@@ -0,0 +1,468 @@
+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.TrainCreditAccount;
+import com.train.entity.TrainCreditLedger;
+import com.train.mapper.TrainAttendanceMapper;
+import com.train.mapper.TrainCreditAccountMapper;
+import com.train.mapper.TrainCreditLedgerMapper;
+import com.train.service.CreditService;
+import com.train.service.CfcCreditSyncService;
+import com.train.service.RoleGuard;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.context.annotation.Lazy;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.annotation.Resource;
+import java.time.Year;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * 学时服务实现(账户 + 台账 + 生效 + 异议回滚)
+ *
+ * 关键口径(对齐设计 §2.3 + 数据模型):
+ * - 单一账户多来源:账户 uk(user_id) 仅存当年,跨年 ensureAccount 原地重置;历史年由 ledger 聚合
+ * - 学时一律分钟整数;pending 不计入 effective;T+3 到期生效(可配 app.credit.effective-delay-hours)
+ * - ledger↔attendance 双写按 source_id=attendance.id 关联,同事务翻转
+ * - effectiveDue 全量扫 pending+到期(禁限定当天),逐条单事务容错(对齐 FollowUpTask 范式)
+ */
+@Slf4j
+@Service
+public class CreditServiceImpl implements CreditService {
+
+    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 ACC_ACTIVE = "active";
+    private static final String ACC_SETTLED = "settled";
+
+    private static final String SRC_ATTENDANCE = "attendance";
+    private static final String CAT_THEORY = "theory";
+    private static final String CAT_PRACTICE = "practice";
+
+    @Resource
+    private TrainCreditAccountMapper trainCreditAccountMapper;
+    @Resource
+    private TrainCreditLedgerMapper trainCreditLedgerMapper;
+    @Resource
+    private TrainAttendanceMapper trainAttendanceMapper;
+    @Resource
+    private RoleGuard roleGuard;
+    @Resource
+    private CfcCreditSyncService cfcCreditSyncService;
+
+    /**
+     * 自注入代理:绕过 self-invocation,使 applyEffective/applyRollBack 的 @Transactional 生效。
+     * @Lazy 避免初始化循环依赖。
+     */
+    @Lazy
+    @Resource
+    private CreditService self;
+
+    /** 学时生效延迟小时(T+3,可配) */
+    @Value("${app.credit.effective-delay-hours:72}")
+    private Integer effectiveDelayHours;
+
+    @Override
+    public TrainCreditAccount ensureAccount(Long userId, Integer year) {
+        int curYear = year == null ? Year.now().getValue() : year;
+        TrainCreditAccount acc = trainCreditAccountMapper.selectOne(
+                new LambdaQueryWrapper<TrainCreditAccount>()
+                        .eq(TrainCreditAccount::getUserId, userId)
+                        .last("LIMIT 1"));
+        if (acc == null) {
+            TrainCreditAccount created = new TrainCreditAccount();
+            created.setUserId(userId);
+            created.setYear(curYear);
+            created.setTotalHours(0);
+            created.setTheoryHours(0);
+            created.setPracticeHours(0);
+            created.setEffectiveHours(0);
+            created.setPendingHours(0);
+            created.setStatus(ACC_ACTIVE);
+            try {
+                trainCreditAccountMapper.insert(created);
+                return created;
+            } catch (Exception e) {
+                // 并发首建:uk(user_id) 冲突 → 回查已存在行
+                return trainCreditAccountMapper.selectOne(
+                        new LambdaQueryWrapper<TrainCreditAccount>()
+                                .eq(TrainCreditAccount::getUserId, userId)
+                                .last("LIMIT 1"));
+            }
+        }
+        // 跨年原地重置(只存当年,历史年由 ledger 聚合)
+        if (acc.getYear() == null || acc.getYear() != curYear) {
+            acc.setYear(curYear);
+            acc.setTotalHours(0);
+            acc.setTheoryHours(0);
+            acc.setPracticeHours(0);
+            acc.setEffectiveHours(0);
+            acc.setPendingHours(0);
+            acc.setStatus(ACC_ACTIVE);
+            trainCreditAccountMapper.updateById(acc);
+        }
+        return acc;
+    }
+
+    @Override
+    public Result<Map<String, Object>> mine(Long userId, Integer year) {
+        int curYear = year == null ? Year.now().getValue() : year;
+        TrainCreditAccount acc = ensureAccount(userId, curYear);
+        Map<String, Object> vo;
+        if (acc.getYear() != null && acc.getYear() == curYear) {
+            // 当年读账户
+            vo = new HashMap<>();
+            vo.put("year", acc.getYear());
+            vo.put("totalHours", acc.getTotalHours() == null ? 0 : acc.getTotalHours());
+            vo.put("theoryHours", acc.getTheoryHours() == null ? 0 : acc.getTheoryHours());
+            vo.put("practiceHours", acc.getPracticeHours() == null ? 0 : acc.getPracticeHours());
+            vo.put("effectiveHours", acc.getEffectiveHours() == null ? 0 : acc.getEffectiveHours());
+            vo.put("pendingHours", acc.getPendingHours() == null ? 0 : acc.getPendingHours());
+            vo.put("status", acc.getStatus());
+        } else {
+            // 历史年 ledger 聚合(status=effective)
+            vo = aggregateYear(userId, curYear);
+        }
+        // 单位红线:全部返回分钟整数(换算只在展示层)
+        return Result.success(vo);
+    }
+
+    private Map<String, Object> aggregateYear(Long userId, int year) {
+        List<TrainCreditLedger> list = trainCreditLedgerMapper.selectList(
+                new LambdaQueryWrapper<TrainCreditLedger>()
+                        .eq(TrainCreditLedger::getUserId, userId)
+                        .eq(TrainCreditLedger::getYear, year)
+                        .eq(TrainCreditLedger::getStatus, ST_EFFECTIVE)
+                        .eq(TrainCreditLedger::getDeleted, 0));
+        long theory = 0, practice = 0, total = 0;
+        for (TrainCreditLedger l : list) {
+            int h = l.getHours() == null ? 0 : l.getHours();
+            total += h;
+            if (CAT_THEORY.equals(l.getSourceCategory())) {
+                theory += h;
+            } else if (CAT_PRACTICE.equals(l.getSourceCategory())) {
+                practice += h;
+            }
+        }
+        Map<String, Object> vo = new HashMap<>();
+        vo.put("year", year);
+        vo.put("totalHours", (int) total);
+        vo.put("theoryHours", (int) theory);
+        vo.put("practiceHours", (int) practice);
+        vo.put("effectiveHours", (int) total);
+        vo.put("pendingHours", 0);
+        vo.put("status", ACC_SETTLED);
+        return vo;
+    }
+
+    @Override
+    public Result<List<Map<String, Object>>> pending(Long userId) {
+        List<TrainCreditLedger> list = trainCreditLedgerMapper.selectList(
+                new LambdaQueryWrapper<TrainCreditLedger>()
+                        .eq(TrainCreditLedger::getUserId, userId)
+                        .eq(TrainCreditLedger::getStatus, ST_PENDING)
+                        .eq(TrainCreditLedger::getDeleted, 0)
+                        .orderByDesc(TrainCreditLedger::getCreatedAt));
+        List<Map<String, Object>> rows = new ArrayList<>();
+        for (TrainCreditLedger l : list) {
+            rows.add(toLedgerVO(l));
+        }
+        return Result.success(rows);
+    }
+
+    private Map<String, Object> toLedgerVO(TrainCreditLedger l) {
+        Map<String, Object> m = new HashMap<>();
+        m.put("ledgerId", l.getId());
+        m.put("sourceType", l.getSourceType());
+        m.put("sourceCategory", l.getSourceCategory());
+        m.put("hours", l.getHours() == null ? 0 : l.getHours()); // 分钟
+        m.put("status", l.getStatus());
+        m.put("effectiveAt", l.getEffectiveAt());
+        m.put("sourceDesc", l.getSourceDesc());
+        m.put("createdAt", l.getCreatedAt());
+        return m;
+    }
+
+    @Override
+    @Transactional(rollbackFor = Exception.class)
+    public Result<Void> object(Long userId, Long ledgerId, String reason) {
+        if (userId == null || ledgerId == null) {
+            return Result.error("参数不完整");
+        }
+        TrainCreditLedger l = trainCreditLedgerMapper.selectById(ledgerId);
+        if (l == null || (l.getDeleted() != null && l.getDeleted() == 1)) {
+            return Result.error("学时记录不存在");
+        }
+        if (!userId.equals(l.getUserId())) {
+            return Result.error("无权操作他人学时记录");
+        }
+        // 仅 pending 可提异议(已生效走申诉外流程)
+        if (!ST_PENDING.equals(l.getStatus())) {
+            return Result.error("当前状态不允许提异议");
+        }
+        l.setStatus(ST_OBJECTED);
+        l.setRemark(reason);
+        l.setUpdatedAt(new Date());
+        trainCreditLedgerMapper.updateById(l);
+        // 回写 attendance(source_id=attendance.id)→ objected,扣减账户 pending
+        if (SRC_ATTENDANCE.equals(l.getSourceType())) {
+            TrainAttendance att = trainAttendanceMapper.selectById(parseLong(l.getSourceId()));
+            if (att != null && ST_PENDING.equals(att.getStatus())) {
+                att.setStatus(ST_OBJECTED);
+                att.setObjectReason(reason);
+                att.setObjectedBy(userId);
+                att.setObjectedAt(new Date());
+                att.setUpdatedAt(new Date());
+                trainAttendanceMapper.updateById(att);
+            }
+        }
+        // 扣减账户 pending_hours
+        deductPending(l.getUserId(), l.getHours() == null ? 0 : l.getHours());
+        return Result.success();
+    }
+
+    private void deductPending(Long userId, int hours) {
+        if (hours <= 0) {
+            return;
+        }
+        TrainCreditAccount acc = trainCreditAccountMapper.selectOne(
+                new LambdaQueryWrapper<TrainCreditAccount>()
+                        .eq(TrainCreditAccount::getUserId, userId)
+                        .last("LIMIT 1"));
+        if (acc == null) {
+            return;
+        }
+        int pending = acc.getPendingHours() == null ? 0 : acc.getPendingHours();
+        acc.setPendingHours(Math.max(0, pending - hours));
+        acc.setUpdatedAt(new Date());
+        trainCreditAccountMapper.updateById(acc);
+    }
+
+    private Long parseLong(String v) {
+        if (v == null || v.trim().isEmpty()) {
+            return null;
+        }
+        try {
+            return Long.valueOf(v.trim());
+        } catch (NumberFormatException e) {
+            return null;
+        }
+    }
+
+    @Override
+    @Transactional(rollbackFor = Exception.class)
+    public boolean ledgerPending(Long userId, String sourceType, String sourceId, String category,
+                                 Integer hours, String desc) {
+        if (userId == null || sourceId == null || hours == null || hours <= 0) {
+            return false;
+        }
+        // 幂等:uk(user_id, source_type, source_id) 命中即跳过
+        Long cnt = trainCreditLedgerMapper.selectCount(
+                new LambdaQueryWrapper<TrainCreditLedger>()
+                        .eq(TrainCreditLedger::getUserId, userId)
+                        .eq(TrainCreditLedger::getSourceType, sourceType)
+                        .eq(TrainCreditLedger::getSourceId, sourceId)
+                        .eq(TrainCreditLedger::getDeleted, 0));
+        if (cnt != null && cnt > 0) {
+            return false;
+        }
+        Date now = new Date();
+        Date effAt = addHours(now, effectiveDelayHours == null ? 72 : effectiveDelayHours);
+        TrainCreditLedger l = new TrainCreditLedger();
+        l.setUserId(userId);
+        l.setYear(Year.of(yearOf(effAt)).getValue()); // 年度归属=effective_at 年度
+        l.setSourceType(sourceType);
+        l.setSourceCategory(category);
+        l.setSourceId(sourceId);
+        l.setHours(hours);
+        l.setStatus(ST_PENDING);
+        l.setEffectiveAt(effAt);
+        l.setSourceDesc(desc);
+        l.setDeleted(0);
+        try {
+            trainCreditLedgerMapper.insert(l);
+        } catch (Exception e) {
+            // 并发幂等命中
+            log.debug("ledger 幂等命中,跳过: userId={}, source={}:{}, err={}", userId, sourceType, sourceId, e.getMessage());
+            return false;
+        }
+        // 账户 pending 累加
+        TrainCreditAccount acc = ensureAccount(userId, Year.now().getValue());
+        int pending = acc.getPendingHours() == null ? 0 : acc.getPendingHours();
+        acc.setPendingHours(pending + hours);
+        acc.setUpdatedAt(now);
+        trainCreditAccountMapper.updateById(acc);
+        return true;
+    }
+
+    private int yearOf(Date d) {
+        Calendar c = Calendar.getInstance();
+        c.setTime(d);
+        return c.get(Calendar.YEAR);
+    }
+
+    private Date addHours(Date base, int hours) {
+        Calendar c = Calendar.getInstance();
+        c.setTime(base);
+        c.add(Calendar.HOUR_OF_DAY, hours);
+        return c.getTime();
+    }
+
+    @Override
+    public int effectiveDue() {
+        // 全量扫 pending 且到期(禁限定当天);启动/重启补偿幂等
+        List<TrainCreditLedger> list = trainCreditLedgerMapper.selectList(
+                new LambdaQueryWrapper<TrainCreditLedger>()
+                        .eq(TrainCreditLedger::getStatus, ST_PENDING)
+                        .eq(TrainCreditLedger::getDeleted, 0)
+                        .le(TrainCreditLedger::getEffectiveAt, new Date())
+                        .last("LIMIT 500"));
+        int ok = 0;
+        for (TrainCreditLedger l : list) {
+            try {
+                self.applyEffective(l);
+                // 生效成功后触发 cfc 学时回填(失败 warn 不阻塞;幂等键 sourceType:sourceId)
+                try {
+                    cfcCreditSyncService.push(l.getUserId(), l.getSourceType(), l.getSourceId(), l.getHours());
+                } catch (Exception e) {
+                    log.warn("cfc 学时回填触发失败: syncKey={}:{}, err={}", l.getSourceType(), l.getSourceId(), e.getMessage());
+                }
+                ok++;
+            } catch (Exception e) {
+                log.warn("学时生效失败(跳过): ledgerId={}, err={}", l.getId(), e.getMessage());
+            }
+        }
+        if (ok > 0) {
+            log.info("学时到期生效完成: 本批 {} 条", ok);
+        }
+        return ok;
+    }
+
+    /** 单条生效:单事务,ledger pending→effective + attendance 翻转 + 账户累加 */
+    @Transactional(rollbackFor = Exception.class)
+    public void applyEffective(TrainCreditLedger l) {
+        // 前置再校验(防并发重复生效)
+        TrainCreditLedger cur = trainCreditLedgerMapper.selectById(l.getId());
+        if (cur == null || !ST_PENDING.equals(cur.getStatus())) {
+            return;
+        }
+        Date now = new Date();
+        cur.setStatus(ST_EFFECTIVE);
+        cur.setUpdatedAt(now);
+        trainCreditLedgerMapper.updateById(cur);
+        // attendance 双写翻转
+        if (SRC_ATTENDANCE.equals(cur.getSourceType())) {
+            TrainAttendance att = trainAttendanceMapper.selectById(parseLong(cur.getSourceId()));
+            if (att != null && ST_PENDING.equals(att.getStatus())) {
+                att.setStatus(ST_EFFECTIVE);
+                att.setEffectiveAt(now);
+                att.setUpdatedAt(now);
+                trainAttendanceMapper.updateById(att);
+            }
+        }
+        // 账户累加:effective + 分类 + total
+        TrainCreditAccount acc = ensureAccount(cur.getUserId(), Year.now().getValue());
+        int h = cur.getHours() == null ? 0 : cur.getHours();
+        int pending = acc.getPendingHours() == null ? 0 : acc.getPendingHours();
+        int effective = acc.getEffectiveHours() == null ? 0 : acc.getEffectiveHours();
+        int theory = acc.getTheoryHours() == null ? 0 : acc.getTheoryHours();
+        int practice = acc.getPracticeHours() == null ? 0 : acc.getPracticeHours();
+        int total = acc.getTotalHours() == null ? 0 : acc.getTotalHours();
+        acc.setEffectiveHours(effective + h);
+        acc.setPendingHours(Math.max(0, pending - h));
+        if (CAT_THEORY.equals(cur.getSourceCategory())) {
+            acc.setTheoryHours(theory + h);
+        } else if (CAT_PRACTICE.equals(cur.getSourceCategory())) {
+            acc.setPracticeHours(practice + h);
+        }
+        acc.setTotalHours(total + h);
+        acc.setUpdatedAt(now);
+        trainCreditAccountMapper.updateById(acc);
+    }
+
+    @Override
+    public int rollBackObjected() {
+        List<TrainCreditLedger> list = trainCreditLedgerMapper.selectList(
+                new LambdaQueryWrapper<TrainCreditLedger>()
+                        .eq(TrainCreditLedger::getStatus, ST_OBJECTED)
+                        .eq(TrainCreditLedger::getDeleted, 0)
+                        .last("LIMIT 500"));
+        int ok = 0;
+        for (TrainCreditLedger l : list) {
+            try {
+                self.applyRollBack(l);
+                ok++;
+            } catch (Exception e) {
+                log.warn("学时异议回滚失败(跳过): ledgerId={}, err={}", l.getId(), e.getMessage());
+            }
+        }
+        if (ok > 0) {
+            log.info("学时异议回滚完成: 本批 {} 条", ok);
+        }
+        return ok;
+    }
+
+    /** 单条回滚:单事务,ledger objected→rejected(终态)+ attendance 翻转 */
+    @Transactional(rollbackFor = Exception.class)
+    public void applyRollBack(TrainCreditLedger l) {
+        TrainCreditLedger cur = trainCreditLedgerMapper.selectById(l.getId());
+        if (cur == null || !ST_OBJECTED.equals(cur.getStatus())) {
+            return;
+        }
+        Date now = new Date();
+        cur.setStatus(ST_REJECTED);
+        cur.setUpdatedAt(now);
+        trainCreditLedgerMapper.updateById(cur);
+        if (SRC_ATTENDANCE.equals(cur.getSourceType())) {
+            TrainAttendance att = trainAttendanceMapper.selectById(parseLong(cur.getSourceId()));
+            if (att != null && ST_OBJECTED.equals(att.getStatus())) {
+                att.setStatus(ST_REJECTED);
+                att.setUpdatedAt(now);
+                trainAttendanceMapper.updateById(att);
+            }
+        }
+        // pending 已在 object 时扣减,此处无需再动账户
+    }
+
+    @Override
+    public Result<Map<String, Object>> ledgerPending(Boolean isAdmin, 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;
+        Long total = trainCreditLedgerMapper.selectCount(
+                new LambdaQueryWrapper<TrainCreditLedger>()
+                        .eq(TrainCreditLedger::getStatus, ST_PENDING)
+                        .eq(TrainCreditLedger::getDeleted, 0));
+        List<TrainCreditLedger> list = trainCreditLedgerMapper.selectList(
+                new LambdaQueryWrapper<TrainCreditLedger>()
+                        .eq(TrainCreditLedger::getStatus, ST_PENDING)
+                        .eq(TrainCreditLedger::getDeleted, 0)
+                        .orderByAsc(TrainCreditLedger::getEffectiveAt)
+                        .last("LIMIT " + offset + "," + s));
+        List<Map<String, Object>> rows = new ArrayList<>();
+        for (TrainCreditLedger l : list) {
+            rows.add(toLedgerVO(l));
+        }
+        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);
+    }
+}

+ 16 - 0
train-backend/src/main/resources/application.yml

@@ -102,6 +102,22 @@ logging:
 # 应用配置
 app:
   init-test-data: true  # 是否初始化测试/种子数据
+  # 培训签到码有效期(分钟,可配;默认 5)
+  attendance:
+    code-valid-minutes: ${ATTENDANCE_CODE_VALID_MINUTES:5}
+  # 学时生效延迟小时(T+3,可配;默认 72)
+  credit:
+    effective-delay-hours: ${CREDIT_EFFECTIVE_DELAY_HOURS:72}
+
+# cfc 学时回填(train 权威 → cfc 弱一致)
+cfc:
+  credit-sync:
+    retry-max: ${CFC_CREDIT_SYNC_RETRY_MAX:5}
+
+# 定时任务
+task:
+  # 学时到期生效扫描 cron(默认每晚 04:00)
+  credit-scan-cron: "${TASK_CREDIT_SCAN_CRON:0 0 4 * * ?}"
 
 # Admin 登录配置
 admin: