CfcCreditSyncService.java 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. package com.train.service;
  2. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  3. import com.train.cfc.entity.CfcUser;
  4. import com.train.cfc.mapper.CfcUserMapper;
  5. import com.train.entity.TrainCfcSyncLog;
  6. import com.train.entity.TrainUser;
  7. import com.train.mapper.TrainCfcSyncLogMapper;
  8. import com.train.mapper.TrainUserMapper;
  9. import lombok.extern.slf4j.Slf4j;
  10. import org.springframework.beans.factory.annotation.Value;
  11. import org.springframework.stereotype.Service;
  12. import javax.annotation.Resource;
  13. import java.util.Date;
  14. import java.util.List;
  15. /**
  16. * cfc 学时回填(train 权威 → cfc 弱一致)
  17. *
  18. * 幂等键:sync_key = sourceType:sourceId(如 "attendance:123")。
  19. * 失败 warn 不阻塞,重试至 retry-max;cfc 不可达或目标未就绪时日志置 pending,由重试扫描补偿。
  20. *
  21. * cfc 隔离红线:所有 cfc 读写仅经 com.train.cfc 方言 Mapper,本 Service 是 train 学时回填 cfc 的唯一出口。
  22. */
  23. @Slf4j
  24. @Service
  25. public class CfcCreditSyncService {
  26. private static final String LOG_PENDING = "pending";
  27. private static final String LOG_SUCCESS = "success";
  28. private static final String LOG_FAILED = "failed";
  29. @Resource
  30. private TrainCfcSyncLogMapper trainCfcSyncLogMapper;
  31. @Resource
  32. private TrainUserMapper trainUserMapper;
  33. @Resource
  34. private CfcUserMapper cfcUserMapper;
  35. /** cfc 回填失败最大重推次数 */
  36. @Value("${cfc.credit-sync.retry-max:5}")
  37. private Integer retryMax;
  38. /**
  39. * 回填一条学时到 cfc(学时生效后由 CreditEffectiveManager 触发)。
  40. *
  41. * @param userId train 用户ID
  42. * @param sourceType 来源类型(attendance/exam/practice/...)
  43. * @param sourceId 来源业务ID(如 attendance.id)
  44. * @param hours 学时(分钟整数)
  45. * @return true=推送成功;false=推送失败或目标未就绪(记日志,等待重试)
  46. */
  47. public boolean push(Long userId, String sourceType, String sourceId, Integer hours) {
  48. if (userId == null || sourceType == null || sourceId == null || hours == null) {
  49. return false;
  50. }
  51. String syncKey = sourceType + ":" + sourceId;
  52. // 幂等:sync_key 命中已成功 → 跳过
  53. TrainCfcSyncLog exist = trainCfcSyncLogMapper.selectOne(
  54. new LambdaQueryWrapper<TrainCfcSyncLog>()
  55. .eq(TrainCfcSyncLog::getSyncKey, syncKey)
  56. .last("LIMIT 1"));
  57. if (exist != null && LOG_SUCCESS.equals(exist.getStatus())) {
  58. log.debug("cfc 回填幂等命中,跳过: syncKey={}", syncKey);
  59. return true;
  60. }
  61. TrainCfcSyncLog syncLog = exist == null ? new TrainCfcSyncLog() : exist;
  62. Date now = new Date();
  63. boolean ok = false;
  64. String lastError = null;
  65. try {
  66. ok = doPush(userId, hours);
  67. } catch (Exception e) {
  68. lastError = e.getMessage();
  69. log.warn("cfc 回填推送异常: userId={}, syncKey={}, hours={}, err={}", userId, syncKey, hours, lastError);
  70. }
  71. // 写/更新日志
  72. syncLog.setSyncKey(syncKey);
  73. syncLog.setSyncType("credit");
  74. syncLog.setUserId(userId);
  75. syncLog.setSourceType(sourceType);
  76. syncLog.setSourceId(sourceId);
  77. syncLog.setHours(hours);
  78. syncLog.setUpdatedAt(now);
  79. if (ok) {
  80. syncLog.setStatus(LOG_SUCCESS);
  81. syncLog.setLastError(null);
  82. syncLog.setSyncedAt(now);
  83. } else {
  84. int retry = (exist != null && exist.getRetryCount() != null ? exist.getRetryCount() : 0) + 1;
  85. syncLog.setStatus(retry >= retryMax ? LOG_FAILED : LOG_PENDING);
  86. syncLog.setRetryCount(retry);
  87. syncLog.setLastError(lastError == null ? "目标未就绪/未配置映射" : lastError);
  88. }
  89. if (exist == null) {
  90. syncLog.setCreatedAt(now);
  91. try {
  92. trainCfcSyncLogMapper.insert(syncLog);
  93. } catch (Exception e) {
  94. // 并发首建:uk(sync_key) 冲突可忽略
  95. log.debug("cfc sync_log 幂等命中: syncKey={}", syncKey);
  96. }
  97. } else {
  98. trainCfcSyncLogMapper.updateById(syncLog);
  99. }
  100. return ok;
  101. }
  102. /**
  103. * 实际推送 cfc:解析 cfc 会员并校验就绪;未就绪返回 false(记日志,等待重试)。
  104. * cfc 侧学时落点由 category 映射决定,train 侧无映射时不强行写入,避免污染 cfc 数据。
  105. */
  106. private boolean doPush(Long userId, Integer hours) {
  107. TrainUser trainUser = trainUserMapper.selectById(userId);
  108. if (trainUser == null || trainUser.getCfcUserId() == null) {
  109. log.warn("cfc 回填跳过(train 用户未关联 cfc 会员): userId={}", userId);
  110. return false;
  111. }
  112. CfcUser cfcUser = cfcUserMapper.selectById(trainUser.getCfcUserId());
  113. if (cfcUser == null) {
  114. log.warn("cfc 回填跳过(cfc 会员不存在): userId={}, cfcUserId={}", userId, trainUser.getCfcUserId());
  115. return false;
  116. }
  117. // cfc 学时落点需要 category 映射(如 attendance→planner_cert_categories.id),
  118. // 当前 M2 未配置映射,学时仅在日志待推送状态保留,由管理端补登 /api/admin/planner-certifications/sync-hours。
  119. log.warn("cfc 学时映射未配置,记录待推送: userId={}, cfcUserId={}, hours={} 分钟", userId, trainUser.getCfcUserId(), hours);
  120. return false;
  121. }
  122. /**
  123. * 补偿重推(由 CreditEffectiveManager 调用):扫描 pending 日志重推。
  124. */
  125. public int retryPending() {
  126. List<TrainCfcSyncLog> list = trainCfcSyncLogMapper.selectList(
  127. new LambdaQueryWrapper<TrainCfcSyncLog>()
  128. .eq(TrainCfcSyncLog::getStatus, LOG_PENDING)
  129. .last("LIMIT 500"));
  130. int ok = 0;
  131. for (TrainCfcSyncLog l : list) {
  132. try {
  133. boolean done = push(l.getUserId(), l.getSourceType(), l.getSourceId(), l.getHours());
  134. if (done) {
  135. ok++;
  136. }
  137. } catch (Exception e) {
  138. log.warn("cfc 回填补偿重推异常: syncKey={}, err={}", l.getSyncKey(), e.getMessage());
  139. }
  140. }
  141. if (ok > 0) {
  142. log.info("cfc 回填补偿重推完成: 本批 {} 条", ok);
  143. }
  144. return ok;
  145. }
  146. }