Browse Source

feat(train): train.promo.history GREEN 实现使契约单测 8/8 全绿

liaoxg 5 hours ago
parent
commit
526e22e8b3

+ 5 - 0
train-backend/src/main/java/com/train/entity/TrainPromotionRecord.java

@@ -3,6 +3,7 @@ package com.train.entity;
 import com.baomidou.mybatisplus.annotation.IdType;
 import com.baomidou.mybatisplus.annotation.TableId;
 import com.baomidou.mybatisplus.annotation.TableName;
+import com.baomidou.mybatisplus.annotation.Version;
 import lombok.Data;
 
 import java.io.Serializable;
@@ -52,4 +53,8 @@ public class TrainPromotionRecord implements Serializable {
     private Date createdAt;
 
     private Date updatedAt;
+
+    /** 乐观锁版本(履历处置/导出并发冲突 C422) */
+    @Version
+    private Long version;
 }

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

@@ -42,4 +42,13 @@ public interface PromotionService {
 
     /** admin:手动触发周期评定(与 @Scheduled 共用),返回 {processed, granted} */
     Result<Map<String, Object>> scanAndGrant(Boolean isAdmin);
+
+    /**
+     * admin:晋升履历合规举证导出(train.promo.history,TC-1038 / TC-3005)。
+     *
+     * <p>replay=true 表示幂等重放;key 为幂等键,payload 为导出范围/格式/操作人等载荷。
+     * 同一 key 重复重放须返回同一份档案;同键异载荷返回 C4092(4092)。</p>
+     */
+    Result<Map<String, Object>> exportHistory(Boolean isAdmin, Long userId, Boolean replay,
+                                               String key, Map<String, Object> payload);
 }

+ 55 - 3
train-backend/src/main/java/com/train/service/impl/PromotionServiceImpl.java

