| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155 |
- 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;
- }
- }
|