下发修改

parent c5ab1f7a
...@@ -23,6 +23,8 @@ import java.util.Collections; ...@@ -23,6 +23,8 @@ import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import static com.aps.common.util.R.ok;
@RestController @RestController
@RequestMapping("/queryChromosome") @RequestMapping("/queryChromosome")
@Tag(name = "甘特图数据查询", description = "甘特图数据查询") @Tag(name = "甘特图数据查询", description = "甘特图数据查询")
...@@ -52,7 +54,6 @@ public class ChromosomeDataController { ...@@ -52,7 +54,6 @@ public class ChromosomeDataController {
@PathVariable String entityName, @PathVariable String entityName,
@RequestBody Paged paged) { @RequestBody Paged paged) {
// 获取sceneId(文件实体需要,数据库实体可选) // 获取sceneId(文件实体需要,数据库实体可选)
String sceneId = paged.getCondition("sceneId") != null ? String sceneId = paged.getCondition("sceneId") != null ?
paged.getCondition("sceneId").getFieldValue() : null; paged.getCondition("sceneId").getFieldValue() : null;
...@@ -64,7 +65,7 @@ public class ChromosomeDataController { ...@@ -64,7 +65,7 @@ public class ChromosomeDataController {
Map<String, Object> result = chromosomeDataService.queryChromosomeDataWithConditions( Map<String, Object> result = chromosomeDataService.queryChromosomeDataWithConditions(
sceneId, entityName, paged); sceneId, entityName, paged);
return R.ok(result); return ok(result);
} }
...@@ -85,7 +86,6 @@ public class ChromosomeDataController { ...@@ -85,7 +86,6 @@ public class ChromosomeDataController {
@PathVariable String entityName, @PathVariable String entityName,
@RequestBody Paged paged) { @RequestBody Paged paged) {
// 获取sceneId(文件实体需要,数据库实体可选) // 获取sceneId(文件实体需要,数据库实体可选)
String sceneId = paged.getCondition("sceneId") != null ? String sceneId = paged.getCondition("sceneId") != null ?
paged.getCondition("sceneId").getFieldValue() : null; paged.getCondition("sceneId").getFieldValue() : null;
...@@ -98,12 +98,11 @@ public class ChromosomeDataController { ...@@ -98,12 +98,11 @@ public class ChromosomeDataController {
// 直接调用服务层的list查询方法 // 直接调用服务层的list查询方法
List<Object> result = chromosomeDataService.queryChromosomeDataList(sceneId, entityName, paged); List<Object> result = chromosomeDataService.queryChromosomeDataList(sceneId, entityName, paged);
if (result == null) { if (result == null) {
return R.ok(Collections.emptyList(), "查询成功,但未找到匹配的数据"); return ok(Collections.emptyList(), "查询成功,但未找到匹配的数据");
} }
return R.ok(result); return ok(result);
} }
...@@ -124,17 +123,18 @@ public class ChromosomeDataController { ...@@ -124,17 +123,18 @@ public class ChromosomeDataController {
@PathVariable String entityName, @PathVariable String entityName,
@RequestParam String id) { @RequestParam String id) {
// 参数校验
if (id == null || id.isEmpty()) {
return R.ok(null);
}
// 文件实体必须要有sceneId // 文件实体必须要有sceneId
if (isFileEntity(entityName) && (sceneId == null || sceneId.isEmpty())) { if (isFileEntity(entityName) && (sceneId == null || sceneId.isEmpty())) {
return R.failed("文件实体查询时sceneId不能为空"); return R.ok(null);
} }
Object result = chromosomeDataService.queryChromosomeDataById(sceneId, entityName, id); Object result = chromosomeDataService.queryChromosomeDataById(sceneId, entityName, id);
return ok(result);
return R.ok(result);
} }
...@@ -164,20 +164,25 @@ public class ChromosomeDataController { ...@@ -164,20 +164,25 @@ public class ChromosomeDataController {
@Parameter(description = "要更新的数据 (必须包含id字段)", required = true) @Parameter(description = "要更新的数据 (必须包含id字段)", required = true)
@RequestBody Map<String, Object> data) { @RequestBody Map<String, Object> data) {
// 参数校验
if (data == null || data.isEmpty()) {
throw new RuntimeException("更新数据不能为空");
}
if (data.get("id") == null) {
throw new RuntimeException("更新数据必须包含id字段");
}
// 文件实体必须要有sceneId // 文件实体必须要有sceneId
if (isFileEntity(entityName) && (sceneId == null || sceneId.isEmpty())) { if (isFileEntity(entityName) && (sceneId == null || sceneId.isEmpty())) {
throw new RuntimeException("文件实体更新时sceneId不能为空"); throw new RuntimeException("文件实体更新时sceneId不能为空");
} }
if (entityName.equalsIgnoreCase("machine")){
if (entityName.equalsIgnoreCase("machine")) {
return chromosomeDataService.updateMachineOption(sceneId, taskId, data); return chromosomeDataService.updateMachineOption(sceneId, taskId, data);
} }
boolean success = chromosomeDataService.updateChromosomeData(sceneId, entityName, data); boolean success = chromosomeDataService.updateChromosomeData(sceneId, entityName, data);
return R.ok("更新成功"); return ok("更新成功");
} }
...@@ -196,112 +201,10 @@ public class ChromosomeDataController { ...@@ -196,112 +201,10 @@ public class ChromosomeDataController {
public R<List<FieldInfo>> getEntityInfo( public R<List<FieldInfo>> getEntityInfo(
@Parameter(description = "实体名称", required = true) @Parameter(description = "实体名称", required = true)
@PathVariable String entityName) { @PathVariable String entityName) {
System.out.println("getEntityInfo");
List<FieldInfo> fieldInfos = chromosomeDataService.getEntityInfo(entityName); List<FieldInfo> fieldInfos = chromosomeDataService.getEntityInfo(entityName);
return R.ok(fieldInfos); return ok(fieldInfos);
} }
//
// // 处理setupTime字段
// if (data.containsKey("setupTime")) {
// Object setupTimeObj = data.get("setupTime");
// if (setupTimeObj instanceof Integer) {
// machineOption.setSetupTime((Integer) setupTimeObj);
// } else if (setupTimeObj instanceof Long) {
// machineOption.setSetupTime(((Long) setupTimeObj).intValue());
// } else if (setupTimeObj instanceof String) {
// machineOption.setSetupTime(Integer.parseInt((String) setupTimeObj));
// }
// }
//
// // 处理teardownTime字段
// if (data.containsKey("teardownTime")) {
// Object teardownTimeObj = data.get("teardownTime");
// if (teardownTimeObj instanceof Integer) {
// machineOption.setTeardownTime((Integer) teardownTimeObj);
// } else if (teardownTimeObj instanceof Long) {
// machineOption.setTeardownTime(((Long) teardownTimeObj).intValue());
// } else if (teardownTimeObj instanceof String) {
// machineOption.setTeardownTime(Integer.parseInt((String) teardownTimeObj));
// }
// }
//
// // 处理contantTime字段
// if (data.containsKey("contantTime")) {
// Object contantTimeObj = data.get("contantTime");
// if (contantTimeObj instanceof Integer) {
// machineOption.setContantTime((Integer) contantTimeObj);
// } else if (contantTimeObj instanceof Long) {
// machineOption.setContantTime(((Long) contantTimeObj).intValue());
// } else if (contantTimeObj instanceof String) {
// machineOption.setContantTime(Integer.parseInt((String) contantTimeObj));
// }
// }
// // 处理equipCode字段
// if (data.containsKey("equipCode")) {
// machineOption.setEquipCode(String.valueOf(data.get("equipCode")));
// }
//
// // 处理resourceCode字段
// if (data.containsKey("resourceCode")) {
// machineOption.setResourceCode(String.valueOf(data.get("resourceCode")));
// }
// 忽略id等未知字段
private boolean updateMachineOptionsForEntry(Entry targetEntry, List<?> machineOptions, ObjectMapper objectMapper) {
boolean allSuccess = true;
for (Object optionObj : machineOptions) {
if (!(optionObj instanceof Map)) {
allSuccess = false;
continue;
}
Map<?, ?> optionMap = (Map<?, ?>) optionObj;
// 获取machineId
Object machineIdObj = optionMap.get("machineId");
if (machineIdObj == null) {
allSuccess = false;
continue;
}
String machineOptionId = String.valueOf(machineIdObj);
// 在entry的machineOptions列表中找到对应的machineOption
MachineOption targetMachineOption = null;
for (MachineOption machineOption : targetEntry.getMachineOptions()) {
if (String.valueOf(machineOption.getMachineId()).equals(machineOptionId)) {
targetMachineOption = machineOption;
break;
}
}
if (targetMachineOption == null) {
allSuccess = false;
continue;
}
// 更新machineOption的字段
MachineOption updatedMachineOption = objectMapper.convertValue(optionMap, MachineOption.class);
// 替换原来的machineOption
int index = targetEntry.getMachineOptions().indexOf(targetMachineOption);
targetEntry.getMachineOptions().set(index, updatedMachineOption);
}
return allSuccess;
}
/** /**
* 判断是否为文件实体 * 判断是否为文件实体
*/ */
......
...@@ -280,7 +280,7 @@ if(finishedOrder==null||finishedOrder.size()==0) ...@@ -280,7 +280,7 @@ if(finishedOrder==null||finishedOrder.size()==0)
public void decode(Chromosome chromosome) { public void decode(Chromosome chromosome) {
List<OrderMaterialRequirement> orderMaterials = materialRequirementService.buildMultiLevelRequirementNetwork(chromosome, sceneId, baseTime,_globalParam); // List<OrderMaterialRequirement> orderMaterials = materialRequirementService.buildMultiLevelRequirementNetwork(chromosome, sceneId, baseTime,_globalParam);
if(_globalParam.isIsCheckSf()) { if(_globalParam.isIsCheckSf()) {
int isnew= generateGlobalOpList(chromosome); int isnew= generateGlobalOpList(chromosome);
......
...@@ -4,6 +4,7 @@ import cn.hutool.core.bean.BeanUtil; ...@@ -4,6 +4,7 @@ import cn.hutool.core.bean.BeanUtil;
import com.aps.common.util.R; import com.aps.common.util.R;
import com.aps.entity.Algorithm.Chromosome; import com.aps.entity.Algorithm.Chromosome;
import com.aps.entity.Algorithm.GAScheduleResult; import com.aps.entity.Algorithm.GAScheduleResult;
import com.aps.entity.Algorithm.OrderMaterialRequirement;
import com.aps.entity.ProdProcessExec; import com.aps.entity.ProdProcessExec;
import com.aps.entity.Algorithm.GlobalOperationInfo; import com.aps.entity.Algorithm.GlobalOperationInfo;
import com.aps.entity.Algorithm.IDAndChildID.GroupResult; import com.aps.entity.Algorithm.IDAndChildID.GroupResult;
...@@ -29,6 +30,7 @@ import org.springframework.util.CollectionUtils; ...@@ -29,6 +30,7 @@ import org.springframework.util.CollectionUtils;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.time.ZoneOffset;
import java.util.*; import java.util.*;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors; import java.util.stream.Collectors;
...@@ -72,6 +74,21 @@ public class ChromosomeDataService { ...@@ -72,6 +74,21 @@ public class ChromosomeDataService {
*/ */
private final ConcurrentHashMap<Class<?>, Map<String, String>> fieldCommentCache = new ConcurrentHashMap<>(); private final ConcurrentHashMap<Class<?>, Map<String, String>> fieldCommentCache = new ConcurrentHashMap<>();
/**
* 实体配置缓存,避免重复创建配置
*/
private final ConcurrentHashMap<String, EntityConfig> entityConfigCache = new ConcurrentHashMap<>();
/**
* 文件数据查询缓存,避免重复加载文件
*/
private final ConcurrentHashMap<String, Object> fileDataCache = new ConcurrentHashMap<>();
/**
* 反射字段缓存,避免重复反射操作
*/
private final ConcurrentHashMap<Class<?>, Map<String, Field>> fieldCache = new ConcurrentHashMap<>();
/** /**
* 根据场景ID和实体名称查询Chromosome中的数据 * 根据场景ID和实体名称查询Chromosome中的数据
*/ */
...@@ -79,18 +96,7 @@ public class ChromosomeDataService { ...@@ -79,18 +96,7 @@ public class ChromosomeDataService {
ObjectMapper objectMapper = new ObjectMapper() ObjectMapper objectMapper = new ObjectMapper()
.registerModule(new JavaTimeModule()) .registerModule(new JavaTimeModule())
.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
// public Object queryChromosomeData(String sceneId, String entityName) {
// EntityConfig config = getEntityConfig(entityName);
//
// if (config.getDataSource() == DataSourceType.FILE) {
// return queryFileData(sceneId, config);
// } else {
// // 数据库实体不需要sceneId,创建空的Paged对象
// Paged paged = new Paged();
// List<Object> result = databaseQueryService.queryDatabaseDataList(config, paged);
// return result;
// }
// }
/** /**
* 驼峰命名转下划线大写:prodProduct -> PROD_PRODUCT, apsOder -> APS_ORDER * 驼峰命名转下划线大写:prodProduct -> PROD_PRODUCT, apsOder -> APS_ORDER
*/ */
...@@ -115,111 +121,9 @@ public class ChromosomeDataService { ...@@ -115,111 +121,9 @@ public class ChromosomeDataService {
result.append(Character.toUpperCase(c)); result.append(Character.toUpperCase(c));
} }
// 特殊处理:apsOder -> APS_ORDER
if (result.toString().equals("APS_ODER")) {
return "APS_ORDER";
}
return result.toString(); return result.toString();
} }
/**
* 查询当前场景排产的成品/半成品物料信息
*/
public Map<String, Object> queryScheduledMaterials(String sceneId, Paged paged) {
try {
// 1. 从文件中加载Chromosome对象
Chromosome chromosome = sceneService.loadChromosomeFromFile(sceneId);
if (chromosome == null || chromosome.getResult() == null) {
return createEmptyPageResult();
}
// 2. 从排产结果中提取产品ID列表
Set<String> productIds = chromosome.getResult().stream()
.map(GAScheduleResult::getProductId)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
if (productIds.isEmpty()) {
return createEmptyPageResult();
}
// 3. 查询MaterialInfo表获取物料详细信息
List<MaterialInfo> materialInfos = queryMaterialInfoByProductIds(productIds, paged);
// 4. 构建分页结果
return buildPageResult(materialInfos, paged);
} catch (Exception e) {
log.error("查询排产物料失败,场景ID: " + sceneId, e);
return createEmptyPageResult();
}
}
/**
* 根据产品ID列表查询MaterialInfo
*/
private List<MaterialInfo> queryMaterialInfoByProductIds(Set<String> productIds, Paged paged) {
// 使用MyBatis-Plus查询
LambdaQueryWrapper<MaterialInfo> wrapper = new LambdaQueryWrapper<>();
wrapper.in(MaterialInfo::getId, productIds)
.eq(MaterialInfo::getIsdeleted, 0);
// 添加额外的查询条件
if (paged.getConditions() != null && !paged.getConditions().isEmpty()) {
for (ConditionEntity condition : paged.getConditions()) {
if (!"sceneId".equals(condition.getFieldName())) {
addConditionToWrapper(wrapper, condition);
}
}
}
// 添加排序
if (paged.getSortByList() != null && !paged.getSortByList().isEmpty()) {
for (String sortBy : paged.getSortByList()) {
String[] parts = sortBy.split(" ");
String fieldName = parts[0];
boolean isAsc = parts.length <= 1 || !"desc".equalsIgnoreCase(parts[1]);
// 根据字段名添加排序
switch (fieldName.toLowerCase()) {
case "id":
wrapper.orderBy(true, isAsc, MaterialInfo::getId);
break;
case "name":
wrapper.orderBy(true, isAsc, MaterialInfo::getName);
break;
case "code":
wrapper.orderBy(true, isAsc, MaterialInfo::getCode);
break;
case "creationtime":
wrapper.orderBy(true, isAsc, MaterialInfo::getCreationtime);
break;
// 可以继续添加其他字段的排序
}
}
}
// 查询数据
List<MaterialInfo> materialInfos;
long total = 0;
if (paged.getPageSize() > 0) {
// Oracle分页查询 - 使用MyBatis-Plus的Page对象
Page<MaterialInfo> page = new Page<>(paged.getPageIndex(), paged.getPageSize());
Page<MaterialInfo> result = materialInfoService.page(page, wrapper);
materialInfos = result.getRecords();
total = result.getTotal();
} else {
materialInfos = materialInfoService.list(wrapper);
total = materialInfos.size();
}
// 将总数存储到paged对象中,供buildPageResult使用
paged.setTotal((int) total);
return materialInfos;
}
/** /**
* 为查询条件包装器添加条件 * 为查询条件包装器添加条件
...@@ -255,63 +159,6 @@ public class ChromosomeDataService { ...@@ -255,63 +159,6 @@ public class ChromosomeDataService {
} }
} }
/**
* 构建分页结果
*/
private Map<String, Object> buildPageResult(List<MaterialInfo> data, Paged paged) {
Map<String, Object> result = new HashMap<>();
result.put("data", data);
result.put("pageIndex", paged.getPageIndex());
result.put("pageSize", paged.getPageSize());
result.put("total", paged.getTotal() != null ? paged.getTotal() : data.size());
return result;
}
/**
* 根据ID查询单个排产物料
*/
private Object queryScheduledMaterialById(String sceneId, String id) {
try {
// 1. 从文件中加载Chromosome对象
Chromosome chromosome = sceneService.loadChromosomeFromFile(sceneId);
if (chromosome == null || chromosome.getResult() == null) {
return null;
}
// 2. 检查该ID是否在排产结果中
boolean isScheduled = chromosome.getResult().stream()
.anyMatch(result -> id.equals(result.getProductId()));
if (!isScheduled) {
return null;
}
// 3. 使用MyBatis-Plus查询MaterialInfo
LambdaQueryWrapper<MaterialInfo> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(MaterialInfo::getId, id)
.eq(MaterialInfo::getIsdeleted, 0);
MaterialInfo materialInfo = materialInfoService.getOne(wrapper);
return materialInfo;
} catch (Exception e) {
log.error("查询排产物料失败,场景ID: " + sceneId + ", 物料ID: " + id, e);
return null;
}
}
/**
* 创建空的分页结果
*/
private Map<String, Object> createEmptyPageResult() {
Map<String, Object> result = new HashMap<>();
result.put("data", Collections.emptyList());
result.put("pageIndex", 1);
result.put("pageSize", 0);
result.put("total", 0);
return result;
}
/** /**
* 获取实体的字段信息 * 获取实体的字段信息
...@@ -413,17 +260,10 @@ public class ChromosomeDataService { ...@@ -413,17 +260,10 @@ public class ChromosomeDataService {
} }
// 处理数据库实体 // 处理数据库实体
else { else {
try { try (// 获取数据库连接
// 获取数据库连接
java.sql.Connection connection = jdbcTemplate.getDataSource().getConnection(); java.sql.Connection connection = jdbcTemplate.getDataSource().getConnection();
// 获取数据库元数据
java.sql.DatabaseMetaData metaData = connection.getMetaData();
// 获取表名
String tableName = config.getTableName();
// 获取表的列信息 // 获取表的列信息
java.sql.ResultSet columns = metaData.getColumns(null, null, tableName, null); java.sql.ResultSet columns = connection.getMetaData().getColumns(null, null, config.getTableName(), null)) {
// 遍历列信息,生成FieldInfo // 遍历列信息,生成FieldInfo
while (columns.next()) { while (columns.next()) {
...@@ -437,10 +277,6 @@ public class ChromosomeDataService { ...@@ -437,10 +277,6 @@ public class ChromosomeDataService {
fieldInfos.add(fieldInfo); fieldInfos.add(fieldInfo);
} }
// 关闭资源
columns.close();
connection.close();
} catch (Exception e) { } catch (Exception e) {
log.error("获取数据库表字段信息失败: {}", e.getMessage(), e); log.error("获取数据库表字段信息失败: {}", e.getMessage(), e);
} }
...@@ -534,71 +370,10 @@ public class ChromosomeDataService { ...@@ -534,71 +370,10 @@ public class ChromosomeDataService {
return fieldDescriptions; return fieldDescriptions;
} }
} }
//
// // 传统方式:手动维护字段描述(作为备用)
// switch (entityName.toLowerCase()) {
// case "order":
// // Order实体字段描述
// fieldDescriptions.put("id", "自增主键");
// fieldDescriptions.put("orderId", "订单ID");
// fieldDescriptions.put("orderCode", "订单编码");
// fieldDescriptions.put("productId", "产品ID");
// fieldDescriptions.put("materialId", "物料ID");
// fieldDescriptions.put("materialCode", "物料编码");
// fieldDescriptions.put("materialName", "物料名称");
// fieldDescriptions.put("serie", "系列");
// fieldDescriptions.put("routingId", "工艺路线ID");
// fieldDescriptions.put("routingCode", "工艺路线编码");
// fieldDescriptions.put("quantity", "订单数量,默认值:100");
// fieldDescriptions.put("sYQuantity", "生产数量");
// fieldDescriptions.put("startDate", "开始日期");
// fieldDescriptions.put("dueDate", "到期日期");
// fieldDescriptions.put("groupStartDate", "组开始日期");
// fieldDescriptions.put("groupDueDate", "组到期日期");
// fieldDescriptions.put("orderCompletion", "订单完成时间");
// fieldDescriptions.put("orderStart", "订单开始时间");
// fieldDescriptions.put("machineProcessingTime", "机器加工时间");
// fieldDescriptions.put("orderFlow", "订单流程");
// fieldDescriptions.put("orderProductTime", "订单生产时间");
// fieldDescriptions.put("tardiness", "延误时间");
// fieldDescriptions.put("priority", "优先级");
// fieldDescriptions.put("canSplit", "是否可拆分,默认值:false");
// fieldDescriptions.put("canInterrupt", "是否可中断,默认值:false");
// fieldDescriptions.put("actualPriority", "实际优先级");
// fieldDescriptions.put("mainId", "主ID");
// fieldDescriptions.put("FinishOrderId", "使用这个半成品的成品工单");
// fieldDescriptions.put("newCreate", "是否新创建,默认值:false");
// fieldDescriptions.put("createBom", "是否创建BOM,默认值:false");
// fieldDescriptions.put("TargetFinishedOperationId", "关联的成品工序ID(核心:明确该半成品服务于哪个成品工序)");
// fieldDescriptions.put("delayHours", "延迟时间");
// fieldDescriptions.put("materialRequirementList", "物料需求");
// break;
// // 可以继续添加其他实体的字段描述
// case "entry":
// // Entry实体字段描述
// // 后续可以补充
// break;
// case "machine":
// // Machine实体字段描述
// // 后续可以补充
// break;
// }
return fieldDescriptions; return fieldDescriptions;
} }
/**
* 尝试从JavaDoc注释中提取字段描述
* @param entityClass 实体类
* @param fieldName 字段名
* @return 字段描述,提取失败返回null
*/
/**
* 从JavaDoc中提取字段注释
* @param clazz 实体类
* @param fieldName 字段名
* @return 字段注释
*/
/** /**
* 从源文件中提取字段注释 * 从源文件中提取字段注释
* @param clazz 实体类 * @param clazz 实体类
...@@ -661,6 +436,8 @@ public class ChromosomeDataService { ...@@ -661,6 +436,8 @@ public class ChromosomeDataService {
filteredMachine.setActualWorkTime(originalMachine.getActualWorkTime()); filteredMachine.setActualWorkTime(originalMachine.getActualWorkTime());
filteredMachine.setRate(originalMachine.getRate()); filteredMachine.setRate(originalMachine.getRate());
filteredMachine.setDepartment(originalMachine.getDepartment()); filteredMachine.setDepartment(originalMachine.getDepartment());
filteredMachine.setShifts(originalMachine.getShifts());
filteredMachine.setMaintenanceWindows(originalMachine.getMaintenanceWindows());
// 不设置不需要的字段:shifts, maintenanceWindows, availability, holidays, shiftsChanged, maintenanceWindowsChanged // 不设置不需要的字段:shifts, maintenanceWindows, availability, holidays, shiftsChanged, maintenanceWindowsChanged
filteredMachines.add(filteredMachine); filteredMachines.add(filteredMachine);
} else { } else {
...@@ -827,6 +604,160 @@ public class ChromosomeDataService { ...@@ -827,6 +604,160 @@ public class ChromosomeDataService {
} else { } else {
return new ArrayList<>(); return new ArrayList<>();
} }
} else if ("ordermaterialrequirement".equalsIgnoreCase(config.getEntityName())) {
// 特殊处理:当实体是OrderMaterialRequirement时,需要先获取Entry列表,再提取所有Entry的OrderMaterialRequirement
EntityConfig entryConfig = new EntityConfig();
entryConfig.setEntityName("entry");
entryConfig.setDataSource(DataSourceType.FILE);
entryConfig.setFieldName("allOperations");
Object entryData = queryFileData(sceneId, entryConfig);
if (entryData instanceof List) {
List<?> entryList = (List<?>) entryData;
List<Object> resultEntries = new ArrayList<>();
// 先将Entry对象转换为Object对象,方便后续处理
for (Object obj : entryList) {
if (obj instanceof Entry) {
Entry entry = (Entry) obj;
// 检查Entry的SceneId是否匹配
if (entry.getSceneId() == null || entry.getSceneId().equals(sceneId)) {
resultEntries.add(obj);
}
}
}
// 提取所有Entry的OrderMaterialRequirement
List<Object> resultOrderMaterialRequirements = new ArrayList<>();
// 加载Chromosome对象,用于获取基准时间和GAScheduleResult
Chromosome chromosome = sceneService.loadChromosomeFromFile(sceneId);
if (chromosome != null) {
// 构建execId到GAScheduleResult的映射
Map<String, GAScheduleResult> execIdToScheduleMap = new HashMap<>();
if (chromosome.getResult() != null) {
for (GAScheduleResult result : chromosome.getResult()) {
if (result.getExecId() != null) {
execIdToScheduleMap.put(result.getExecId(), result);
}
}
}
// 获取基准时间
LocalDateTime baseTime = chromosome.getBaseTime() != null ? chromosome.getBaseTime() : LocalDateTime.now();
for (Object obj : resultEntries) {
if (obj instanceof Entry) {
Entry entry = (Entry) obj;
// 获取该Entry对应的GAScheduleResult
GAScheduleResult gaResult = execIdToScheduleMap.get(entry.getExecId());
LocalDateTime operationStartTime = null;
// 计算工序开始时间
if (gaResult != null) {
operationStartTime = baseTime.plusSeconds((long) gaResult.getStartTime());
}
// 假设Entry类中有getMaterialRequirements方法返回List<OrderMaterialRequirement>
// 这里需要根据实际的字段名和方法名进行调整
try {
// 使用反射获取Entry对象的MaterialRequirements字段
Field materialRequirementsField = Entry.class.getDeclaredField("MaterialRequirements");
materialRequirementsField.setAccessible(true);
Object materialRequirementsObj = materialRequirementsField.get(entry);
if (materialRequirementsObj instanceof List) {
List<?> materialRequirementsList = (List<?>) materialRequirementsObj;
// 遍历MaterialRequirements列表,设置shortageTime字段
for (Object reqObj : materialRequirementsList) {
if (reqObj instanceof OrderMaterialRequirement) {
OrderMaterialRequirement req = (OrderMaterialRequirement) reqObj;
// 将计算出的工序开始时间设置为OrderMaterialRequirement的shortageTime
if (operationStartTime != null) {
req.setShortageTime(operationStartTime);
}
resultOrderMaterialRequirements.add(req);
}
}
}
} catch (Exception e) {
// 如果反射失败,尝试其他可能的字段名
try {
Field materialRequirementsField = Entry.class.getDeclaredField("materialRequirements");
materialRequirementsField.setAccessible(true);
Object materialRequirementsObj = materialRequirementsField.get(entry);
if (materialRequirementsObj instanceof List) {
List<?> materialRequirementsList = (List<?>) materialRequirementsObj;
// 遍历MaterialRequirements列表,设置shortageTime字段
for (Object reqObj : materialRequirementsList) {
if (reqObj instanceof OrderMaterialRequirement) {
OrderMaterialRequirement req = (OrderMaterialRequirement) reqObj;
// 将计算出的工序开始时间设置为OrderMaterialRequirement的shortageTime
if (operationStartTime != null) {
req.setShortageTime(operationStartTime);
}
resultOrderMaterialRequirements.add(req);
}
}
}
} catch (Exception ex) {
// 如果所有尝试都失败,记录错误并继续
log.error("获取Entry的MaterialRequirements失败", ex);
}
}
}
}
} else {
// 如果chromosome为null,使用原来的方式处理
for (Object obj : resultEntries) {
if (obj instanceof Entry) {
Entry entry = (Entry) obj;
// 假设Entry类中有getMaterialRequirements方法返回List<OrderMaterialRequirement>
// 这里需要根据实际的字段名和方法名进行调整
try {
// 使用反射获取Entry对象的MaterialRequirements字段
Field materialRequirementsField = Entry.class.getDeclaredField("MaterialRequirements");
materialRequirementsField.setAccessible(true);
Object materialRequirementsObj = materialRequirementsField.get(entry);
if (materialRequirementsObj instanceof List) {
List<?> materialRequirementsList = (List<?>) materialRequirementsObj;
resultOrderMaterialRequirements.addAll(materialRequirementsList);
}
} catch (Exception e) {
// 如果反射失败,尝试其他可能的字段名
try {
Field materialRequirementsField = Entry.class.getDeclaredField("materialRequirements");
materialRequirementsField.setAccessible(true);
Object materialRequirementsObj = materialRequirementsField.get(entry);
if (materialRequirementsObj instanceof List) {
List<?> materialRequirementsList = (List<?>) materialRequirementsObj;
resultOrderMaterialRequirements.addAll(materialRequirementsList);
}
} catch (Exception ex) {
// 如果所有尝试都失败,记录错误并继续
log.error("获取Entry的MaterialRequirements失败", ex);
}
}
}
}
}
// 应用条件过滤,支持AND/OR关系
if (!CollectionUtils.isEmpty(paged.getConditions())) {
resultOrderMaterialRequirements = filterDataByConditions(resultOrderMaterialRequirements, paged.getConditions(), paged.getAnd());
}
// 应用排序
List<Object> sortedData = sortData(resultOrderMaterialRequirements, paged);
return applyGroupAndFieldsToList(sortedData, paged);
} else {
return new ArrayList<>();
}
} else if ("order".equalsIgnoreCase(config.getEntityName())) { } else if ("order".equalsIgnoreCase(config.getEntityName())) {
// 特殊处理:当实体是Order时,使用orderId字段进行查询 // 特殊处理:当实体是Order时,使用orderId字段进行查询
Object data = queryFileData(sceneId, config); Object data = queryFileData(sceneId, config);
...@@ -878,9 +809,283 @@ public class ChromosomeDataService { ...@@ -878,9 +809,283 @@ public class ChromosomeDataService {
if (paged.getFields() != null && !paged.getFields().trim().isEmpty()) { if (paged.getFields() != null && !paged.getFields().trim().isEmpty()) {
result = projectListToFields(result, paged.getFields()); result = projectListToFields(result, paged.getFields());
} }
return (List<Object>) result; // 应用分页
if (paged.getPageIndex() != null && paged.getPageSize() != null && paged.getPageSize() > 0) {
int pageIndex = paged.getPageIndex();
int pageSize = paged.getPageSize();
int start = (pageIndex - 1) * pageSize;
int end = Math.min(start + pageSize, result.size());
if (start >= result.size()) {
return new ArrayList<>();
}
result = result.subList(start, end);
}
// 格式化时间字段
List<Object> formattedResult = new ArrayList<>();
for (Object item : result) {
formattedResult.add(formatFileEntityTimeFields(item));
}
return formattedResult;
} }
/**
* 格式化文件实体的时间字段
* @param data 要格式化的数据
* @return 格式化后的数据
*/
private Object formatFileEntityTimeFields(Object data) {
if (data == null) {
return null;
}
// 处理Map类型的对象(如分组结果)
if (data instanceof Map) {
Map<?, ?> originalMap = (Map<?, ?>) data;
Map<String, Object> formattedMap = new LinkedHashMap<>();
for (Map.Entry<?, ?> entry : originalMap.entrySet()) {
String key = entry.getKey().toString();
Object value = entry.getValue();
// 检查值是否是时间类型
if (value instanceof LocalDateTime) {
LocalDateTime dateTime = (LocalDateTime) value;
// 转换为OffsetDateTime以包含时区信息
OffsetDateTime offsetDateTime = dateTime.atOffset(ZoneOffset.UTC);
// 格式化时间为指定格式
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
String formattedTime = offsetDateTime.format(formatter);
formattedMap.put(key, formattedTime);
} else {
formattedMap.put(key, value);
}
}
return formattedMap;
}
// 处理普通实体类对象
// 为了简化,我们返回一个包含格式化时间的Map
Map<String, Object> formattedData = new LinkedHashMap<>();
// 获取对象的所有字段(包括父类字段)
List<Field> fields = new ArrayList<>();
Class<?> currentClass = data.getClass();
while (currentClass != null && currentClass != Object.class) {
fields.addAll(Arrays.asList(currentClass.getDeclaredFields()));
currentClass = currentClass.getSuperclass();
}
// 遍历所有字段
for (Field field : fields) {
// 跳过静态字段,避免反射访问权限错误
if (Modifier.isStatic(field.getModifiers())) {
continue;
}
field.setAccessible(true);
try {
Object value = field.get(data);
// 检查是否是时间类型字段
if (value instanceof LocalDateTime) {
LocalDateTime dateTime = (LocalDateTime) value;
// 转换为OffsetDateTime以包含时区信息
OffsetDateTime offsetDateTime = dateTime.atOffset(ZoneOffset.UTC);
// 格式化时间为指定格式
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
String formattedTime = offsetDateTime.format(formatter);
formattedData.put(field.getName(), formattedTime);
} else {
formattedData.put(field.getName(), value);
}
} catch (Exception e) {
// 忽略字段访问错误
}
}
return formattedData;
}
/**
* 处理materialInfo实体的特殊查询逻辑
*/
private boolean handleMaterialInfoQuery(String sceneId, Paged paged) {
boolean hasProductIds = false;
try {
// 从文件中加载Chromosome对象
Chromosome chromosome = sceneService.loadChromosomeFromFile(sceneId);
if (chromosome != null && chromosome.getResult() != null) {
// 从排产结果中提取产品ID列表
Set<String> productIds = chromosome.getResult().stream()
.map(GAScheduleResult::getProductId)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
if (!productIds.isEmpty()) {
// 创建物料ID的IN条件
ConditionEntity idCondition = new ConditionEntity();
idCondition.setFieldName("id");
idCondition.setConditionalType("IN");
idCondition.setFieldValue(String.join(",", productIds));
// 添加到conditions中
if (paged.getConditions() == null) {
paged.setConditions(new ArrayList<>());
}
paged.getConditions().add(idCondition);
hasProductIds = true;
}
}
} catch (Exception e) {
log.error("提取排产物料ID失败,场景ID: " + sceneId, e);
hasProductIds = false;
} finally {
// 无论是否发生异常,都移除原始的sceneId条件
if (paged.getConditions() != null) {
paged.getConditions().removeIf(condition -> "sceneId".equalsIgnoreCase(condition.getFieldName()));
}
}
return hasProductIds;
}
/**
* 从Entry列表中提取OrderMaterialRequirement
*/
private List<Object> extractOrderMaterialRequirements(String sceneId, List<Object> resultEntries) {
List<Object> resultOrderMaterialRequirements = new ArrayList<>();
// 加载Chromosome对象,用于获取基准时间和GAScheduleResult
Chromosome chromosome = sceneService.loadChromosomeFromFile(sceneId);
if (chromosome != null) {
// 构建execId到GAScheduleResult的映射
Map<String, GAScheduleResult> execIdToScheduleMap = new HashMap<>();
if (chromosome.getResult() != null) {
for (GAScheduleResult result : chromosome.getResult()) {
if (result.getExecId() != null) {
execIdToScheduleMap.put(result.getExecId(), result);
}
}
}
// 获取基准时间
LocalDateTime baseTime = chromosome.getBaseTime() != null ? chromosome.getBaseTime() : LocalDateTime.now();
for (Object obj : resultEntries) {
if (obj instanceof Entry) {
Entry entry = (Entry) obj;
extractMaterialRequirementsWithTime(entry, execIdToScheduleMap, baseTime, resultOrderMaterialRequirements);
}
}
} else {
// 如果chromosome为null,使用原来的方式处理
for (Object obj : resultEntries) {
if (obj instanceof Entry) {
Entry entry = (Entry) obj;
extractMaterialRequirements(entry, resultOrderMaterialRequirements);
}
}
}
return resultOrderMaterialRequirements;
}
/**
* 提取带时间信息的物料需求
*/
private void extractMaterialRequirementsWithTime(Entry entry, Map<String, GAScheduleResult> execIdToScheduleMap,
LocalDateTime baseTime, List<Object> resultList) {
// 获取该Entry对应的GAScheduleResult
GAScheduleResult gaResult = execIdToScheduleMap.get(entry.getExecId());
LocalDateTime operationStartTime = null;
// 计算工序开始时间
if (gaResult != null) {
operationStartTime = baseTime.plusSeconds((long) gaResult.getStartTime());
}
// 尝试获取Entry对象的MaterialRequirements字段
try {
// 使用反射获取Entry对象的MaterialRequirements字段
Field materialRequirementsField = Entry.class.getDeclaredField("MaterialRequirements");
materialRequirementsField.setAccessible(true);
Object materialRequirementsObj = materialRequirementsField.get(entry);
if (materialRequirementsObj instanceof List) {
List<?> materialRequirementsList = (List<?>) materialRequirementsObj;
// 遍历MaterialRequirements列表,设置shortageTime字段
for (Object reqObj : materialRequirementsList) {
if (reqObj instanceof OrderMaterialRequirement) {
OrderMaterialRequirement req = (OrderMaterialRequirement) reqObj;
// 将计算出的工序开始时间设置为OrderMaterialRequirement的shortageTime
if (operationStartTime != null) {
req.setShortageTime(operationStartTime);
}
resultList.add(req);
}
}
}
} catch (Exception e) {
// 如果反射失败,尝试其他可能的字段名
try {
Field materialRequirementsField = Entry.class.getDeclaredField("materialRequirements");
materialRequirementsField.setAccessible(true);
Object materialRequirementsObj = materialRequirementsField.get(entry);
if (materialRequirementsObj instanceof List) {
List<?> materialRequirementsList = (List<?>) materialRequirementsObj;
// 遍历MaterialRequirements列表,设置shortageTime字段
for (Object reqObj : materialRequirementsList) {
if (reqObj instanceof OrderMaterialRequirement) {
OrderMaterialRequirement req = (OrderMaterialRequirement) reqObj;
// 将计算出的工序开始时间设置为OrderMaterialRequirement的shortageTime
if (operationStartTime != null) {
req.setShortageTime(operationStartTime);
}
resultList.add(req);
}
}
}
} catch (Exception ex) {
// 如果所有尝试都失败,记录错误并继续
log.error("获取Entry的MaterialRequirements失败", ex);
}
}
}
/**
* 提取物料需求(不包含时间信息)
*/
private void extractMaterialRequirements(Entry entry, List<Object> resultList) {
// 尝试获取Entry对象的MaterialRequirements字段
try {
// 使用反射获取Entry对象的MaterialRequirements字段
Field materialRequirementsField = Entry.class.getDeclaredField("MaterialRequirements");
materialRequirementsField.setAccessible(true);
Object materialRequirementsObj = materialRequirementsField.get(entry);
if (materialRequirementsObj instanceof List) {
List<?> materialRequirementsList = (List<?>) materialRequirementsObj;
resultList.addAll(materialRequirementsList);
}
} catch (Exception e) {
// 如果反射失败,尝试其他可能的字段名
try {
Field materialRequirementsField = Entry.class.getDeclaredField("materialRequirements");
materialRequirementsField.setAccessible(true);
Object materialRequirementsObj = materialRequirementsField.get(entry);
if (materialRequirementsObj instanceof List) {
List<?> materialRequirementsList = (List<?>) materialRequirementsObj;
resultList.addAll(materialRequirementsList);
}
} catch (Exception ex) {
// 如果所有尝试都失败,记录错误并继续
log.error("获取Entry的MaterialRequirements失败", ex);
}
}
}
/** /**
* 根据ID查询单条数据 * 根据ID查询单条数据
*/ */
...@@ -943,6 +1148,13 @@ public class ChromosomeDataService { ...@@ -943,6 +1148,13 @@ public class ChromosomeDataService {
config.setDataSource(DataSourceType.FILE); config.setDataSource(DataSourceType.FILE);
config.setFieldName("allOperations"); config.setFieldName("allOperations");
} }
// 特殊处理:当实体是OrderMaterialRequirement时,映射到allOperations字段
else if ("ordermaterialrequirement".equalsIgnoreCase(key)) {
config = new EntityConfig();
config.setEntityName(entityName);
config.setDataSource(DataSourceType.FILE);
config.setFieldName("allOperations");
}
// 特殊处理:当实体是KpiMetrics时,映射到kpiMetrics字段 // 特殊处理:当实体是KpiMetrics时,映射到kpiMetrics字段
else if ("kpimetrics".equalsIgnoreCase(key)) { else if ("kpimetrics".equalsIgnoreCase(key)) {
config = new EntityConfig(); config = new EntityConfig();
...@@ -985,8 +1197,21 @@ public class ChromosomeDataService { ...@@ -985,8 +1197,21 @@ public class ChromosomeDataService {
System.out.println("智能表名映射:" + entityName + " -> " + tableName); System.out.println("智能表名映射:" + entityName + " -> " + tableName);
config.setTableName(tableName); config.setTableName(tableName);
// 尝试设置对应的实体类
try {
// 特殊处理:materialInfo 映射到 MaterialInfo
if ("materialinfo".equalsIgnoreCase(entityName)) {
config.setEntityClass(MaterialInfo.class);
} else {
// 假设实体类都在 com.aps.entity 包下
String entityClassName = "com.aps.entity." + entityName.substring(0, 1).toUpperCase() + entityName.substring(1);
Class<?> entityClass = Class.forName(entityClassName);
config.setEntityClass(entityClass);
}
} catch (ClassNotFoundException e) {
// 如果没有对应的实体类,设置为null,查询返回Map // 如果没有对应的实体类,设置为null,查询返回Map
config.setEntityClass(null); config.setEntityClass(null);
}
return config; return config;
} }
...@@ -1020,6 +1245,15 @@ public class ChromosomeDataService { ...@@ -1020,6 +1245,15 @@ public class ChromosomeDataService {
* 查询文件数据 * 查询文件数据
*/ */
private Object queryFileData(String sceneId, EntityConfig config) { private Object queryFileData(String sceneId, EntityConfig config) {
// 生成缓存键
String cacheKey = sceneId + ":" + config.getEntityName() + ":" + config.getFieldName();
// 先从缓存中获取
Object cachedData = fileDataCache.get(cacheKey);
if (cachedData != null) {
return cachedData;
}
Chromosome chromosome = sceneService.loadChromosomeFromFile(sceneId); Chromosome chromosome = sceneService.loadChromosomeFromFile(sceneId);
if (chromosome == null) { if (chromosome == null) {
return null; return null;
...@@ -1028,34 +1262,22 @@ public class ChromosomeDataService { ...@@ -1028,34 +1262,22 @@ public class ChromosomeDataService {
try { try {
String fieldName = config.getFieldName(); String fieldName = config.getFieldName();
// // 特殊处理:当实体是ProdProcessExec时,使用allOperations字段
// if ("prodprocessexec".equalsIgnoreCase(config.getEntityName())) {
// fieldName = "allOperations";
// }
//
// 特殊处理:当实体是MachineOption时,使用allOperations字段 // 特殊处理:当实体是MachineOption时,使用allOperations字段
if ("machineoption".equalsIgnoreCase(config.getEntityName())) { if ("machineoption".equalsIgnoreCase(config.getEntityName())) {
fieldName = "allOperations"; fieldName = "allOperations";
} }
Field field = Chromosome.class.getDeclaredField(fieldName); // 从缓存中获取反射字段
field.setAccessible(true); Field field = getCachedField(Chromosome.class, fieldName);
Object result = field.get(chromosome); Object result = field.get(chromosome);
// // 如果实体是ProdProcessExec,但数据源是Entry,则进行转换
// if ("prodprocessexec".equalsIgnoreCase(config.getEntityName())) {
// return convertEntryToProdProcessExec(result);
// }
// 如果实体是MachineOption,提取Entry中的MachineOption列表 // 如果实体是MachineOption,提取Entry中的MachineOption列表
if ("machineoption".equalsIgnoreCase(config.getEntityName())) { if ("machineoption".equalsIgnoreCase(config.getEntityName())) {
return extractMachineOptionsFromEntries(result); result = extractMachineOptionsFromEntries(result);
} }
// 如果实体是KpiMetrics,直接返回结果 // 缓存结果
if ("kpimetrics".equalsIgnoreCase(config.getEntityName())) { fileDataCache.put(cacheKey, result);
return result;
}
return result; return result;
} catch (NoSuchFieldException e) { } catch (NoSuchFieldException e) {
...@@ -1065,6 +1287,20 @@ public class ChromosomeDataService { ...@@ -1065,6 +1287,20 @@ public class ChromosomeDataService {
} }
} }
/**
* 从缓存中获取反射字段,避免重复反射操作
*/
private Field getCachedField(Class<?> clazz, String fieldName) throws NoSuchFieldException {
Map<String, Field> classFields = fieldCache.computeIfAbsent(clazz, k -> new HashMap<>());
Field field = classFields.get(fieldName);
if (field == null) {
field = clazz.getDeclaredField(fieldName);
field.setAccessible(true);
classFields.put(fieldName, field);
}
return field;
}
/** /**
* 查询文件数据(分页+条件) * 查询文件数据(分页+条件)
*/ */
...@@ -1095,52 +1331,206 @@ public class ChromosomeDataService { ...@@ -1095,52 +1331,206 @@ public class ChromosomeDataService {
} }
} }
} }
// 应用条件过滤,支持AND/OR关系 // 应用条件过滤,支持AND/OR关系
if (!CollectionUtils.isEmpty(paged.getConditions())) { if (!CollectionUtils.isEmpty(paged.getConditions())) {
resultEntries = filterDataByConditions(resultEntries, paged.getConditions(), paged.getAnd()); resultEntries = filterDataByConditions(resultEntries, paged.getConditions(), paged.getAnd());
}
// 提取符合条件的Entry的MachineOptions
List<MachineOption> resultMachineOptions = new ArrayList<>();
for (Object obj : resultEntries) {
if (obj instanceof Entry) {
Entry entry = (Entry) obj;
if (entry.getMachineOptions() != null) {
resultMachineOptions.addAll(entry.getMachineOptions());
}
}
}
data = resultMachineOptions;
} else {
data = new ArrayList<MachineOption>();
}
} else if ("order".equalsIgnoreCase(config.getEntityName())) {
// 特殊处理:当实体是Order时,使用orderId字段进行查询
Object orderData = queryFileData(sceneId, config);
if (orderData instanceof List) {
List<?> orderList = (List<?>) orderData;
List<Object> resultOrders = new ArrayList<>();
// 先将Order对象转换为Object对象,方便后续处理
for (Object obj : orderList) {
if (obj instanceof Order) {
resultOrders.add(obj);
}
}
// 应用条件过滤,支持AND/OR关系
if (!CollectionUtils.isEmpty(paged.getConditions())) {
resultOrders = filterDataByConditions(resultOrders, paged.getConditions(), paged.getAnd());
}
// 应用排序
List<Object> sortedData = sortData(resultOrders, paged);
data = sortedData;
} else {
data = new ArrayList<Order>();
}
} else if ("ordermaterialrequirement".equalsIgnoreCase(config.getEntityName())) {
// 特殊处理:当实体是OrderMaterialRequirement时,需要先获取Entry列表,再提取所有Entry的OrderMaterialRequirement
EntityConfig entryConfig = new EntityConfig();
entryConfig.setEntityName("entry");
entryConfig.setDataSource(DataSourceType.FILE);
entryConfig.setFieldName("allOperations");
Object entryData = queryFileData(sceneId, entryConfig);
if (entryData instanceof List) {
List<?> entryList = (List<?>) entryData;
List<Object> resultEntries = new ArrayList<>();
// 先将Entry对象转换为Object对象,方便后续处理
for (Object obj : entryList) {
if (obj instanceof Entry) {
Entry entry = (Entry) obj;
// 检查Entry的SceneId是否匹配
if (entry.getSceneId() == null || entry.getSceneId().equals(sceneId)) {
resultEntries.add(obj);
}
}
}
// 提取所有Entry的OrderMaterialRequirement
List<Object> resultOrderMaterialRequirements = new ArrayList<>();
// 加载Chromosome对象,用于获取基准时间和GAScheduleResult
Chromosome chromosome = sceneService.loadChromosomeFromFile(sceneId);
if (chromosome != null) {
// 构建execId到GAScheduleResult的映射
Map<String, GAScheduleResult> execIdToScheduleMap = new HashMap<>();
if (chromosome.getResult() != null) {
for (GAScheduleResult result : chromosome.getResult()) {
if (result.getExecId() != null) {
execIdToScheduleMap.put(result.getExecId(), result);
}
}
}
// 获取基准时间
LocalDateTime baseTime = chromosome.getBaseTime() != null ? chromosome.getBaseTime() : LocalDateTime.now();
for (Object obj : resultEntries) {
if (obj instanceof Entry) {
Entry entry = (Entry) obj;
// 获取该Entry对应的GAScheduleResult
GAScheduleResult gaResult = execIdToScheduleMap.get(entry.getExecId());
LocalDateTime operationStartTime = null;
// 计算工序开始时间
if (gaResult != null) {
operationStartTime = baseTime.plusSeconds((long) gaResult.getStartTime());
}
// 假设Entry类中有getMaterialRequirements方法返回List<OrderMaterialRequirement>
// 这里需要根据实际的字段名和方法名进行调整
try {
// 使用反射获取Entry对象的MaterialRequirements字段
Field materialRequirementsField = Entry.class.getDeclaredField("MaterialRequirements");
materialRequirementsField.setAccessible(true);
Object materialRequirementsObj = materialRequirementsField.get(entry);
if (materialRequirementsObj instanceof List) {
List<?> materialRequirementsList = (List<?>) materialRequirementsObj;
// 遍历MaterialRequirements列表,设置shortageTime字段
for (Object reqObj : materialRequirementsList) {
if (reqObj instanceof OrderMaterialRequirement) {
OrderMaterialRequirement req = (OrderMaterialRequirement) reqObj;
// 将计算出的工序开始时间设置为OrderMaterialRequirement的shortageTime
if (operationStartTime != null) {
req.setShortageTime(operationStartTime);
}
resultOrderMaterialRequirements.add(req);
}
}
}
} catch (Exception e) {
// 如果反射失败,尝试其他可能的字段名
try {
Field materialRequirementsField = Entry.class.getDeclaredField("materialRequirements");
materialRequirementsField.setAccessible(true);
Object materialRequirementsObj = materialRequirementsField.get(entry);
if (materialRequirementsObj instanceof List) {
List<?> materialRequirementsList = (List<?>) materialRequirementsObj;
// 遍历MaterialRequirements列表,设置shortageTime字段
for (Object reqObj : materialRequirementsList) {
if (reqObj instanceof OrderMaterialRequirement) {
OrderMaterialRequirement req = (OrderMaterialRequirement) reqObj;
// 将计算出的工序开始时间设置为OrderMaterialRequirement的shortageTime
if (operationStartTime != null) {
req.setShortageTime(operationStartTime);
}
resultOrderMaterialRequirements.add(req);
}
}
} }
} catch (Exception ex) {
// 提取符合条件的Entry的MachineOptions // 如果所有尝试都失败,记录错误并继续
List<MachineOption> resultMachineOptions = new ArrayList<>(); log.error("获取Entry的MaterialRequirements失败", ex);
}
}
}
}
} else {
// 如果chromosome为null,使用原来的方式处理
for (Object obj : resultEntries) { for (Object obj : resultEntries) {
if (obj instanceof Entry) { if (obj instanceof Entry) {
Entry entry = (Entry) obj; Entry entry = (Entry) obj;
if (entry.getMachineOptions() != null) {
resultMachineOptions.addAll(entry.getMachineOptions()); // 假设Entry类中有getMaterialRequirements方法返回List<OrderMaterialRequirement>
// 这里需要根据实际的字段名和方法名进行调整
try {
// 使用反射获取Entry对象的MaterialRequirements字段
Field materialRequirementsField = Entry.class.getDeclaredField("MaterialRequirements");
materialRequirementsField.setAccessible(true);
Object materialRequirementsObj = materialRequirementsField.get(entry);
if (materialRequirementsObj instanceof List) {
List<?> materialRequirementsList = (List<?>) materialRequirementsObj;
resultOrderMaterialRequirements.addAll(materialRequirementsList);
} }
} catch (Exception e) {
// 如果反射失败,尝试其他可能的字段名
try {
Field materialRequirementsField = Entry.class.getDeclaredField("materialRequirements");
materialRequirementsField.setAccessible(true);
Object materialRequirementsObj = materialRequirementsField.get(entry);
if (materialRequirementsObj instanceof List) {
List<?> materialRequirementsList = (List<?>) materialRequirementsObj;
resultOrderMaterialRequirements.addAll(materialRequirementsList);
}
} catch (Exception ex) {
// 如果所有尝试都失败,记录错误并继续
log.error("获取Entry的MaterialRequirements失败", ex);
} }
} }
data = resultMachineOptions;
} else {
data = new ArrayList<MachineOption>();
} }
} else if ("order".equalsIgnoreCase(config.getEntityName())) {
// 特殊处理:当实体是Order时,使用orderId字段进行查询
Object orderData = queryFileData(sceneId, config);
if (orderData instanceof List) {
List<?> orderList = (List<?>) orderData;
List<Object> resultOrders = new ArrayList<>();
// 先将Order对象转换为Object对象,方便后续处理
for (Object obj : orderList) {
if (obj instanceof Order) {
resultOrders.add(obj);
} }
} }
// 应用条件过滤,支持AND/OR关系 // 应用条件过滤,支持AND/OR关系
if (!CollectionUtils.isEmpty(paged.getConditions())) { if (!CollectionUtils.isEmpty(paged.getConditions())) {
resultOrders = filterDataByConditions(resultOrders, paged.getConditions(), paged.getAnd()); resultOrderMaterialRequirements = filterDataByConditions(resultOrderMaterialRequirements, paged.getConditions(), paged.getAnd());
} }
// 应用排序 // 应用排序
List<Object> sortedData = sortData(resultOrders, paged); List<Object> sortedData = sortData(resultOrderMaterialRequirements, paged);
data = sortedData; data = sortedData;
} else { } else {
data = new ArrayList<Order>(); data = new ArrayList<Object>();
} }
} else { } else {
data = queryFileData(sceneId, config); data = queryFileData(sceneId, config);
...@@ -1173,6 +1563,21 @@ public class ChromosomeDataService { ...@@ -1173,6 +1563,21 @@ public class ChromosomeDataService {
List<?> dataList = (List<?>) data; List<?> dataList = (List<?>) data;
if (paged.getGroupName() != null && !paged.getGroupName().trim().isEmpty()) { if (paged.getGroupName() != null && !paged.getGroupName().trim().isEmpty()) {
dataList = groupListByFields(dataList, paged.getGroupName()); dataList = groupListByFields(dataList, paged.getGroupName());
// 确保分组结果根据count倒序排序
if (dataList instanceof List) {
((List<?>) dataList).sort((o1, o2) -> {
if (o1 instanceof Map && o2 instanceof Map) {
Map<?, ?> m1 = (Map<?, ?>) o1;
Map<?, ?> m2 = (Map<?, ?>) o2;
Object count1 = m1.get("count");
Object count2 = m2.get("count");
if (count1 instanceof Number && count2 instanceof Number) {
return ((Number) count2).longValue() - ((Number) count1).longValue() > 0 ? 1 : -1;
}
}
return 0;
});
}
} }
if (paged.getFields() != null && !paged.getFields().trim().isEmpty()) { if (paged.getFields() != null && !paged.getFields().trim().isEmpty()) {
dataList = projectListToFields(dataList, paged.getFields()); dataList = projectListToFields(dataList, paged.getFields());
...@@ -1185,7 +1590,13 @@ public class ChromosomeDataService { ...@@ -1185,7 +1590,13 @@ public class ChromosomeDataService {
List<?> pagedData = dataList.subList(fromIndex, toIndex); List<?> pagedData = dataList.subList(fromIndex, toIndex);
result.put("records", pagedData); // 格式化时间字段
List<Object> formattedPagedData = new ArrayList<>();
for (Object item : pagedData) {
formattedPagedData.add(formatFileEntityTimeFields(item));
}
result.put("records", formattedPagedData);
result.put("totalCount", total); result.put("totalCount", total);
result.put("pageIndex", page); result.put("pageIndex", page);
result.put("size", size); result.put("size", size);
...@@ -1216,7 +1627,7 @@ public class ChromosomeDataService { ...@@ -1216,7 +1627,7 @@ public class ChromosomeDataService {
filteredMachine.setRate(originalMachine.getRate()); filteredMachine.setRate(originalMachine.getRate());
filteredMachine.setDepartment(originalMachine.getDepartment()); filteredMachine.setDepartment(originalMachine.getDepartment());
filteredMachine.setShifts(originalMachine.getShifts()); filteredMachine.setShifts(originalMachine.getShifts());
filteredMachine.setAvailability(originalMachine.getAvailability()); filteredMachine.setMaintenanceWindows(originalMachine.getMaintenanceWindows());
// 不设置不需要的字段:shifts, maintenanceWindows, availability, holidays, shiftsChanged, maintenanceWindowsChanged // 不设置不需要的字段:shifts, maintenanceWindows, availability, holidays, shiftsChanged, maintenanceWindowsChanged
return filteredMachine; return filteredMachine;
} }
...@@ -1284,9 +1695,10 @@ public class ChromosomeDataService { ...@@ -1284,9 +1695,10 @@ public class ChromosomeDataService {
if (item != null) { if (item != null) {
// 特殊处理:当实体是Machine时,过滤不需要的字段 // 特殊处理:当实体是Machine时,过滤不需要的字段
if ("machine".equalsIgnoreCase(config.getEntityName())) { if ("machine".equalsIgnoreCase(config.getEntityName())) {
return filterSingleMachineData(item); item = filterSingleMachineData(item);
} }
return item; // 格式化时间字段
return formatFileEntityTimeFields(item);
} else { } else {
return null; // 找不到数据时返回null而不是抛出异常 return null; // 找不到数据时返回null而不是抛出异常
} }
...@@ -1294,9 +1706,10 @@ public class ChromosomeDataService { ...@@ -1294,9 +1706,10 @@ public class ChromosomeDataService {
// 如果不是列表,直接返回结果 // 如果不是列表,直接返回结果
// 特殊处理:当实体是Machine时,过滤不需要的字段 // 特殊处理:当实体是Machine时,过滤不需要的字段
if ("machine".equalsIgnoreCase(config.getEntityName())) { if ("machine".equalsIgnoreCase(config.getEntityName())) {
return filterSingleMachineData(result); result = filterSingleMachineData(result);
} }
return result; // 格式化时间字段
return formatFileEntityTimeFields(result);
} }
} }
...@@ -1383,7 +1796,7 @@ public class ChromosomeDataService { ...@@ -1383,7 +1796,7 @@ public class ChromosomeDataService {
break; break;
} }
} }
row.put(fn.toLowerCase(), val); row.put(fn, val);
} }
} else { } else {
try { try {
...@@ -1391,7 +1804,7 @@ public class ChromosomeDataService { ...@@ -1391,7 +1804,7 @@ public class ChromosomeDataService {
Field field = getFieldIgnoreCase(item.getClass(), fn); Field field = getFieldIgnoreCase(item.getClass(), fn);
if (field != null) { if (field != null) {
field.setAccessible(true); field.setAccessible(true);
row.put(fn.toLowerCase(), field.get(item)); row.put(fn, field.get(item));
} }
} }
} catch (Exception e) { } catch (Exception e) {
...@@ -1455,11 +1868,24 @@ public class ChromosomeDataService { ...@@ -1455,11 +1868,24 @@ public class ChromosomeDataService {
Long count = countByKey.get(keyStr); Long count = countByKey.get(keyStr);
Map<String, Object> row = new LinkedHashMap<>(); Map<String, Object> row = new LinkedHashMap<>();
for (int i = 0; i < fieldNames.size(); i++) { for (int i = 0; i < fieldNames.size(); i++) {
row.put(fieldNames.get(i).toLowerCase(), key.get(i)); row.put(fieldNames.get(i), key.get(i));
} }
row.put("count", count != null ? count : 0L); row.put("count", count != null ? count : 0L);
result.add(row); result.add(row);
} }
// 根据count倒序排序
result.sort((o1, o2) -> {
if (o1 instanceof Map && o2 instanceof Map) {
Map<?, ?> m1 = (Map<?, ?>) o1;
Map<?, ?> m2 = (Map<?, ?>) o2;
Object count1 = m1.get("count");
Object count2 = m2.get("count");
if (count1 instanceof Number && count2 instanceof Number) {
return ((Number) count2).longValue() - ((Number) count1).longValue() > 0 ? 1 : -1;
}
}
return 0;
});
return result; return result;
} }
...@@ -1672,6 +2098,36 @@ public class ChromosomeDataService { ...@@ -1672,6 +2098,36 @@ public class ChromosomeDataService {
return conditionType == ConditionEnum.IsEmpty; return conditionType == ConditionEnum.IsEmpty;
} }
// 特殊处理时间类型字段
if (actualValue instanceof LocalDateTime) {
LocalDateTime actualDateTime = (LocalDateTime) actualValue;
// 尝试解析输入的时间字符串
LocalDateTime inputDateTime = parseDateTimeString(fieldValue);
if (inputDateTime != null) {
// 时间类型比较
int compareResult = actualDateTime.compareTo(inputDateTime);
switch (conditionType) {
case Equal:
return compareResult == 0;
case NoEqual:
return compareResult != 0;
case GreaterThan:
return compareResult > 0;
case GreaterThanOrEqual:
return compareResult >= 0;
case LessThan:
return compareResult < 0;
case LessThanOrEqual:
return compareResult <= 0;
default:
return compareResult == 0;
}
}
}
// 非时间类型字段的处理
String actualValueStr = actualValue.toString(); String actualValueStr = actualValue.toString();
switch (conditionType) { switch (conditionType) {
...@@ -1708,6 +2164,47 @@ public class ChromosomeDataService { ...@@ -1708,6 +2164,47 @@ public class ChromosomeDataService {
} }
} }
/**
* 解析时间字符串为LocalDateTime(兼容Java 8)
* @param dateTimeStr 时间字符串
* @return 解析后的LocalDateTime,解析失败返回null
*/
private LocalDateTime parseDateTimeString(String dateTimeStr) {
try {
if (dateTimeStr == null || dateTimeStr.trim().isEmpty()) {
return null;
}
String trimmed = dateTimeStr.trim();
// 处理带Z后缀的格式
if (trimmed.endsWith("Z")) {
// Java 8兼容处理:移除Z后缀,解析为LocalDateTime
trimmed = trimmed.substring(0, trimmed.length() - 1);
// 处理可能的毫秒部分
if (trimmed.contains(".")) {
// 保留三位小数
int dotIndex = trimmed.indexOf(".");
if (dotIndex + 4 < trimmed.length()) {
trimmed = trimmed.substring(0, dotIndex + 4);
}
}
return LocalDateTime.parse(trimmed, DateTimeFormatter.ISO_DATE_TIME);
}
// 处理包含空格的格式
if (trimmed.contains(" ")) {
return LocalDateTime.parse(trimmed, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
}
// 处理ISO格式
return LocalDateTime.parse(trimmed, DateTimeFormatter.ISO_DATE_TIME);
} catch (Exception e) {
// 解析失败,返回null
return null;
}
}
/** /**
* 安全获取字段值(支持多种字段名格式) * 安全获取字段值(支持多种字段名格式)
*/ */
...@@ -1744,30 +2241,8 @@ public class ChromosomeDataService { ...@@ -1744,30 +2241,8 @@ public class ChromosomeDataService {
} }
} }
/**
* 转换为驼峰命名
*/
private String toCamelCase(String str) {
if (str == null || str.isEmpty()) return str;
if (str.length() == 1) return str.toLowerCase();
return str.substring(0, 1).toLowerCase() + str.substring(1);
}
/**
* 转换为下划线命名
*/
private String toUnderScoreCase(String str) {
if (str == null || str.isEmpty()) return str;
StringBuilder result = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (Character.isUpperCase(c) && i > 0) {
result.append('_');
}
result.append(Character.toLowerCase(c));
}
return result.toString();
}
/** /**
* 更新Chromosome中的数据(支持文件实体和数据库实体) * 更新Chromosome中的数据(支持文件实体和数据库实体)
*/ */
...@@ -1899,7 +2374,6 @@ public class ChromosomeDataService { ...@@ -1899,7 +2374,6 @@ public class ChromosomeDataService {
} }
} }
// 其他字段通过updateObjectFields更新
} }
...@@ -1963,170 +2437,8 @@ public class ChromosomeDataService { ...@@ -1963,170 +2437,8 @@ public class ChromosomeDataService {
} }
} }
/**
* 批量操作Chromosome中的数据(仅支持文件实体)
*/
public int batchChromosomeData(String sceneId, String entityName, List<Map<String, Object>> dataList) {
EntityConfig config = getEntityConfig(entityName);
if (config.getDataSource() == DataSourceType.DATABASE) {
throw new RuntimeException("数据库实体暂不支持批量操作");
}
// 从文件中加载Chromosome对象
Chromosome chromosome = sceneService.loadChromosomeFromFile(sceneId);
if (chromosome == null) {
throw new RuntimeException("未找到场景ID为 " + sceneId + " 的Chromosome数据");
}
try {
// 根据实体名称映射到Chromosome中的字段名
String fieldName = config.getFieldName();
// 使用反射获取字段值
Field field = Chromosome.class.getDeclaredField(fieldName);
field.setAccessible(true);
// 获取原始数据
Object originalData = field.get(chromosome);
// 如果原始数据是List类型,则批量更新列表中的项
if (originalData instanceof List) {
List<Object> originalList = (List<Object>) originalData;
int successCount = 0;
for (Map<String, Object> data : dataList) {
try {
if (data.containsKey("id")) {
String id = data.get("id").toString();
// 查找并更新匹配的项
for (Object item : originalList) {
try {
Field idField = item.getClass().getDeclaredField("id");
idField.setAccessible(true);
Object itemId = idField.get(item);
if (itemId != null && itemId.toString().equals(id)) {
// 找到匹配项,更新它
updateObjectFields(item, data);
successCount++;
break;
}
} catch (Exception e) {
// 如果没有id字段或访问失败,尝试使用Id字段
try {
Field idField = item.getClass().getDeclaredField("Id");
idField.setAccessible(true);
Object itemId = idField.get(item);
if (itemId != null && itemId.toString().equals(id)) {
// 找到匹配项,更新它
updateObjectFields(item, data);
successCount++;
break;
}
} catch (Exception ex) {
// 忽略异常,继续下一个
}
}
}
}
} catch (Exception e) {
// 忽略单个数据的异常,继续处理下一个
}
}
// 保存更新后的Chromosome到文件
boolean saved = sceneService.saveChromosomeToFile(chromosome, sceneId);
return saved ? successCount : 0;
} else {
throw new RuntimeException("字段 " + entityName + " 不是列表类型,无法进行批量操作");
}
} catch (NoSuchFieldException e) {
throw new RuntimeException("Chromosome类中未找到字段: " + entityName, e);
} catch (IllegalAccessException e) {
throw new RuntimeException("访问Chromosome字段失败: " + e.getMessage(), e);
}
}
/**
* 删除Chromosome中的数据(仅支持文件实体)
*/
public int deleteChromosomeData(String sceneId, String entityName, List<Object> ids) {
EntityConfig config = getEntityConfig(entityName);
if (config.getDataSource() == DataSourceType.DATABASE) {
throw new RuntimeException("数据库实体暂不支持删除操作");
}
// 从文件中加载Chromosome对象
Chromosome chromosome = sceneService.loadChromosomeFromFile(sceneId);
if (chromosome == null) {
throw new RuntimeException("未找到场景ID为 " + sceneId + " 的Chromosome数据");
}
try {
// 根据实体名称映射到Chromosome中的字段名
String fieldName = config.getFieldName();
// 使用反射获取字段值
Field field = Chromosome.class.getDeclaredField(fieldName);
field.setAccessible(true);
// 获取原始数据
Object originalData = field.get(chromosome);
// 如果原始数据是List类型,则从列表中删除指定项
if (originalData instanceof List) {
List<Object> originalList = (List<Object>) originalData;
int deleteCount = 0;
// 创建ID字符串列表便于比较
List<String> idStrings = ids.stream()
.map(Object::toString)
.collect(Collectors.toList());
// 使用迭代器安全地删除元素
Iterator<Object> iterator = originalList.iterator();
while (iterator.hasNext()) {
Object item = iterator.next();
try {
Field idField = item.getClass().getDeclaredField("id");
idField.setAccessible(true);
Object itemId = idField.get(item);
if (itemId != null && idStrings.contains(itemId.toString())) {
// 找到匹配项,删除它
iterator.remove();
deleteCount++;
}
} catch (Exception e) {
// 如果没有id字段或访问失败,尝试使用Id字段
try {
Field idField = item.getClass().getDeclaredField("Id");
idField.setAccessible(true);
Object itemId = idField.get(item);
if (itemId != null && idStrings.contains(itemId.toString())) {
// 找到匹配项,删除它
iterator.remove();
deleteCount++;
}
} catch (Exception ex) {
// 忽略异常,继续下一个
}
}
}
// 保存更新后的Chromosome到文件
boolean saved = sceneService.saveChromosomeToFile(chromosome, sceneId);
return saved ? deleteCount : 0;
} else {
throw new RuntimeException("字段 " + entityName + " 不是列表类型,无法进行删除操作");
}
} catch (NoSuchFieldException e) {
throw new RuntimeException("Chromosome类中未找到字段: " + entityName, e);
} catch (IllegalAccessException e) {
throw new RuntimeException("访问Chromosome字段失败: " + e.getMessage(), e);
}
}
/** /**
* 更新对象的字段值 * 更新对象的字段值
...@@ -2237,66 +2549,6 @@ public class ChromosomeDataService { ...@@ -2237,66 +2549,6 @@ public class ChromosomeDataService {
} }
} }
/**
* 将Entry列表转换为ProdProcessExec列表
*/
private Object convertEntryToProdProcessExec(Object data) {
if (data instanceof List) {
List<?> entryList = (List<?>) data;
List<ProdProcessExec> result = new ArrayList<>();
for (Object obj : entryList) {
if (obj instanceof Entry) {
Entry entry = (Entry) obj;
ProdProcessExec prodProcessExec = convertEntryToProdProcessExecSingle(entry);
result.add(prodProcessExec);
}
}
return result;
} else if (data instanceof Entry) {
Entry entry = (Entry) data;
return convertEntryToProdProcessExecSingle(entry);
}
return data; // 如果不是Entry类型,直接返回原数据
}
/**
* 将单个Entry转换为ProdProcessExec
*/
private ProdProcessExec convertEntryToProdProcessExecSingle(Entry entry) {
ProdProcessExec prodProcessExec = new ProdProcessExec();
// 基本字段映射
prodProcessExec.setExecId(entry.ExecId);
prodProcessExec.setSceneId(entry.SceneId);
prodProcessExec.setOrderId(entry.OrderId);
prodProcessExec.setRoutingDetailId(entry.getRoutingDetailId());
prodProcessExec.setTaskSeq(entry.getTaskSeq());
prodProcessExec.setRoutingDetailName(entry.getRoutingDetailName());
prodProcessExec.setMachineId(entry.getSelectMachineID());
prodProcessExec.setEquipTypeName(entry.getEquipTypeName());
prodProcessExec.setEquipTypeCode(entry.getEquipTypeCode());
// prodProcessExec.setEquipTypeID(entry.getEquipTypeID());
prodProcessExec.setRuntime(entry.getRuntime());
prodProcessExec.setSingleOut(entry.getSingleOut());
prodProcessExec.setPlanQty(entry.getQuantity());
prodProcessExec.setLogicalOrder((long) entry.getSequence());
// 设置ID字段
prodProcessExec.setId(String.valueOf(entry.getId()));
// 其他字段根据需要进行映射
prodProcessExec.setCanInterrupt(entry.getIsInterrupt());
prodProcessExec.setRoutingId(entry.getRoutingId());
if (entry.getDepartmentId() != null) {
prodProcessExec.setDepartmentId(entry.getDepartmentId());
}
return prodProcessExec;
}
/** /**
* 从Entry列表中提取MachineOption列表 * 从Entry列表中提取MachineOption列表
...@@ -2435,18 +2687,6 @@ public class ChromosomeDataService { ...@@ -2435,18 +2687,6 @@ public class ChromosomeDataService {
} }
} }
// 处理preTime字段
// if (data.containsKey("preTime")) {
// Object preTimeObj = data.get("preTime");
// if (preTimeObj instanceof Integer) {
// machineOption.setPreTime((Integer) preTimeObj);
// } else if (preTimeObj instanceof Long) {
// machineOption.setPreTime(((Long) preTimeObj).intValue());
// } else if (preTimeObj instanceof String) {
// machineOption.setPreTime(Integer.parseInt((String) preTimeObj));
// }
// }
// 处理processingTime字段 - 修改为:时间(runtime) ÷ 数量(singleOut) // 处理processingTime字段 - 修改为:时间(runtime) ÷ 数量(singleOut)
if (data.containsKey("processingTime") || data.containsKey("singleOut") || data.containsKey("runtime")) { if (data.containsKey("processingTime") || data.containsKey("singleOut") || data.containsKey("runtime")) {
// 1. 获取singleOut值 // 1. 获取singleOut值
...@@ -2496,58 +2736,6 @@ public class ChromosomeDataService { ...@@ -2496,58 +2736,6 @@ public class ChromosomeDataService {
machineOption.setProcessingTime(processingTime); machineOption.setProcessingTime(processingTime);
} }
//
// // 处理setupTime字段
// if (data.containsKey("setupTime")) {
// Object setupTimeObj = data.get("setupTime");
// if (setupTimeObj instanceof Integer) {
// machineOption.setSetupTime((Integer) setupTimeObj);
// } else if (setupTimeObj instanceof Long) {
// machineOption.setSetupTime(((Long) setupTimeObj).intValue());
// } else if (setupTimeObj instanceof String) {
// machineOption.setSetupTime(Integer.parseInt((String) setupTimeObj));
// }
// }
//
// // 处理teardownTime字段
// if (data.containsKey("teardownTime")) {
// Object teardownTimeObj = data.get("teardownTime");
// if (teardownTimeObj instanceof Integer) {
// machineOption.setTeardownTime((Integer) teardownTimeObj);
// } else if (teardownTimeObj instanceof Long) {
// machineOption.setTeardownTime(((Long) teardownTimeObj).intValue());
// } else if (teardownTimeObj instanceof String) {
// machineOption.setTeardownTime(Integer.parseInt((String) teardownTimeObj));
// }
// }
//
// // 处理contantTime字段
// if (data.containsKey("contantTime")) {
// Object contantTimeObj = data.get("contantTime");
// if (contantTimeObj instanceof Integer) {
// machineOption.setContantTime((Integer) contantTimeObj);
// } else if (contantTimeObj instanceof Long) {
// machineOption.setContantTime(((Long) contantTimeObj).intValue());
// } else if (contantTimeObj instanceof String) {
// machineOption.setContantTime(Integer.parseInt((String) contantTimeObj));
// }
// }
// // 处理equipCode字段
// if (data.containsKey("equipCode")) {
// machineOption.setEquipCode(String.valueOf(data.get("equipCode")));
// }
//
// // 处理resourceCode字段
// if (data.containsKey("resourceCode")) {
// machineOption.setResourceCode(String.valueOf(data.get("resourceCode")));
// }
// 忽略id等未知字段
} }
} }
\ No newline at end of file
...@@ -163,7 +163,8 @@ public class DatabaseQueryService { ...@@ -163,7 +163,8 @@ public class DatabaseQueryService {
} }
String groupColsStr = String.join(", ", groupCols); String groupColsStr = String.join(", ", groupCols);
String orderBy = buildOrderBy(paged); // 修复分组查询时的ORDER BY语法错误
String orderBy = buildOrderByForGroupBy(paged, groupCols);
int page = paged.getPageIndex() != null ? paged.getPageIndex() : 1; int page = paged.getPageIndex() != null ? paged.getPageIndex() : 1;
int size = paged.getPageSize() != null ? paged.getPageSize() : 10; int size = paged.getPageSize() != null ? paged.getPageSize() : 10;
...@@ -191,6 +192,10 @@ public class DatabaseQueryService { ...@@ -191,6 +192,10 @@ public class DatabaseQueryService {
Map<String, Object> out = new LinkedHashMap<>(); Map<String, Object> out = new LinkedHashMap<>();
for (Map.Entry<String, Object> e : row.entrySet()) { for (Map.Entry<String, Object> e : row.entrySet()) {
String key = e.getKey(); String key = e.getKey();
// 排除rn字段(Oracle分页查询的行号)
if ("RN".equalsIgnoreCase(key)) {
continue;
}
if ("CNT".equalsIgnoreCase(key) || "cnt".equals(key)) { if ("CNT".equalsIgnoreCase(key) || "cnt".equals(key)) {
out.put("count", e.getValue()); out.put("count", e.getValue());
} else { } else {
...@@ -219,7 +224,7 @@ public class DatabaseQueryService { ...@@ -219,7 +224,7 @@ public class DatabaseQueryService {
} }
/** /**
* 查询数据库数据列表(分页)。当 paged.groupName 有值时按分组字段 GROUP BY,返回分组列 + count。 * 查询数据库数据列表(支持分页)。当 paged.groupName 有值时按分组字段 GROUP BY,返回分组列 + count。
*/ */
public List<Object> queryDatabaseDataList(EntityConfig config, Paged paged) { public List<Object> queryDatabaseDataList(EntityConfig config, Paged paged) {
String tableName = config.getTableName(); String tableName = config.getTableName();
...@@ -268,28 +273,58 @@ public class DatabaseQueryService { ...@@ -268,28 +273,58 @@ public class DatabaseQueryService {
} }
boolean useFieldsOnly = !"*".equals(selectClause); boolean useFieldsOnly = !"*".equals(selectClause);
try {
List<Object> result;
// 检查是否需要分页
if (paged.getPageIndex() != null && paged.getPageSize() != null && paged.getPageSize() > 0) {
// 使用分页查询
String dataSql = buildOraclePaginationSql(tableName, whereClause.toString(), orderBy,
paged.getPageIndex(), paged.getPageSize(), selectClause);
if (useFieldsOnly) {
List<Map<String, Object>> rows = params.getValues().isEmpty()
? jdbcTemplate.queryForList(dataSql)
: namedParameterJdbcTemplate.queryForList(dataSql, params);
result = new ArrayList<>(normalizeMapKeysToLower(rows));
} else if (config.getEntityClass() != null) {
if (params.getValues().isEmpty()) {
result = new ArrayList<>(jdbcTemplate.query(dataSql, new BeanPropertyRowMapper<>(config.getEntityClass())));
} else {
result = new ArrayList<>(namedParameterJdbcTemplate.query(dataSql, params, new BeanPropertyRowMapper<>(config.getEntityClass())));
}
} else {
if (params.getValues().isEmpty()) {
result = new ArrayList<>(jdbcTemplate.queryForList(dataSql));
} else {
result = new ArrayList<>(namedParameterJdbcTemplate.queryForList(dataSql, params));
}
}
} else {
// 不分页,查询全部
String sql = "SELECT " + selectClause + " FROM " + tableName + whereClause.toString() + orderBy; String sql = "SELECT " + selectClause + " FROM " + tableName + whereClause.toString() + orderBy;
try {
if (useFieldsOnly) { if (useFieldsOnly) {
List<Map<String, Object>> rows = params.getValues().isEmpty() List<Map<String, Object>> rows = params.getValues().isEmpty()
? jdbcTemplate.queryForList(sql) ? jdbcTemplate.queryForList(sql)
: namedParameterJdbcTemplate.queryForList(sql, params); : namedParameterJdbcTemplate.queryForList(sql, params);
return new ArrayList<>(normalizeMapKeysToLower(rows)); result = new ArrayList<>(normalizeMapKeysToLower(rows));
} } else if (config.getEntityClass() != null) {
if (config.getEntityClass() != null) {
if (params.getValues().isEmpty()) { if (params.getValues().isEmpty()) {
return new ArrayList<>(jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(config.getEntityClass()))); result = new ArrayList<>(jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(config.getEntityClass())));
} else { } else {
return new ArrayList<>(namedParameterJdbcTemplate.query(sql, params, new BeanPropertyRowMapper<>(config.getEntityClass()))); result = new ArrayList<>(namedParameterJdbcTemplate.query(sql, params, new BeanPropertyRowMapper<>(config.getEntityClass())));
} }
} else { } else {
if (params.getValues().isEmpty()) { if (params.getValues().isEmpty()) {
return new ArrayList<>(jdbcTemplate.queryForList(sql)); result = new ArrayList<>(jdbcTemplate.queryForList(sql));
} else { } else {
return new ArrayList<>(namedParameterJdbcTemplate.queryForList(sql, params)); result = new ArrayList<>(namedParameterJdbcTemplate.queryForList(sql, params));
} }
} }
}
return result;
} catch (Exception e) { } catch (Exception e) {
throw new RuntimeException("查询数据列表失败: " + e.getMessage(), e); throw new RuntimeException("查询数据列表失败: " + e.getMessage(), e);
} }
...@@ -313,7 +348,12 @@ public class DatabaseQueryService { ...@@ -313,7 +348,12 @@ public class DatabaseQueryService {
for (Map<String, Object> row : rows) { for (Map<String, Object> row : rows) {
Map<String, Object> m = new LinkedHashMap<>(); Map<String, Object> m = new LinkedHashMap<>();
for (Map.Entry<String, Object> e : row.entrySet()) { for (Map.Entry<String, Object> e : row.entrySet()) {
m.put(e.getKey() != null ? e.getKey().toLowerCase() : "", e.getValue()); String key = e.getKey();
// 排除rn字段(Oracle分页查询的行号)
if ("RN".equalsIgnoreCase(key)) {
continue;
}
m.put(key != null ? key.toLowerCase() : "", e.getValue());
} }
out.add(m); out.add(m);
} }
...@@ -345,7 +385,8 @@ public class DatabaseQueryService { ...@@ -345,7 +385,8 @@ public class DatabaseQueryService {
return new ArrayList<>(); return new ArrayList<>();
} }
String groupColsStr = String.join(", ", groupCols); String groupColsStr = String.join(", ", groupCols);
String orderBy = buildOrderBy(paged); // 修复分组查询时的ORDER BY语法错误
String orderBy = buildOrderByForGroupBy(paged, groupCols);
String sql = "SELECT " + groupColsStr + ", COUNT(*) AS cnt FROM " + tableName + whereClause + " GROUP BY " + groupColsStr + orderBy; String sql = "SELECT " + groupColsStr + ", COUNT(*) AS cnt FROM " + tableName + whereClause + " GROUP BY " + groupColsStr + orderBy;
try { try {
...@@ -440,7 +481,7 @@ public class DatabaseQueryService { ...@@ -440,7 +481,7 @@ public class DatabaseQueryService {
// 处理字段名大小写问题:将驼峰命名转换为下划线大写(数据库字段格式) // 处理字段名大小写问题:将驼峰命名转换为下划线大写(数据库字段格式)
fieldName = camelCaseToUnderScoreUpperCase(fieldName).toUpperCase(); fieldName = camelCaseToUnderScoreUpperCase(fieldName).toUpperCase();
orderBy.append(fieldName).append(" ").append(direction); orderBy.append(fieldName).append(" " ).append(direction);
} }
// 如果有有效的排序规则,返回构建的ORDER BY子句 // 如果有有效的排序规则,返回构建的ORDER BY子句
...@@ -461,6 +502,76 @@ public class DatabaseQueryService { ...@@ -461,6 +502,76 @@ public class DatabaseQueryService {
return " ORDER BY ID DESC"; return " ORDER BY ID DESC";
} }
/**
* 构建分组查询的排序子句
*/
private String buildOrderByForGroupBy(Paged paged, List<String> groupCols) {
// 优先使用sortByList进行多字段排序
if (paged.getSortByList() != null && !paged.getSortByList().isEmpty()) {
StringBuilder orderBy = new StringBuilder(" ORDER BY ");
boolean first = true;
for (String sortBy : paged.getSortByList()) {
if (!first) {
orderBy.append(", ");
}
first = false;
// 解析排序规则,格式如"field asc"或"field desc"
String[] parts = sortBy.trim().split("\\s+");
if (parts.length < 2) {
continue; // 跳过格式不正确的排序规则
}
String fieldName = parts[0];
String direction = "DESC".equalsIgnoreCase(parts[1]) ? "DESC" : "ASC";
// 处理字段名大小写问题:将驼峰命名转换为下划线大写(数据库字段格式)
fieldName = camelCaseToUnderScoreUpperCase(fieldName).toUpperCase();
// 检查字段是否在GROUP BY中或是否为聚合函数
if (isValidGroupBySortField(fieldName, groupCols)) {
orderBy.append(fieldName).append(" " ).append(direction);
}
}
// 如果有有效的排序规则,返回构建的ORDER BY子句
if (!first) {
return orderBy.toString();
}
}
// 使用原有sortBy和desc字段进行单字段排序
if (paged.getSortBy() != null && !paged.getSortBy().isEmpty()) {
String direction = Boolean.TRUE.equals(paged.getDesc()) ? "DESC" : "ASC";
// 处理字段名大小写问题:将驼峰命名转换为下划线大写(数据库字段格式)
String fieldName = camelCaseToUnderScoreUpperCase(paged.getSortBy()).toUpperCase();
// 检查字段是否在GROUP BY中或是否为聚合函数
if (isValidGroupBySortField(fieldName, groupCols)) {
return " ORDER BY " + fieldName + " " + direction;
}
}
// 默认按COUNT(*)降序(分组查询的默认排序)
return " ORDER BY COUNT(*) DESC";
}
/**
* 检查字段是否可以在分组查询中用于排序
* 可以用于排序的字段:
* 1. 在GROUP BY中包含的列
* 2. 聚合函数(如COUNT(*), SUM(*)等)
*/
private boolean isValidGroupBySortField(String fieldName, List<String> groupCols) {
// 检查是否为聚合函数
if (fieldName.contains("(")) {
return true;
}
// 检查是否在GROUP BY中
return groupCols != null && groupCols.contains(fieldName);
}
/** /**
* 构建条件SQL * 构建条件SQL
*/ */
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment