Procházet zdrojové kódy

merge: 合入 S-train-49 的 train.hours.ingest GREEN 实现

liaoxg před 11 hodinami
rodič
revize
3c1eb9ae86

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

@@ -46,6 +46,15 @@ public interface CreditService {
     boolean ledgerPending(Long userId, String sourceType, String sourceId, String category,
                           Integer hours, String desc);
 
+    /**
+     * train.hours.ingest 契约入口:多来源学时入账(返回 Result 而非 boolean,以表达冲突语义)。
+     *
+     * <p>幂等键 (userId, sourceType, sourceId):重放且载荷(category/hours)一致 → 幂等成功;
+     * 同键异载荷 → C4092(4092)。学时单位一律分钟整数。</p>
+     */
+    Result<Map<String, Object>> ingest(Long userId, String sourceType, String sourceId,
+                                       String category, Integer hours, String desc);
+
     /**
      * 全量到期生效:扫描 status=pending 且 effective_at<=now 的台账逐条生效(对齐 FollowUpTask 逐条容错)。
      * 禁止限定「当天」,启动/重启补偿幂等。返回本批生效条数。

+ 81 - 9
train-backend/src/main/java/com/train/service/impl/CreditServiceImpl.java

@@ -50,6 +50,17 @@ public class CreditServiceImpl implements CreditService {
     private static final String CAT_THEORY = "theory";
     private static final String CAT_PRACTICE = "practice";
 
+    /** train.hours.ingest 契约错误码(对齐契约级单测,勿改名) */
+    private static final Integer C_SAME_KEY_DIFF_PAYLOAD = 4092;
+    private static final Integer C_VERSION_CONFLICT = 422;
+    private static final Integer C_NOT_FOUND = 404;
+    private static final Integer C_FORBIDDEN = 403;
+
+    /** train.hours.ingest 学分封顶(分钟):theory 40h / practice 20h / total 90h */
+    private static final int CAP_THEORY = 2400;
+    private static final int CAP_PRACTICE = 1200;
+    private static final int CAP_TOTAL = 5400;
+
     @Resource
     private TrainCreditAccountMapper trainCreditAccountMapper;
     @Resource
@@ -203,19 +214,22 @@ public class CreditServiceImpl implements CreditService {
         }
         TrainCreditLedger l = trainCreditLedgerMapper.selectById(ledgerId);
         if (l == null || (l.getDeleted() != null && l.getDeleted() == 1)) {
-            return Result.error("学时记录不存在");
+            return Result.error(C_NOT_FOUND, "学时记录不存在");
         }
         if (!userId.equals(l.getUserId())) {
-            return Result.error("无权操作他人学时记录");
+            return Result.error(C_FORBIDDEN, "无权操作他人学时记录");
         }
         // 仅 pending 可提异议(已生效走申诉外流程)
         if (!ST_PENDING.equals(l.getStatus())) {
-            return Result.error("当前状态不允许提异议");
+            return Result.error(C_VERSION_CONFLICT, "当前状态不允许提异议");
         }
         l.setStatus(ST_OBJECTED);
         l.setRemark(reason);
         l.setUpdatedAt(new Date());
-        trainCreditLedgerMapper.updateById(l);
+        // 乐观锁:更新影响 0 行 = 并发丢失更新,必须 C422,禁止静默按成功返回
+        if (trainCreditLedgerMapper.updateById(l) <= 0) {
+            return Result.error(C_VERSION_CONFLICT, "学时台账更新冲突");
+        }
         // 回写 attendance(source_id=attendance.id)→ objected,扣减账户 pending
         if (SRC_ATTENDANCE.equals(l.getSourceType())) {
             TrainAttendance att = trainAttendanceMapper.selectById(parseLong(l.getSourceId()));
@@ -307,6 +321,61 @@ public class CreditServiceImpl implements CreditService {
         return true;
     }
 
+    /**
+     * train.hours.ingest 契约入口:多来源学时入账,返回 Result 表达同键异载荷冲突(C4092)。
+     * 幂等键 (userId, sourceType, sourceId) 命中且载荷一致时直接幂等成功,不重复入账。
+     */
+    @Override
+    @Transactional(rollbackFor = Exception.class)
+    public Result<Map<String, Object>> ingest(Long userId, String sourceType, String sourceId,
+                                              String category, Integer hours, String desc) {
+        if (userId == null || sourceType == null || sourceId == null || hours == null || hours <= 0) {
+            return Result.error("参数不完整");
+        }
+        TrainCreditLedger exist = trainCreditLedgerMapper.selectOne(ingestKeyQuery(userId, sourceType, sourceId));
+        if (exist != null) {
+            if (!sameIngestPayload(exist, category, hours)) {
+                return Result.error(C_SAME_KEY_DIFF_PAYLOAD, "同学时来源已存在且载荷不一致");
+            }
+            return Result.success(ingestVO(exist.getId(), true));
+        }
+        if (!ledgerPending(userId, sourceType, sourceId, category, hours, desc)) {
+            // 并发 insert 命中唯一键:回查按幂等键判载荷,异载荷 C4092,否则按幂等成功返回
+            TrainCreditLedger concurrent = trainCreditLedgerMapper.selectOne(ingestKeyQuery(userId, sourceType, sourceId));
+            if (concurrent == null) {
+                return Result.error("学时入账失败");
+            }
+            if (!sameIngestPayload(concurrent, category, hours)) {
+                return Result.error(C_SAME_KEY_DIFF_PAYLOAD, "同学时来源已存在且载荷不一致");
+            }
+            return Result.success(ingestVO(concurrent.getId(), true));
+        }
+        TrainCreditLedger created = trainCreditLedgerMapper.selectOne(ingestKeyQuery(userId, sourceType, sourceId));
+        return Result.success(ingestVO(created == null ? null : created.getId(), false));
+    }
+
+    private LambdaQueryWrapper<TrainCreditLedger> ingestKeyQuery(Long userId, String sourceType, String sourceId) {
+        return new LambdaQueryWrapper<TrainCreditLedger>()
+                .eq(TrainCreditLedger::getUserId, userId)
+                .eq(TrainCreditLedger::getSourceType, sourceType)
+                .eq(TrainCreditLedger::getSourceId, sourceId)
+                .eq(TrainCreditLedger::getDeleted, 0)
+                .last("LIMIT 1");
+    }
+
+    private boolean sameIngestPayload(TrainCreditLedger l, String category, Integer hours) {
+        boolean sameCategory = category == null ? l.getSourceCategory() == null
+                : category.equals(l.getSourceCategory());
+        return sameCategory && hours.equals(l.getHours());
+    }
+
+    private Map<String, Object> ingestVO(Long ledgerId, boolean dedup) {
+        Map<String, Object> vo = new HashMap<>();
+        vo.put("ledgerId", ledgerId);
+        vo.put("dedup", dedup);
+        return vo;
+    }
+
     private int yearOf(Date d) {
         Calendar c = Calendar.getInstance();
         c.setTime(d);
@@ -390,13 +459,15 @@ public class CreditServiceImpl implements CreditService {
         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);
+        // TC-1008 学分封顶:theory≤40h(2400分) / practice≤20h(1200分) / total≤90h(5400分)
+        int add = Math.max(0, h);
+        acc.setEffectiveHours(Math.min(effective + add, CAP_TOTAL));
         if (CAT_THEORY.equals(category)) {
-            acc.setTheoryHours(theory + h);
+            acc.setTheoryHours(Math.min(theory + add, CAP_THEORY));
         } else if (CAT_PRACTICE.equals(category)) {
-            acc.setPracticeHours(practice + h);
+            acc.setPracticeHours(Math.min(practice + add, CAP_PRACTICE));
         }
-        acc.setTotalHours(total + h);
+        acc.setTotalHours(Math.min(total + add, CAP_TOTAL));
         acc.setUpdatedAt(new Date());
         trainCreditAccountMapper.updateById(acc);
     }
@@ -658,7 +729,8 @@ public class CreditServiceImpl implements CreditService {
     public Result<Boolean> disposeObjected(Boolean isAdmin, Long operatorId, Long ledgerId, Boolean approved, String reason) {
         String noAuth = roleGuard.requireAdminRole(isAdmin);
         if (noAuth != null) {
-            return Result.error(noAuth);
+            // 越权处置学时入账结果必须 C403,不得笼统 500
+            return Result.error(C_FORBIDDEN, noAuth);
         }
         if (ledgerId == null) {
             return Result.error("id 不能为空");