修改工单订单设备

parent a1aaee69
...@@ -380,11 +380,6 @@ public class SwaggerMapParamConfig { ...@@ -380,11 +380,6 @@ public class SwaggerMapParamConfig {
examples.put("订单更新示例", createExample( examples.put("订单更新示例", createExample(
"更新订单数据", "更新订单数据",
"{\n" + "{\n" +
" \"sceneId\": \"SCENE001\",\n" +
" \"data\": {\n" +
" \"id\": \"123\",\n" +
" \"name\": \"updated name\"\n" +
" }\n" +
"}" "}"
)); ));
break; break;
......
package com.aps.controller.common; package com.aps.controller.common;
import com.aps.common.util.R; import com.aps.common.util.R;
import com.aps.entity.Algorithm.Chromosome;
import com.aps.entity.basic.Entry;
import com.aps.entity.basic.MachineOption;
import com.aps.entity.common.Paged; import com.aps.entity.common.Paged;
import com.aps.service.common.ChromosomeDataService; import com.aps.service.common.ChromosomeDataService;
import com.aps.service.plan.PlanResultService;
import com.aps.service.plan.SceneService;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
...@@ -18,6 +27,10 @@ public class ChromosomeDataController { ...@@ -18,6 +27,10 @@ public class ChromosomeDataController {
@Autowired @Autowired
private ChromosomeDataService chromosomeDataService; private ChromosomeDataService chromosomeDataService;
@Autowired
private SceneService sceneService;
@Autowired
private PlanResultService planResultService;
/** /**
* 通用接口,根据实体名称查询Chromosome中的数据,支持分页和条件过滤 * 通用接口,根据实体名称查询Chromosome中的数据,支持分页和条件过滤
...@@ -122,7 +135,222 @@ public class ChromosomeDataController { ...@@ -122,7 +135,222 @@ public class ChromosomeDataController {
} }
/**
* 通用接口,根据实体名称更新Chromosome中的数据
* 支持文件实体(通过sceneId)和数据库实体的更新
* 示例:
* - 文件实体: PUT /queryChromosome/order/update?sceneId=xxx
* Body: { "id": 123, "fieldName": "newValue", ... }
* - 数据库实体: PUT /queryChromosome/user/update
* Body: { "id": 123, "fieldName": "newValue", ... }
*
* @param sceneId 场景ID (文件实体必需,数据库实体可选)
* @param entityName 实体名称
* @param data 要更新的数据 (必须包含id字段)
* @return 更新结果
*/
@PostMapping("/{entityName}/update")
@Operation(summary = "更新实体数据", description = "根据实体名称和ID更新数据,支持文件实体和数据库实体")
public R<String> updateChromosomeData(
@Parameter(description = "场景ID (文件实体必需,数据库实体可选)", required = false)
@RequestParam(required = false) String sceneId,
@Parameter(description = "taskID (文件实体必需,数据库实体可选)", required = false)
@RequestParam(required = false) String taskId,
@Parameter(description = "实体名称", required = true)
@PathVariable String entityName,
@Parameter(description = "要更新的数据 (必须包含id字段)", required = true)
@RequestBody Map<String, Object> data) {
// 文件实体必须要有sceneId
if (isFileEntity(entityName) && (sceneId == null || sceneId.isEmpty())) {
return R.failed("文件实体更新时sceneId不能为空");
}
if (entityName.equalsIgnoreCase("machineOption")){
return updateMachineOption(sceneId, taskId, data);
}
try {
boolean success = chromosomeDataService.updateChromosomeData(sceneId, entityName, data);
if (success) {
return R.ok("更新成功");
} else {
return R.failed("更新失败");
}
} catch (Exception e) {
return R.failed("更新失败: " + e.getMessage());
}
}
private R<String> updateMachineOption(String sceneId, String taskId, Map<String, Object> data) {
// 验证taskId不能为空
if (taskId == null || taskId.isEmpty()) {
return R.failed("更新machineOption时taskId不能为空");
}
try {
// 1. 加载Chromosome对象
Chromosome chromosome = sceneService.loadChromosomeFromFile(sceneId);
if (chromosome == null) {
return R.failed("未找到场景ID为 " + sceneId + " 的Chromosome数据");
}
// 2. 根据taskId找到对应的entry
Entry targetEntry = null;
for (Entry entry : chromosome.getAllOperations()) {
if (String.valueOf(entry.getId()).equals(taskId)) {
targetEntry = entry;
break;
}
}
if (targetEntry == null) {
return R.failed("未找到taskId为 " + taskId + " 的entry数据");
}
// 3. 获取machineOption的id
String machineOptionId = String.valueOf(data.get("machineId"));
// 4. 在entry的machineOptions列表中找到对应的machineOption
MachineOption targetMachineOption = null;
for (MachineOption machineOption : targetEntry.getMachineOptions()) {
if (String.valueOf(machineOption.getMachineId()).equals(machineOptionId)) {
targetMachineOption = machineOption;
break;
}
}
if (targetMachineOption == null) {
return R.failed("未找到id为 " + machineOptionId + " 的machineOption数据");
}
// 5. 更新machineOption的字段
ObjectMapper objectMapper = new ObjectMapper();
MachineOption updatedMachineOption = objectMapper.convertValue(data, MachineOption.class);
// 6. 替换原来的machineOption
int index = targetEntry.getMachineOptions().indexOf(targetMachineOption);
targetEntry.getMachineOptions().set(index, updatedMachineOption);
planResultService.editMachine(chromosome, sceneId,targetEntry);
// 7. 保存更新后的Chromosome
boolean saved = sceneService.saveChromosomeToFile(chromosome, sceneId);
if (saved) {
return R.ok("更新成功");
} else {
return R.failed("更新失败");
}
} catch (Exception e) {
return R.failed("更新machineOption失败: " + e.getMessage());
}
}
/**
* 同一entry下的多个machineOption更新
*/
private R<String> updateMultipleMachineOptionsInEntry(String sceneId, String taskId, Map<String, Object> data) {
try {
// 1. 加载Chromosome对象
Chromosome chromosome = sceneService.loadChromosomeFromFile(sceneId);
if (chromosome == null) {
return R.failed("未找到场景ID为 " + sceneId + " 的Chromosome数据");
}
// 2. 根据taskId找到对应的entry
Entry targetEntry = null;
for (Entry entry : chromosome.getAllOperations()) {
if (String.valueOf(entry.getId()).equals(taskId)) {
targetEntry = entry;
break;
}
}
if (targetEntry == null) {
return R.failed("未找到taskId为 " + taskId + " 的entry数据");
}
// 3. 获取machineOptions列表
Object machineOptionsObj = data.get("machineOptions");
if (!(machineOptionsObj instanceof List)) {
return R.failed("machineOptions必须是数组格式");
}
List<?> machineOptionsList = (List<?>) machineOptionsObj;
if (machineOptionsList.isEmpty()) {
return R.failed("machineOptions数组不能为空");
}
// 4. 更新当前entry下的所有machineOption
ObjectMapper objectMapper = new ObjectMapper();
boolean allSuccess = true;
List<String> errorMessages = new ArrayList<>();
for (Object optionObj : machineOptionsList) {
if (!(optionObj instanceof Map)) {
allSuccess = false;
errorMessages.add("machineOptions中的元素必须是对象格式");
continue;
}
Map<String, Object> optionMap = (Map<String, Object>) optionObj;
// 获取machineOption的machineId
String machineOptionId = String.valueOf(optionMap.get("machineId"));
if (machineOptionId == null) {
allSuccess = false;
errorMessages.add("machineOption必须包含machineId字段");
continue;
}
// 在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;
errorMessages.add("未找到machineId为 " + machineOptionId + " 的machineOption数据");
continue;
}
// 更新machineOption的字段
MachineOption updatedMachineOption = objectMapper.convertValue(optionMap, MachineOption.class);
// 替换原来的machineOption
int index = targetEntry.getMachineOptions().indexOf(targetMachineOption);
targetEntry.getMachineOptions().set(index, updatedMachineOption);
}
if (!allSuccess) {
return R.failed("部分更新失败: " + String.join("; ", errorMessages));
}
// 5. 调用editMachine方法处理entry更新
planResultService.editMachine(chromosome, sceneId, targetEntry);
// 6. 保存更新后的Chromosome
boolean saved = sceneService.saveChromosomeToFile(chromosome, sceneId);
if (saved) {
return R.ok("批量更新成功");
} else {
return R.failed("批量更新失败: 保存Chromosome数据失败");
}
} catch (Exception e) {
return R.failed("批量更新machineOption失败: " + e.getMessage());
}
}
/** /**
* 判断是否为文件实体 * 判断是否为文件实体
*/ */
......
...@@ -252,7 +252,7 @@ public class ResourceGanttController { ...@@ -252,7 +252,7 @@ public class ResourceGanttController {
@PostMapping("/operationEdit") @PostMapping("/editOperation")
@Operation(summary = "修改工单", description = "修改工单") @Operation(summary = "修改工单", description = "修改工单")
public R<Chromosome> operationEdit(@RequestBody Map<String, Object> params) { public R<Chromosome> operationEdit(@RequestBody Map<String, Object> params) {
log.info("operationEdit 请求参数: {}", params); log.info("operationEdit 请求参数: {}", params);
...@@ -267,6 +267,33 @@ public class ResourceGanttController { ...@@ -267,6 +267,33 @@ public class ResourceGanttController {
return R.ok(result); return R.ok(result);
} }
@PostMapping("/editMachineOption")
@Operation(summary = "修改机器选项", description = "修改工序的机器选项",
requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(
description = "修改机器选项参数",
content = @io.swagger.v3.oas.annotations.media.Content(
mediaType = "application/json",
examples = @io.swagger.v3.oas.annotations.media.ExampleObject(
name = "修改机器选项示例",
value = "{\n \"sceneId\": \"B571EF6682DB463AB2977B1055A74112\",\n \"entry\": {\n \"id\": 1,\n \"groupId\": 1,\n \"sequence\": 1,\n \"orderId\": \"ORDER001\",\n \"orderCode\": \"订单编号\",\n \"productId\": 1,\n \"productName\": \"产品名称\",\n \"productCode\": \"产品编号\",\n \"routingId\": 1,\n \"routingDetailId\": 1,\n \"execId\": \"EXEC001\",\n \"orderId\": \"ORDER001\",\n \"orderCode\": \"订单编号\",\n \"sceneId\": \"B571EF6682DB463AB2977B1055A74112\",\n \"mainId\": \"MAIN001\",\n \"priority\": 1,\n \"quantity\": 100,\n \"sequence\": 1,\n \"machineOptions\": [],\n \"selectMachineID\": 1,\n \"prevEntryIds\": [],\n \"nextEntryIds\": [],\n \"state\": 1,\n \"isInterrupt\": 1,\n \"materialRequirements\": []\n },\n \"newMachineId\": 123\n}"
)
)
)
)
public R<Chromosome> editMachineOption(@RequestBody Map<String, Object> params) {
log.info("editMachineOption 请求参数: {}", params);
String sceneId = ParamValidator.getString(params, "sceneId", "场景ID");
ParamValidator.validateSceneExists(sceneService, sceneId);
// 使用BeanUtil转换LinkedHashMap为Entry对象
Entry entry = BeanUtil.toBean(params.get("entry"), Entry.class);
Long newMachineId = ParamValidator.getLong(params, "newMachineId", "新机器ID");
Chromosome result = planResultService.editMachineOption(sceneId, entry, newMachineId);
return R.ok(result);
}
@PostMapping("/changebasetime") @PostMapping("/changebasetime")
@Operation(summary = "修改基础时间", description = "修改基础时间") @Operation(summary = "修改基础时间", description = "修改基础时间")
public R<String> changeBaseTime(@RequestBody Map<String, Object> params) { public R<String> changeBaseTime(@RequestBody Map<String, Object> params) {
......
...@@ -78,12 +78,12 @@ public class Entry { ...@@ -78,12 +78,12 @@ public class Entry {
/** /**
* 可选设备列表 * 可选设备列表
*/ */
public List<MachineOption> MachineOptions ; private List<MachineOption> MachineOptions ;
/** /**
* 选择的设备 * 选择的设备
*/ */
public Long SelectMachineID ; private Long SelectMachineID ;
/** /**
* 前工单ID * 前工单ID
......
...@@ -276,15 +276,15 @@ public class GeneticAlgorithm { ...@@ -276,15 +276,15 @@ public class GeneticAlgorithm {
private List<Chromosome> chromosomeDistinct(List<Chromosome> population) private List<Chromosome> chromosomeDistinct(List<Chromosome> population)
{ {
population = population.stream() // population = population.stream()
.collect(Collectors.toMap( // .collect(Collectors.toMap(
Chromosome::getGeneStr, // key:去重的字段(GeneStr) // Chromosome::getGeneStr, // key:去重的字段(GeneStr)
u -> u, // value:Chromosome对象 // u -> u, // value:Chromosome对象
(u1, u2) -> u1 // 重复时保留第一个元素 // (u1, u2) -> u1 // 重复时保留第一个元素
)) // ))
.values() // 获取去重后的 // .values() // 获取去重后的
.stream() // .stream()
.collect(Collectors.toList()); // .collect(Collectors.toList());
return population; return population;
} }
......
...@@ -145,6 +145,162 @@ Integer newMachineId1=newMachineId.intValue(); ...@@ -145,6 +145,162 @@ Integer newMachineId1=newMachineId.intValue();
} }
public void editMachineOption(Chromosome chromosome,Entry operation,
Long newMachineId, GlobalParam globalParam) {
List<Entry> allOperations = chromosome.getAllOperations();
Map<Integer, Integer> opTimeMap = chromosome.getResult().stream()
.collect(Collectors.toMap(
GAScheduleResult::getOperationId,
r -> r.getStartTime()
));
Integer newMachineId1=newMachineId.intValue();
int opId = operation.getId();
// 获取目标结果和工序
GAScheduleResult targetResult = chromosome.getResult().stream()
.filter(r -> r.getOperationId() == opId)
.findFirst()
.orElseThrow(() -> new NoSuchElementException("Operation not found: " + opId));
Entry targetOp = allOperations.stream()
.filter(o -> o.getId() == opId)
.findFirst()
.orElseThrow(() -> new NoSuchElementException("Operation not found: " + opId));
if(newMachineId1!=0) {
int machineOptionIndex = targetOp.getMachineOptions().stream()
.map(MachineOption::getMachineId)
.collect(Collectors.toList())
.indexOf(newMachineId) + 1;
if (machineOptionIndex == 0) {
throw new NoSuchElementException("Machine not found: " + newMachineId);
}
// 更新设备选择序列
int globalOpIndex = chromosome.getGlobalOpList().stream()
.filter(g -> g.getOp().getId() == opId)
.findFirst()
.map(GlobalOperationInfo::getGlobalOpId)
.orElseThrow(() -> new NoSuchElementException("Global operation not found: " + opId));
chromosome.getMachineSelection().set(globalOpIndex, machineOptionIndex);
targetResult.setForcedMachineId(newMachineId);
}
List<Integer> operationSequencing = allOperations.stream()
.sorted((op1, op2) -> {
int time1 = opTimeMap.getOrDefault(op1.getId(), Integer.MAX_VALUE);
int time2 = opTimeMap.getOrDefault(op2.getId(), Integer.MAX_VALUE);
if (time1 != time2) {
return Integer.compare(time1, time2);
} else {
return Integer.compare(op1.getSequence(), op2.getSequence());
}
})
.map(Entry::getGroupId)
.collect(Collectors.toList());
chromosome.setOperationSequencing(operationSequencing);
// 重新解码
redecode(chromosome, chromosome.getBaseTime(), globalParam);
}
public void editMachine(Chromosome chromosome,Entry operation,
Long newMachineId, GlobalParam globalParam) {
List<Entry> allOperations = chromosome.getAllOperations();
Map<Integer, Integer> opTimeMap = chromosome.getResult().stream()
.collect(Collectors.toMap(
GAScheduleResult::getOperationId,
r -> r.getStartTime()
));
Integer newMachineId1=newMachineId.intValue();
int opId = operation.getId();
// 获取目标结果和工序
GAScheduleResult targetResult = chromosome.getResult().stream()
.filter(r -> r.getOperationId() == opId)
.findFirst()
.orElseThrow(() -> new NoSuchElementException("Operation not found: " + opId));
Entry targetOp = allOperations.stream()
.filter(o -> o.getId() == opId)
.findFirst()
.orElseThrow(() -> new NoSuchElementException("Operation not found: " + opId));
if(newMachineId1!=0) {
int machineOptionIndex = targetOp.getMachineOptions().stream()
.map(MachineOption::getMachineId)
.collect(Collectors.toList())
.indexOf(newMachineId) + 1;
if (machineOptionIndex == 0) {
throw new NoSuchElementException("Machine not found: " + newMachineId);
}
// 更新设备选择序列
int globalOpIndex = chromosome.getGlobalOpList().stream()
.filter(g -> g.getOp().getId() == opId)
.findFirst()
.map(GlobalOperationInfo::getGlobalOpId)
.orElseThrow(() -> new NoSuchElementException("Global operation not found: " + opId));
chromosome.getMachineSelection().set(globalOpIndex, machineOptionIndex);
targetResult.setForcedMachineId(newMachineId);
}
List<Integer> operationSequencing = allOperations.stream()
.sorted((op1, op2) -> {
int time1 = opTimeMap.getOrDefault(op1.getId(), Integer.MAX_VALUE);
int time2 = opTimeMap.getOrDefault(op2.getId(), Integer.MAX_VALUE);
if (time1 != time2) {
return Integer.compare(time1, time2);
} else {
return Integer.compare(op1.getSequence(), op2.getSequence());
}
})
.map(Entry::getGroupId)
.collect(Collectors.toList());
chromosome.setOperationSequencing(operationSequencing);
// 重新解码
redecode(chromosome, chromosome.getBaseTime(), globalParam);
}
/** /**
* 增加设备维修保养 * 增加设备维修保养
* @param chromosome 染色体对象 * @param chromosome 染色体对象
......
package com.aps.service.common; package com.aps.service.common;
import cn.hutool.core.bean.BeanUtil;
import com.aps.entity.Algorithm.Chromosome; import com.aps.entity.Algorithm.Chromosome;
import com.aps.entity.ProdProcessExec; import com.aps.entity.ProdProcessExec;
import com.aps.entity.basic.Entry; import com.aps.entity.basic.Entry;
import com.aps.entity.basic.MachineOption; import com.aps.entity.basic.MachineOption;
import com.aps.entity.basic.Order; import com.aps.entity.basic.Order;
import com.aps.entity.common.*; import com.aps.entity.common.*;
import com.aps.service.plan.PlanResultService;
import com.aps.service.plan.SceneService; import com.aps.service.plan.SceneService;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils; import org.springframework.util.CollectionUtils;
...@@ -24,12 +32,21 @@ public class ChromosomeDataService { ...@@ -24,12 +32,21 @@ public class ChromosomeDataService {
@Autowired @Autowired
private DatabaseQueryService databaseQueryService; private DatabaseQueryService databaseQueryService;
@Autowired
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
@Autowired @Autowired
private Map<String, EntityConfig> entityConfigMap; private Map<String, EntityConfig> entityConfigMap;
@Autowired
private PlanResultService planResultService;
/** /**
* 根据场景ID和实体名称查询Chromosome中的数据 * 根据场景ID和实体名称查询Chromosome中的数据
*/ */
ObjectMapper objectMapper = new ObjectMapper()
.registerModule(new JavaTimeModule())
.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
public Object queryChromosomeData(String sceneId, String entityName) { public Object queryChromosomeData(String sceneId, String entityName) {
EntityConfig config = getEntityConfig(entityName); EntityConfig config = getEntityConfig(entityName);
...@@ -793,14 +810,27 @@ public class ChromosomeDataService { ...@@ -793,14 +810,27 @@ public class ChromosomeDataService {
return result.toString(); return result.toString();
} }
/** /**
* 更新Chromosome中的数据(仅支持文件实体) * 更新Chromosome中的数据(支持文件实体和数据库实体)
*/ */
public boolean updateChromosomeData(String sceneId, String entityName, Map<String, Object> data) { public boolean updateChromosomeData(String sceneId, String entityName, Map<String, Object> data) {
EntityConfig config = getEntityConfig(entityName); EntityConfig config = getEntityConfig(entityName);
if (config.getDataSource() == DataSourceType.DATABASE) { if (config.getDataSource() == DataSourceType.FILE) {
throw new RuntimeException("数据库实体暂不支持更新操作"); if ("entry".equalsIgnoreCase(entityName)) {
convertNestedObjects(data);
}
return updateFileEntity(sceneId, entityName, data);
} else {
// 数据库实体更新
return updateDatabaseEntity(entityName, data);
} }
}
/**
* 更新文件实体数据
*/
private boolean updateFileEntity(String sceneId, String entityName, Map<String, Object> data) {
EntityConfig config = getEntityConfig(entityName);
// 从文件中加载Chromosome对象 // 从文件中加载Chromosome对象
Chromosome chromosome = sceneService.loadChromosomeFromFile(sceneId); Chromosome chromosome = sceneService.loadChromosomeFromFile(sceneId);
...@@ -853,8 +883,36 @@ public class ChromosomeDataService { ...@@ -853,8 +883,36 @@ public class ChromosomeDataService {
} }
} }
} else { } else {
// 直接更新整个字段 // 如果不是列表类型或没有id字段,抛出异常提示
field.set(chromosome, data); throw new RuntimeException("更新文件实体时必须提供id字段以标识要更新的具体对象");
}
if (entityName.equals("order")) {
chromosome = planResultService.editOrder(chromosome, sceneId, BeanUtil.toBean(data, Order.class));
System.out.println("test1123");
}else if (entityName.equals("entry")) {
System.out.println("5757");
Entry entry = objectMapper.convertValue(data, Entry.class);
// 2. 手动转换machineOptions字段
if (data.containsKey("machineOptions")) {
List<?> machineOptionsList = (List<?>) data.get("machineOptions");
List<MachineOption> convertedOptions = new ArrayList<>();
for (Object item : machineOptionsList) {
// 手动转换每个MachineOption对象
MachineOption option = objectMapper.convertValue(item, MachineOption.class);
convertedOptions.add(option);
}
// 设置转换后的machineOptions
entry.setMachineOptions(convertedOptions);
}
chromosome = planResultService.editOperation(chromosome, sceneId, entry );
}else if (entityName.equals("machineOption")) {
// chromosome =planResultService.editMachine(chromosome, sceneId, BeanUtil.toBean(data, MachineOption.class));
} }
// 保存更新后的Chromosome到文件 // 保存更新后的Chromosome到文件
...@@ -865,6 +923,57 @@ public class ChromosomeDataService { ...@@ -865,6 +923,57 @@ public class ChromosomeDataService {
throw new RuntimeException("访问Chromosome字段失败: " + e.getMessage(), e); throw new RuntimeException("访问Chromosome字段失败: " + e.getMessage(), e);
} }
} }
/**
* 更新数据库实体数据
*/
private boolean updateDatabaseEntity(String entityName, Map<String, Object> data) {
EntityConfig config = getEntityConfig(entityName);
String tableName = config.getTableName();
if (data == null || !data.containsKey("id")) {
throw new RuntimeException("更新数据库实体时必须提供id字段");
}
String id = data.get("id").toString();
// 构建更新SQL
StringBuilder sql = new StringBuilder();
sql.append("UPDATE ").append(tableName).append(" SET ");
List<String> setParts = new ArrayList<>();
MapSqlParameterSource params = new MapSqlParameterSource();
// 遍历要更新的字段,排除id字段
for (Map.Entry<String, Object> entry : data.entrySet()) {
String fieldName = entry.getKey();
Object fieldValue = entry.getValue();
if (!"id".equalsIgnoreCase(fieldName)) {
// 将驼峰命名转换为下划线大写格式
String dbFieldName = camelCaseToUnderScoreUpperCase(fieldName).toUpperCase();
setParts.add(dbFieldName + " = :" + fieldName);
params.addValue(fieldName, fieldValue);
}
}
if (setParts.isEmpty()) {
throw new RuntimeException("没有有效的字段用于更新");
}
sql.append(String.join(", ", setParts));
// 添加WHERE条件
sql.append(" WHERE ID = :idParam");
params.addValue("idParam", id);
try {
int rowsAffected = namedParameterJdbcTemplate.update(sql.toString(), params);
return rowsAffected > 0;
} catch (Exception e) {
throw new RuntimeException("数据库更新失败: " + e.getMessage(), e);
}
}
/** /**
* 批量操作Chromosome中的数据(仅支持文件实体) * 批量操作Chromosome中的数据(仅支持文件实体)
...@@ -1057,6 +1166,16 @@ public class ChromosomeDataService { ...@@ -1057,6 +1166,16 @@ public class ChromosomeDataService {
field.set(obj, Double.parseDouble(fieldValue.toString())); field.set(obj, Double.parseDouble(fieldValue.toString()));
} else if (fieldType == Boolean.class || fieldType == boolean.class) { } else if (fieldType == Boolean.class || fieldType == boolean.class) {
field.set(obj, Boolean.parseBoolean(fieldValue.toString())); field.set(obj, Boolean.parseBoolean(fieldValue.toString()));
} else if (fieldType == List.class) {
// 特殊处理List类型字段,特别是MachineOption列表
List<?> valueList = (List<?>) fieldValue;
if (!valueList.isEmpty() && valueList.get(0) instanceof Map) {
// 如果列表中的元素是Map(如JSON反序列化结果),需要特殊处理
// 对于MachineOption这类复杂对象,我们暂时直接赋值
field.set(obj, fieldValue);
} else {
field.set(obj, fieldValue);
}
} else { } else {
field.set(obj, fieldValue); field.set(obj, fieldValue);
} }
...@@ -1155,4 +1274,30 @@ public class ChromosomeDataService { ...@@ -1155,4 +1274,30 @@ public class ChromosomeDataService {
return new ArrayList<>(); // 如果不是Entry类型,返回空列表 return new ArrayList<>(); // 如果不是Entry类型,返回空列表
} }
private void convertNestedObjects(Map<String, Object> data) {
// 转换machineOptions(支持大小写)
convertListField(data, "MachineOptions", MachineOption.class);
// 可以添加其他需要转换的字段
}
private <T> void convertListField(Map<String, Object> data, String fieldName, Class<T> targetClass) {
if (data.containsKey(fieldName)) {
Object fieldValue = data.get(fieldName);
if (fieldValue instanceof List) {
List<?> list = (List<?>) fieldValue;
List<T> convertedList = new ArrayList<>();
for (Object item : list) {
if (item instanceof LinkedHashMap) {
T convertedItem = BeanUtil.toBean((Map<?, ?>) item, targetClass);
convertedList.add(convertedItem);
}
}
data.put(fieldName, convertedList);
}
}
}
} }
\ No newline at end of file
...@@ -323,7 +323,43 @@ order.setDueDate(LocalDateTime.of(2025, 12, 1,0,0,0)); ...@@ -323,7 +323,43 @@ order.setDueDate(LocalDateTime.of(2025, 12, 1,0,0,0));
} }
public Chromosome editMachineOption(String SceneId, Entry operation,
Long newMachineId) {
Chromosome chromosome = _sceneService.loadChromosomeFromFile(SceneId);
if (chromosome == null || chromosome.getAllOperations() == null) {
return chromosome;
}
List<Entry> operations = chromosome.getAllOperations();
int position = IntStream.range(0, operations.size())
.filter(i -> operations.get(i).getId() == operation.getId())
.findFirst()
.orElse(-1);
if (position != -1) {
Entry oldEntry = operations.set(position, operation);
List<GlobalOperationInfo> globalOpList = chromosome.getGlobalOpList();
if (globalOpList != null) {
globalOpList.stream()
.filter(opInfo -> opInfo.getOp() != null && opInfo.getOp().getId() == oldEntry.getId())
.forEach(opInfo -> opInfo.setOp(operation));
}
}
GlobalParam globalParam=new GlobalParam();
// Chromosome chromosome= _sceneService.loadChromosomeFromFile(SceneId);
// WriteScheduleSummary(chromosome);
ScheduleOperationService ScheduleOperation=new ScheduleOperationService();
WriteScheduleSummary(chromosome);
ScheduleOperation.editMachineOption(chromosome,operation,newMachineId,globalParam);
WriteScheduleSummary(chromosome);
_sceneService.saveChromosomeToFile(chromosome, SceneId);
return chromosome;
}
public Chromosome EditOperation(String SceneId, Entry operation) { public Chromosome EditOperation(String SceneId, Entry operation) {
...@@ -344,12 +380,12 @@ order.setDueDate(LocalDateTime.of(2025, 12, 1,0,0,0)); ...@@ -344,12 +380,12 @@ order.setDueDate(LocalDateTime.of(2025, 12, 1,0,0,0));
List<GlobalOperationInfo> globalOpList = chromosome.getGlobalOpList(); List<GlobalOperationInfo> globalOpList = chromosome.getGlobalOpList();
if (globalOpList != null) { if (globalOpList != null) {
globalOpList.stream() globalOpList.stream()
.filter(opInfo -> opInfo.getOp() == oldEntry) .filter(opInfo -> opInfo.getOp() != null && opInfo.getOp().getId() == oldEntry.getId())
.forEach(opInfo -> opInfo.setOp(operation)); .forEach(opInfo -> opInfo.setOp(operation));
} }
} }
// _sceneService.saveChromosomeToFile(chromosome, SceneId);
return redecodeChromosome(chromosome); return redecodeChromosome(chromosome, SceneId);
} }
public Chromosome EditOrder(String SceneId, Order order) { public Chromosome EditOrder(String SceneId, Order order) {
...@@ -373,10 +409,74 @@ order.setDueDate(LocalDateTime.of(2025, 12, 1,0,0,0)); ...@@ -373,10 +409,74 @@ order.setDueDate(LocalDateTime.of(2025, 12, 1,0,0,0));
orderSortService.assignPriority(orders, rule); orderSortService.assignPriority(orders, rule);
updateOrderRelatedEntries(chromosome, order); updateOrderRelatedEntries(chromosome, order);
// _sceneService.saveChromosomeToFile(chromosome, SceneId);
return redecodeChromosome(chromosome); return redecodeChromosome(chromosome,SceneId);
} }
public Chromosome editOrder(Chromosome chromosome,String SceneId, Order order) {
List<Order> orders = chromosome.getOrders();
orderSortService.initializeFieldExtractors();
OrderSortRule rule = createMultiConditionRule(orders);
orderSortService.assignPriority(orders, rule);
updateOrderRelatedEntries(chromosome, order);
// _sceneService.saveChromosomeToFile(chromosome, SceneId);
return redecodeChromosome(chromosome,SceneId);
}
public Chromosome editOperation(Chromosome chromosome,String SceneId, Entry operation) {
System.out.println("4545");
List<GlobalOperationInfo> globalOpList = chromosome.getGlobalOpList();
if (globalOpList != null) {
globalOpList.stream()
.filter(opInfo -> opInfo.getOp() != null && opInfo.getOp().getId() == operation.getId())
.forEach(opInfo -> opInfo.setOp(operation));
}
GlobalParam globalParam=new GlobalParam();
ScheduleOperationService ScheduleOperation=new ScheduleOperationService();
System.out.println(operation.getSelectMachineID());
ScheduleOperation.editMachineOption(chromosome,operation,operation.getSelectMachineID(),globalParam);
return redecodeChromosome(chromosome,SceneId);
}
public Chromosome editMachine(Chromosome chromosome,String SceneId, Entry operation) {
List<GlobalOperationInfo> globalOpList = chromosome.getGlobalOpList();
if (globalOpList != null) {
globalOpList.stream()
.filter(opInfo -> opInfo.getOp() != null && opInfo.getOp().getId() == operation.getId())
.forEach(opInfo -> opInfo.setOp(operation));
}
// _sceneService.saveChromosomeToFile(chromosome, SceneId);
return redecodeChromosome(chromosome, SceneId);
}
/** /**
* 更新订单相关的所有Entry的数量和优先级 * 更新订单相关的所有Entry的数量和优先级
*/ */
...@@ -408,10 +508,11 @@ order.setDueDate(LocalDateTime.of(2025, 12, 1,0,0,0)); ...@@ -408,10 +508,11 @@ order.setDueDate(LocalDateTime.of(2025, 12, 1,0,0,0));
/** /**
* 重新解码染色体 * 重新解码染色体
*/ */
private Chromosome redecodeChromosome(Chromosome chromosome) { private Chromosome redecodeChromosome(Chromosome chromosome,String SceneId) {
GlobalParam globalParam = new GlobalParam(); GlobalParam globalParam = new GlobalParam();
ScheduleOperationService scheduleOperation = new ScheduleOperationService(); ScheduleOperationService scheduleOperation = new ScheduleOperationService();
scheduleOperation.redecode(chromosome, chromosome.getBaseTime(), globalParam); scheduleOperation.redecode(chromosome, chromosome.getBaseTime(), globalParam);
// _sceneService.saveChromosomeToFile(chromosome, SceneId);
return chromosome; return chromosome;
} }
......
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