package com.klp.service.impl; import com.baomidou.dynamic.datasource.annotation.DS; import com.klp.domain.DrMillProcessRecipeVersion; import com.klp.mapper.DrMillProcessPassMapper; import com.klp.mapper.DrMillProcessRecipeVersionMapper; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; /** * 双机架历史道次版本迁移 * 将所有 version_id IS NULL 的道次归入对应方案的 V1.0 版本 */ @Slf4j @DS("double-rack") @RequiredArgsConstructor @Service public class DrMigrationService { private final DrMillProcessPassMapper passMapper; private final DrMillProcessRecipeVersionMapper versionMapper; @Transactional(rollbackFor = Exception.class) public void migrateOrphanPassesToV1() { List recipeIds = passMapper.selectDistinctRecipeIdsWithOrphanPasses(); if (recipeIds.isEmpty()) { log.info("[DR迁移] 无需迁移:所有道次已绑定版本"); return; } int newVersionCount = 0; int migratedPassCount = 0; for (Long recipeId : recipeIds) { // 幂等:V1.0 已存在则复用,避免重复执行时重复创建 DrMillProcessRecipeVersion v1 = versionMapper.selectV1ByRecipeId(recipeId); if (v1 == null) { v1 = new DrMillProcessRecipeVersion(); v1.setRecipeId(recipeId); v1.setVersionCode("V1.0"); v1.setIsActive(1); // 默认激活 v1.setStatus("1"); // 已发布 v1.setCreateBy("system"); v1.setUpdateBy("system"); v1.setRemark("系统启动时自动迁移历史数据"); versionMapper.insert(v1); newVersionCount++; log.info("[DR迁移] 方案 {} 新建 V1.0,versionId={}", recipeId, v1.getVersionId()); } else { log.info("[DR迁移] 方案 {} 已有 V1.0(versionId={}),直接复用", recipeId, v1.getVersionId()); } int rows = passMapper.updateVersionIdForOrphans(recipeId, v1.getVersionId()); migratedPassCount += rows; log.info("[DR迁移] 方案 {} 迁移 {} 条道次 → versionId={}", recipeId, rows, v1.getVersionId()); } log.info("[DR迁移] 完成:共处理方案 {} 个,新建版本 {} 个,迁移道次 {} 条", recipeIds.size(), newVersionCount, migratedPassCount); } }