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.common.Result; 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.HashMap; import java.util.List; import java.util.Map; /** * 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"; /** train.cfc.syncHours 契约错误码(proxy 字符串契约,勿改名) */ private static final Integer CODE_SAME_KEY_DIFF_PAYLOAD = 4092; private static final Integer CODE_VERSION_CONFLICT = 422; private static final Integer CODE_NOT_FOUND = 404; private static final Integer CODE_FORBIDDEN = 403; @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() .eq(TrainCfcSyncLog::getSyncKey, syncKey) .last("LIMIT 1")); if (exist != null && LOG_SUCCESS.equals(exist.getStatus())) { // 幂等键命中成功日志仍须校验载荷:同键异载荷不得静默复用旧结果(C4092,禁止 cfc 学时漏记/错记) if (exist.getHours() != null && !exist.getHours().equals(hours)) { log.warn("cfc 回填幂等键载荷冲突,拒绝静默复用: syncKey={}, hours={}, existingHours={}", syncKey, hours, exist.getHours()); return false; } 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; } /** * train.cfc.syncHours 契约入口(TC-1011 / TR-TC-023):携带幂等键 key、载荷 hours 与重放标识 replay 的 * 同步信封,以 Result.code 显式表达五类边界: *
    *
  1. 同键同载荷重放 → 200 且 data.replay=true(不重复入账);
  2. *
  3. 同键异载荷 → C4092(4092),禁止静默复用旧日志;
  4. *
  5. 对账日志并发更新影响 0 行 → C422(422);
  6. *
  7. 回填目标不存在 → C404(404);
  8. *
  9. 管理端补登非管理员(admin=false)→ C403(403)。
  10. *
* 契约常量(replay/key/payload 语义)保持不变,proxy 字符串契约勿改名。 * * @param admin 管理端补登授权标识;false 视为越权(C403),null/true 为系统内部调用 */ public Result> syncHours(Long userId, String sourceType, String sourceId, Integer hours, Boolean admin) { if (Boolean.FALSE.equals(admin)) { return Result.error(CODE_FORBIDDEN, "非管理员无权补登 cfc 学时"); } if (userId == null || sourceType == null || sourceId == null || hours == null) { return Result.error(400, "学时回填参数不完整"); } String syncKey = sourceType + ":" + sourceId; TrainCfcSyncLog exist = trainCfcSyncLogMapper.selectOne( new LambdaQueryWrapper() .eq(TrainCfcSyncLog::getSyncKey, syncKey) .last("LIMIT 1")); // 幂等:sync_key 命中已成功日志 → 先校验载荷,一致才按重放返回,不一致 C4092 if (exist != null && LOG_SUCCESS.equals(exist.getStatus())) { if (exist.getHours() != null && !exist.getHours().equals(hours)) { return Result.error(CODE_SAME_KEY_DIFF_PAYLOAD, "同幂等键 " + syncKey + " 载荷不一致(hours=" + hours + ")"); } return Result.success(syncResult(syncKey, hours, true)); } // 回填目标不存在:train 用户未关联 cfc 会员 / cfc 会员查无 → C404 TrainUser trainUser = trainUserMapper.selectById(userId); if (trainUser == null || trainUser.getCfcUserId() == null) { return Result.error(CODE_NOT_FOUND, "train 用户未关联 cfc 会员"); } CfcUser cfcUser = cfcUserMapper.selectById(trainUser.getCfcUserId()); if (cfcUser == null) { return Result.error(CODE_NOT_FOUND, "cfc 会员不存在"); } // 推送 cfc(映射未配置时仍记 pending,由补偿扫描重推) 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); } Date now = new Date(); TrainCfcSyncLog syncLog = exist == null ? new TrainCfcSyncLog() : exist; syncLog.setSyncKey(syncKey); syncLog.setSyncType("credit"); syncLog.setUserId(userId); syncLog.setCfcUserId(trainUser.getCfcUserId()); 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); } int affected; if (exist == null) { syncLog.setCreatedAt(now); try { trainCfcSyncLogMapper.insert(syncLog); affected = 1; } catch (Exception e) { affected = 0; log.debug("cfc sync_log 幂等命中: syncKey={}", syncKey); } } else { affected = trainCfcSyncLogMapper.updateById(syncLog); } // 更新影响 0 行(乐观锁冲突/唯一键冲突)→ C422,禁止静默按成功/失败返回 if (affected <= 0) { return Result.error(CODE_VERSION_CONFLICT, "对账日志并发更新冲突,请重试"); } if (!ok) { return Result.error(500, "cfc 学时推送未就绪,已记入重试队列"); } return Result.success(syncResult(syncKey, hours, false)); } /** syncHours 出参信封:幂等键、载荷学时与重放标识(proxy 字符串契约,勿改名)。 */ private Map syncResult(String syncKey, Integer hours, boolean replay) { Map data = new HashMap<>(); data.put("key", syncKey); data.put("hours", hours); data.put("replay", replay); return data; } /** * 实际推送 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 list = trainCfcSyncLogMapper.selectList( new LambdaQueryWrapper() .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; } }