@@ -35,6 +35,7 @@ import java.util.HashSet;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
 
 /**
  * 晋升域实现。
@@ -65,6 +66,12 @@ public class PromotionServiceImpl implements PromotionService {
     private static final String O_CONFIRMED = "confirmed";
     private static final String BADGE_PREFIX = "lec_t";
 
+    /** train.promo.history 合规举证契约错误码 */
+    private static final int CODE_FORBIDDEN = 403;
+    private static final int CODE_NOT_FOUND = 404;
+    private static final int CODE_VERSION_CONFLICT = 422;
+    private static final int CODE_SAME_KEY_DIFF_PAYLOAD = 4092;
+
     private static final Set<String> ALLOWED_METRICS = new HashSet<>(Arrays.asList(
             "serve_count", "order_count", "rating", "theory_hours", "total_hours", "credit_hours", "exam_score"));
     private static final Set<String> ALLOWED_OPS = new HashSet<>(Arrays.asList(
@@ -72,6 +79,9 @@ public class PromotionServiceImpl implements PromotionService {
 
     private final ObjectMapper objectMapper = new ObjectMapper();
 
+    /** 幂等键 → 导出载荷指纹(同键异载荷 C4092;进程内缓存,重启后以档案为准) */
+    private final Map<String, String> historyExportFingerprints = new ConcurrentHashMap<>();
+
     @Resource
     private TrainPromotionRuleMapper trainPromotionRuleMapper;
     @Resource
@@ -357,14 +367,14 @@ public class PromotionServiceImpl implements PromotionService {
     public Result<Map<String, Object>> rejectRecord(Boolean isAdmin, Long recordId, String reason) {
         String noAuth = roleGuard.requireAdminRole(isAdmin);
         if (noAuth != null) {
-            return Result.error(noAuth);
+            return Result.error(CODE_FORBIDDEN, noAuth);
         }
         if (recordId == null) {
             return Result.error("参数不完整");
         }
         TrainPromotionRecord rec = trainPromotionRecordMapper.selectById(recordId);
         if (rec == null || (rec.getDeleted() != null && rec.getDeleted() == 1)) {
-            return Result.error("晋升记录不存在");
+            return Result.error(CODE_NOT_FOUND, "晋升记录不存在");
         }
         String err = StateGuard.checkPromotion(rec.getStatus(), PR_REJECTED);
         if (err != null) {
@@ -372,12 +382,54 @@ public class PromotionServiceImpl implements PromotionService {
         }
         rec.setStatus(PR_REJECTED);
         rec.setUpdatedAt(new Date());
-        trainPromotionRecordMapper.updateById(rec);
+        int rows = trainPromotionRecordMapper.updateById(rec);
+        if (rows <= 0) {
+            // 并发丢失更新 / 版本不匹配:禁止静默按 200 成功
+            return Result.error(CODE_VERSION_CONFLICT, "并发冲突:履历已被其他操作更新");
+        }
         log.info("晋升记录机构否决: recordId={}, userId={}, authLevel={}, reason={}",
                 recordId, rec.getUserId(), rec.getAuthLevel(), reason);
         return Result.success(recordVO(rec));
     }
 
+    @Override
+    public Result<Map<String, Object>> exportHistory(Boolean isAdmin, Long userId, Boolean replay,
+                                                      String key, Map<String, Object> payload) {
+        String noAuth = roleGuard.requireAdminRole(isAdmin);
+        if (noAuth != null) {
+            return Result.error(CODE_FORBIDDEN, noAuth);
+        }
+        if (userId == null || key == null || key.trim().isEmpty()) {
+            return Result.error("参数不完整");
+        }
+        Map<String, Object> safePayload = payload == null ? new HashMap<String, Object>() : payload;
+        String fingerprint = writeJson(safePayload);
+        if (fingerprint == null) {
+            fingerprint = "";
+        }
+        String previous = historyExportFingerprints.putIfAbsent(key, fingerprint);
+        if (previous != null && !previous.equals(fingerprint)) {
+            return Result.error(CODE_SAME_KEY_DIFF_PAYLOAD, "同一幂等键对应不同导出载荷,禁止静默复用既有档案");
+        }
+        LambdaQueryWrapper<TrainPromotionRecord> q = new LambdaQueryWrapper<TrainPromotionRecord>()
+                .eq(TrainPromotionRecord::getUserId, userId)
+                .eq(TrainPromotionRecord::getDeleted, 0)
+                .orderByAsc(TrainPromotionRecord::getAppliedAt);
+        List<TrainPromotionRecord> records = trainPromotionRecordMapper.selectList(q);
+        List<Map<String, Object>> rows = new ArrayList<>();
+        for (TrainPromotionRecord r : records) {
+            rows.add(recordVO(r));
+        }
+        Map<String, Object> data = new HashMap<>();
+        data.put("key", key);
+        data.put("replay", Boolean.TRUE.equals(replay));
+        data.put("payload", safePayload);
+        data.put("total", rows.size());
+        data.put("list", rows);
+        data.put("exportedAt", new Date());
+        return Result.success(data);
+    }
+
     @Override
     public Result<Map<String, Object>> scanAndGrant(Boolean isAdmin) {
         String noAuth = roleGuard.requireAdminRole(isAdmin);

+ 4 - 0
train-backend/src/main/resources/schema.sql

@@ -1020,11 +1020,15 @@ CREATE TABLE IF NOT EXISTS train_promotion_record (
     deleted TINYINT DEFAULT 0 COMMENT '软删除:0正常/1删除',
     created_at DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
     updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
+    version BIGINT DEFAULT 1 COMMENT '乐观锁版本(履历处置/导出并发冲突 C422)',
     INDEX idx_user_id (user_id),
     INDEX idx_rule_id (rule_id),
     INDEX idx_auth_level (auth_level)
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='晋升记录(履历留痕)';
 
+-- 存量库补列(幂等:重复列报错被 DatabaseInitializer 吞掉,属预期)
+ALTER TABLE train_promotion_record ADD COLUMN version BIGINT DEFAULT 1 COMMENT '乐观锁版本(履历处置/导出并发冲突 C422)';
+
 -- >>>>>>>>> 履约派单域 <<<<<<<<<
 
 -- 14) 派单留痕(uk order_id+worker_id 防重复;工单本体仍在 train_service_order)