公共分页和list查询修改和info修改

parent 8105cd67
...@@ -187,7 +187,7 @@ public class ChromosomeDataController { ...@@ -187,7 +187,7 @@ public class ChromosomeDataController {
* - 文件实体: GET /queryChromosome/order/info?sceneId=xxx * - 文件实体: GET /queryChromosome/order/info?sceneId=xxx
* - 数据库实体: GET /queryChromosome/user/info * - 数据库实体: GET /queryChromosome/user/info
* *
* @param sceneId 场景ID (文件实体可选,数据库实体不需要)
* @param entityName 实体名称 (如: order, entry, machine, user, department等) * @param entityName 实体名称 (如: order, entry, machine, user, department等)
* @return 字段信息列表 * @return 字段信息列表
*/ */
...@@ -196,7 +196,7 @@ public class ChromosomeDataController { ...@@ -196,7 +196,7 @@ 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 R.ok(fieldInfos);
} }
......
...@@ -637,7 +637,7 @@ public class ResourceGanttController { ...@@ -637,7 +637,7 @@ public class ResourceGanttController {
@GetMapping("/productGantt") @GetMapping("/productGantt")
@Operation(summary = "获取资源甘特图数据", description = "获取资源甘特图数据") @Operation(summary = "获取工单甘特图数据", description = "获取工单甘特图数据")
public List<ProductGanttVO> productGantt(@RequestParam String sceneId) { public List<ProductGanttVO> productGantt(@RequestParam String sceneId) {
// 从PlanResultService获取ScheduleChromosome列表 // 从PlanResultService获取ScheduleChromosome列表
Chromosome schedule = sceneService.loadChromosomeFromFile(sceneId); Chromosome schedule = sceneService.loadChromosomeFromFile(sceneId);
......
...@@ -43,7 +43,7 @@ private BigDecimal checkTime; ...@@ -43,7 +43,7 @@ private BigDecimal checkTime;
private String taskType; private String taskType;
private Long taskFlag; private Long taskFlag;
private Long insertFlag; private Long insertFlag;
private Long shopid; private Integer shopid;
private Long lockFlag; private Long lockFlag;
private Short subWorkHourStatus; private Short subWorkHourStatus;
private Short isOutsourcing; private Short isOutsourcing;
......
package com.aps.entity.Gantt;
import lombok.Data;
import java.util.List;
import java.util.Map;
/**
* 供给关系响应数据类
*/
@Data
public class SupplyRelationResponse {
private int code;
private String msg;
private List<Object> data;
private String timestamp;
/**
* 构建成功响应
* @param data 响应数据
* @return 响应对象
*/
public static SupplyRelationResponse success(List<Object> data) {
SupplyRelationResponse response = new SupplyRelationResponse();
response.setCode(200);
response.setMsg("success");
response.setData(data);
response.setTimestamp(java.time.LocalDateTime.now().toString());
return response;
}
}
\ No newline at end of file
package com.aps.entity; package com.aps.entity;
import lombok.Data; import lombok.Data;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName; import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable; import java.io.Serializable;
......
...@@ -102,4 +102,7 @@ public class ProdProcessExec { ...@@ -102,4 +102,7 @@ public class ProdProcessExec {
private String routingCode; private String routingCode;
/** 部门ID,来自工艺路线 routing_header.department_id,新增场景时在 createProcessExec 中赋值 */
private Integer departmentId;
} }
\ No newline at end of file
...@@ -43,6 +43,8 @@ public class Entry { ...@@ -43,6 +43,8 @@ public class Entry {
private Integer routingId; private Integer routingId;
private String routingCode; private String routingCode;
private String routingName; private String routingName;
/** 部门ID,来自工艺路线 routing_header.department_id,在创建 Entry 时从工艺头带出 */
private Integer departmentId;
private Long routingDetailId; private Long routingDetailId;
private Long taskSeq; private Long taskSeq;
private String routingDetailName; private String routingDetailName;
......
...@@ -20,8 +20,10 @@ public class Paged { ...@@ -20,8 +20,10 @@ public class Paged {
private List<String> sortByList=new ArrayList<>(); // 多字段排序列表,格式如["type asc", "id desc"] private List<String> sortByList=new ArrayList<>(); // 多字段排序列表,格式如["type asc", "id desc"]
private String sortBy=""; //排序字段 private String sortBy=""; //排序字段
private Boolean desc=true; //是否倒序 private Boolean desc=true; //是否倒序
private String fields=""; // 返回的字段 /** 返回的字段,多个用逗号分隔如 "id,name";有值时只返回这些列,有几列返回几列 */
private String fields="";
private String table=""; // 返回的表 private String table=""; // 返回的表
/** 分组字段,多个用逗号分隔如 "id,name"。有值时按这些字段 GROUP BY,返回结果仅含分组列 + count(每组条数) */
private String groupName; private String groupName;
private Boolean and=true; // 条件逻辑关系,true为与关系,false为或关系 private Boolean and=true; // 条件逻辑关系,true为与关系,false为或关系
private List<ConditionEntity> conditions=new ArrayList<>(); //条件集合 private List<ConditionEntity> conditions=new ArrayList<>(); //条件集合
......
...@@ -543,8 +543,9 @@ if(routingIds.size()==0) ...@@ -543,8 +543,9 @@ if(routingIds.size()==0)
ProdLaunchOrder prodOrderMain= convertToLaunchOrder(order,""); ProdLaunchOrder prodOrderMain= convertToLaunchOrder(order,"");
List<RoutingDetailEquip> finalRoutingDetailEquips = routingDetailEquips; List<RoutingDetailEquip> finalRoutingDetailEquips = routingDetailEquips;
Integer departmentId = headers1.getDepartmentId() != null ? headers1.getDepartmentId() : null;
List<ProdProcessExec> processExecList = RoutingDetails.stream() List<ProdProcessExec> processExecList = RoutingDetails.stream()
.map(detail -> lanuchService.createProcessExec(prodOrderMain, detail, sceneId, finalRoutingDetailEquips)) .map(detail -> lanuchService.createProcessExec(prodOrderMain, detail, sceneId, finalRoutingDetailEquips, departmentId))
.collect(Collectors.toList()); .collect(Collectors.toList());
List<Equipinfo> equipinfoList = equipinfoService.lambdaQuery().eq(Equipinfo::getIsdeleted, 0).list(); List<Equipinfo> equipinfoList = equipinfoService.lambdaQuery().eq(Equipinfo::getIsdeleted, 0).list();
List<ProdEquipment> ProdEquipmentList= lanuchService.batchInsertEquipMent(routingDetailEquips, sceneId,processExecList,false,equipinfoList); List<ProdEquipment> ProdEquipmentList= lanuchService.batchInsertEquipMent(routingDetailEquips, sceneId,processExecList,false,equipinfoList);
......
...@@ -217,6 +217,9 @@ public class RoutingDataService { ...@@ -217,6 +217,9 @@ public class RoutingDataService {
entry.setRoutingDetailId(op.getRoutingDetailId()); entry.setRoutingDetailId(op.getRoutingDetailId());
entry.setTaskSeq(op.getTaskSeq()); entry.setTaskSeq(op.getTaskSeq());
entry.setRoutingDetailName(op.getRoutingDetailName()); entry.setRoutingDetailName(op.getRoutingDetailName());
if (op.getDepartmentId() != null) {
entry.setDepartmentId(op.getDepartmentId());
}
entry.setIsInterrupt(op.getCanInterrupt()); entry.setIsInterrupt(op.getCanInterrupt());
Order order = ProdLaunchOrders.stream() Order order = ProdLaunchOrders.stream()
.filter(t -> t.getOrderId().equals(op.getOrderId())) .filter(t -> t.getOrderId().equals(op.getOrderId()))
......
...@@ -46,7 +46,8 @@ public interface LanuchService { ...@@ -46,7 +46,8 @@ public interface LanuchService {
ProdProcessExec createProcessExec(ProdLaunchOrder prodOrderMain, ProdProcessExec createProcessExec(ProdLaunchOrder prodOrderMain,
RoutingDetail detail, RoutingDetail detail,
String sceneId,List<RoutingDetailEquip> routingDetailEquip); String sceneId, List<RoutingDetailEquip> routingDetailEquip,
Integer departmentId);
List<ProdEquipment> batchInsertEquipMent( List<ProdEquipment> batchInsertEquipMent(
List<RoutingDetailEquip> routingDetailEquips, List<RoutingDetailEquip> routingDetailEquips,
......
...@@ -30,6 +30,7 @@ import java.lang.reflect.Field; ...@@ -30,6 +30,7 @@ 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.util.*; import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.math.RoundingMode; import java.math.RoundingMode;
import java.time.LocalDateTime; import java.time.LocalDateTime;
...@@ -65,6 +66,12 @@ public class ChromosomeDataService { ...@@ -65,6 +66,12 @@ public class ChromosomeDataService {
@Autowired @Autowired
private PlanResultService planResultService; private PlanResultService planResultService;
/**
* 字段注释缓存,避免重复读取源文件
*/
private final ConcurrentHashMap<Class<?>, Map<String, String>> fieldCommentCache = new ConcurrentHashMap<>();
/** /**
* 根据场景ID和实体名称查询Chromosome中的数据 * 根据场景ID和实体名称查询Chromosome中的数据
*/ */
...@@ -326,7 +333,7 @@ public class ChromosomeDataService { ...@@ -326,7 +333,7 @@ public class ChromosomeDataService {
} }
// 获取字段描述映射 // 获取字段描述映射
Map<String, String> fieldDescriptions = getFieldDescriptions(entityName); Map<String, String> fieldDescriptions = new HashMap<>();
// 遍历字段,生成FieldInfo // 遍历字段,生成FieldInfo
for (Field field : fields) { for (Field field : fields) {
...@@ -441,7 +448,6 @@ public class ChromosomeDataService { ...@@ -441,7 +448,6 @@ public class ChromosomeDataService {
return fieldInfos; return fieldInfos;
} }
/** /**
* 获取实体对应的Java类 * 获取实体对应的Java类
* @param entityName 实体名称 * @param entityName 实体名称
...@@ -464,6 +470,7 @@ public class ChromosomeDataService { ...@@ -464,6 +470,7 @@ public class ChromosomeDataService {
return entityClassMap.get(entityName.toLowerCase()); return entityClassMap.get(entityName.toLowerCase());
} }
/** /**
* 将数据库字段类型转换为Java类型 * 将数据库字段类型转换为Java类型
* @param dbType 数据库字段类型 * @param dbType 数据库字段类型
...@@ -490,6 +497,7 @@ public class ChromosomeDataService { ...@@ -490,6 +497,7 @@ public class ChromosomeDataService {
return typeMap.getOrDefault(dbType.toUpperCase(), dbType); return typeMap.getOrDefault(dbType.toUpperCase(), dbType);
} }
/** /**
* 获取指定实体的字段描述映射 * 获取指定实体的字段描述映射
* @param entityName 实体名称 * @param entityName 实体名称
...@@ -814,7 +822,8 @@ public class ChromosomeDataService { ...@@ -814,7 +822,8 @@ public class ChromosomeDataService {
} }
} }
return (List<Object>) (List<?>) resultMachineOptions; List<Object> listResult = (List<Object>) (List<?>) resultMachineOptions;
return applyGroupAndFieldsToList(listResult, paged);
} else { } else {
return new ArrayList<>(); return new ArrayList<>();
} }
...@@ -840,20 +849,38 @@ public class ChromosomeDataService { ...@@ -840,20 +849,38 @@ public class ChromosomeDataService {
// 应用排序 // 应用排序
List<Object> sortedData = sortData(resultOrders, paged); List<Object> sortedData = sortData(resultOrders, paged);
return sortedData; return applyGroupAndFieldsToList(sortedData, paged);
} else { } else {
return new ArrayList<>(); return new ArrayList<>();
} }
} else { } else {
Object data = queryFileData(sceneId, config); Object data = queryFileData(sceneId, config);
return applyConditionsToList(data, paged, entityName); List<Object> listResult = applyConditionsToList(data, paged, entityName);
return applyGroupAndFieldsToList(listResult, paged);
} }
} else { } else {
// 数据库查询 // 数据库查询(已支持 groupName、fields)
return databaseQueryService.queryDatabaseDataList(config, paged); return databaseQueryService.queryDatabaseDataList(config, paged);
} }
} }
/**
* List 接口统一应用 groupName、fields:先分组(若有)再投影(若有)。
*/
private List<Object> applyGroupAndFieldsToList(List<?> dataList, Paged paged) {
if (dataList == null) {
return new ArrayList<>();
}
List<?> result = new ArrayList<>(dataList);
if (paged.getGroupName() != null && !paged.getGroupName().trim().isEmpty()) {
result = groupListByFields(result, paged.getGroupName());
}
if (paged.getFields() != null && !paged.getFields().trim().isEmpty()) {
result = projectListToFields(result, paged.getFields());
}
return (List<Object>) result;
}
/** /**
* 根据ID查询单条数据 * 根据ID查询单条数据
*/ */
...@@ -1144,6 +1171,12 @@ public class ChromosomeDataService { ...@@ -1144,6 +1171,12 @@ public class ChromosomeDataService {
if (data instanceof List) { if (data instanceof List) {
List<?> dataList = (List<?>) data; List<?> dataList = (List<?>) data;
if (paged.getGroupName() != null && !paged.getGroupName().trim().isEmpty()) {
dataList = groupListByFields(dataList, paged.getGroupName());
}
if (paged.getFields() != null && !paged.getFields().trim().isEmpty()) {
dataList = projectListToFields(dataList, paged.getFields());
}
int total = dataList.size(); int total = dataList.size();
int fromIndex = (page - 1) * size; int fromIndex = (page - 1) * size;
...@@ -1321,6 +1354,115 @@ public class ChromosomeDataService { ...@@ -1321,6 +1354,115 @@ public class ChromosomeDataService {
} }
} }
/**
* 按 fields 只保留指定字段,返回 List<Map>,每个 Map 仅含 fields 中的列(key 小写)。
* fields 格式如 "id,name";若项已是 Map 则按 key 过滤,否则按实体反射取字段值。
*/
private List<Object> projectListToFields(List<?> dataList, String fields) {
if (CollectionUtils.isEmpty(dataList) || fields == null || fields.trim().isEmpty()) {
return new ArrayList<>(dataList);
}
List<String> fieldNames = Arrays.stream(fields.split(","))
.map(String::trim)
.filter(s -> !s.isEmpty())
.collect(Collectors.toList());
if (fieldNames.isEmpty()) {
return new ArrayList<>(dataList);
}
List<Object> result = new ArrayList<>();
for (Object item : dataList) {
Map<String, Object> row = new LinkedHashMap<>();
if (item instanceof Map) {
@SuppressWarnings("unchecked")
Map<String, Object> m = (Map<String, Object>) item;
for (String fn : fieldNames) {
Object val = null;
for (Map.Entry<String, Object> e : m.entrySet()) {
if (e.getKey() != null && e.getKey().equalsIgnoreCase(fn)) {
val = e.getValue();
break;
}
}
row.put(fn.toLowerCase(), val);
}
} else {
try {
for (String fn : fieldNames) {
Field field = getFieldIgnoreCase(item.getClass(), fn);
if (field != null) {
field.setAccessible(true);
row.put(fn.toLowerCase(), field.get(item));
}
}
} catch (Exception e) {
log.warn("投影字段失败 fields={}", fieldNames, e);
}
}
result.add(row);
}
return result;
}
/**
* 按 groupName 对列表做内存分组,返回分组列 + count(每组条数)。
* groupName 格式如 "id,name",返回 List<Map>,每个 Map 含分组字段(小写 key)+ "count"。
*/
private List<Object> groupListByFields(List<?> dataList, String groupName) {
if (CollectionUtils.isEmpty(dataList) || groupName == null || groupName.trim().isEmpty()) {
return new ArrayList<>(dataList);
}
List<String> fieldNames = Arrays.stream(groupName.split(","))
.map(String::trim)
.filter(s -> !s.isEmpty())
.collect(Collectors.toList());
if (fieldNames.isEmpty()) {
return new ArrayList<>(dataList);
}
Map<String, Long> countByKey = new LinkedHashMap<>();
List<List<Object>> keyOrder = new ArrayList<>();
for (Object item : dataList) {
List<Object> key = new ArrayList<>();
try {
for (String fn : fieldNames) {
Field field = getFieldIgnoreCase(item.getClass(), fn);
if (field != null) {
field.setAccessible(true);
key.add(field.get(item));
} else {
key.add(null);
}
}
} catch (Exception e) {
log.warn("分组取字段失败 fieldNames={}", fieldNames, e);
continue;
}
String keyStr = key.stream()
.map(v -> v == null ? "" : v.toString())
.collect(Collectors.joining("\u0000"));
if (!countByKey.containsKey(keyStr)) {
keyOrder.add(key);
}
countByKey.merge(keyStr, 1L, Long::sum);
}
List<Object> result = new ArrayList<>();
for (List<Object> key : keyOrder) {
String keyStr = key.stream()
.map(v -> v == null ? "" : v.toString())
.collect(Collectors.joining("\u0000"));
Long count = countByKey.get(keyStr);
Map<String, Object> row = new LinkedHashMap<>();
for (int i = 0; i < fieldNames.size(); i++) {
row.put(fieldNames.get(i).toLowerCase(), key.get(i));
}
row.put("count", count != null ? count : 0L);
result.add(row);
}
return result;
}
/** /**
* 根据条件过滤数据(文件数据使用)- 修复版本 * 根据条件过滤数据(文件数据使用)- 修复版本
*/ */
...@@ -2149,6 +2291,9 @@ public class ChromosomeDataService { ...@@ -2149,6 +2291,9 @@ public class ChromosomeDataService {
// 其他字段根据需要进行映射 // 其他字段根据需要进行映射
prodProcessExec.setCanInterrupt(entry.getIsInterrupt()); prodProcessExec.setCanInterrupt(entry.getIsInterrupt());
prodProcessExec.setRoutingId(entry.getRoutingId()); prodProcessExec.setRoutingId(entry.getRoutingId());
if (entry.getDepartmentId() != null) {
prodProcessExec.setDepartmentId(entry.getDepartmentId());
}
return prodProcessExec; return prodProcessExec;
} }
......
...@@ -23,10 +23,17 @@ public class DatabaseQueryService { ...@@ -23,10 +23,17 @@ public class DatabaseQueryService {
private NamedParameterJdbcTemplate namedParameterJdbcTemplate; private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
/** /**
* 查询数据库数据(分页+条件)- 修复Oracle分页问题 * 查询数据库数据(分页+条件)- 修复Oracle分页问题。
* 当 paged.groupName 有值时按分组字段 GROUP BY,返回分组列 + count(每组条数)。
*/ */
public Map<String, Object> queryDatabaseDataWithConditions(EntityConfig config, Paged paged) { public Map<String, Object> queryDatabaseDataWithConditions(EntityConfig config, Paged paged) {
String tableName = config.getTableName(); String tableName = config.getTableName();
String groupName = paged.getGroupName();
boolean isGroupBy = groupName != null && !groupName.trim().isEmpty();
if (isGroupBy) {
return queryDatabaseDataWithGroupBy(config, paged, tableName);
}
// 构建基础SQL和参数 // 构建基础SQL和参数
StringBuilder whereClause = new StringBuilder(" WHERE 1=1"); StringBuilder whereClause = new StringBuilder(" WHERE 1=1");
...@@ -61,6 +68,16 @@ public class DatabaseQueryService { ...@@ -61,6 +68,16 @@ public class DatabaseQueryService {
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;
// 返回列:fields 有值时只查指定列,否则 SELECT *
String selectClause = "*";
if (paged.getFields() != null && !paged.getFields().trim().isEmpty()) {
List<String> cols = parseFieldListToDbColumns(paged.getFields());
if (!cols.isEmpty()) {
selectClause = String.join(", ", cols);
}
}
boolean useFieldsOnly = !"*".equals(selectClause);
// 先查询总数 // 先查询总数
String countSql = "SELECT COUNT(*) FROM " + tableName + whereClause.toString(); String countSql = "SELECT COUNT(*) FROM " + tableName + whereClause.toString();
Integer total; Integer total;
...@@ -77,17 +94,21 @@ public class DatabaseQueryService { ...@@ -77,17 +94,21 @@ public class DatabaseQueryService {
// 查询数据(使用Oracle分页语法) // 查询数据(使用Oracle分页语法)
List<?> records = Collections.emptyList(); List<?> records = Collections.emptyList();
if (total != null && total > 0) { if (total != null && total > 0) {
String dataSql = buildOraclePaginationSql(tableName, whereClause.toString(), orderBy, page, size); String dataSql = buildOraclePaginationSql(tableName, whereClause.toString(), orderBy, page, size, selectClause);
try { try {
if (config.getEntityClass() != null) { if (useFieldsOnly) {
// 使用实体类映射 // 指定了 fields 时只返回这些列,用 Map 列表(key 转小写)
List<Map<String, Object>> rows = params.getValues().isEmpty()
? jdbcTemplate.queryForList(dataSql)
: namedParameterJdbcTemplate.queryForList(dataSql, params);
records = normalizeMapKeysToLower(rows);
} else if (config.getEntityClass() != null) {
if (params.getValues().isEmpty()) { if (params.getValues().isEmpty()) {
records = jdbcTemplate.query(dataSql, new BeanPropertyRowMapper<>(config.getEntityClass())); records = jdbcTemplate.query(dataSql, new BeanPropertyRowMapper<>(config.getEntityClass()));
} else { } else {
records = namedParameterJdbcTemplate.query(dataSql, params, new BeanPropertyRowMapper<>(config.getEntityClass())); records = namedParameterJdbcTemplate.query(dataSql, params, new BeanPropertyRowMapper<>(config.getEntityClass()));
} }
} else { } else {
// 返回Map列表
if (params.getValues().isEmpty()) { if (params.getValues().isEmpty()) {
records = jdbcTemplate.queryForList(dataSql); records = jdbcTemplate.queryForList(dataSql);
} else { } else {
...@@ -109,10 +130,105 @@ public class DatabaseQueryService { ...@@ -109,10 +130,105 @@ public class DatabaseQueryService {
} }
/** /**
* 查询数据库数据列表(不分页) * 按 groupName 分组查询:返回分组列 + count(每组条数),支持分页。
*/
private Map<String, Object> queryDatabaseDataWithGroupBy(EntityConfig config, Paged paged, String tableName) {
StringBuilder whereClause = new StringBuilder(" WHERE 1=1");
MapSqlParameterSource params = new MapSqlParameterSource();
int paramIndex = 1;
if (paged.getConditions() != null && !paged.getConditions().isEmpty()) {
boolean isAnd = paged.getAnd() != null && paged.getAnd();
String logicalOperator = isAnd ? " AND " : " OR ";
List<String> conditionSqlList = new ArrayList<>();
for (ConditionEntity condition : paged.getConditions()) {
String conditionSql = buildConditionSql(condition, params, paramIndex);
if (conditionSql != null) {
conditionSqlList.add(conditionSql);
paramIndex++;
}
}
if (!conditionSqlList.isEmpty()) {
whereClause.append(" AND (").append(String.join(logicalOperator, conditionSqlList)).append(")");
}
}
List<String> groupCols = parseFieldListToDbColumns(paged.getGroupName());
if (groupCols.isEmpty()) {
Map<String, Object> empty = new HashMap<>();
empty.put("records", Collections.emptyList());
empty.put("totalCount", 0);
empty.put("pageIndex", paged.getPageIndex() != null ? paged.getPageIndex() : 1);
empty.put("size", paged.getPageSize() != null ? paged.getPageSize() : 10);
return empty;
}
String groupColsStr = String.join(", ", groupCols);
String orderBy = buildOrderBy(paged);
int page = paged.getPageIndex() != null ? paged.getPageIndex() : 1;
int size = paged.getPageSize() != null ? paged.getPageSize() : 10;
String countSql = "SELECT COUNT(*) FROM (SELECT " + groupColsStr + " FROM " + tableName + whereClause + " GROUP BY " + groupColsStr + ")";
Integer total;
try {
if (params.getValues().isEmpty()) {
total = jdbcTemplate.queryForObject(countSql, Integer.class);
} else {
total = namedParameterJdbcTemplate.queryForObject(countSql, params, Integer.class);
}
} catch (Exception e) {
total = 0;
}
List<Map<String, Object>> records = new ArrayList<>();
if (total != null && total > 0) {
String innerSql = "SELECT " + groupColsStr + ", COUNT(*) AS cnt FROM " + tableName + whereClause + " GROUP BY " + groupColsStr + orderBy;
String dataSql = buildOraclePaginationSqlForGroupBy(innerSql, page, size);
try {
List<Map<String, Object>> rows = params.getValues().isEmpty()
? jdbcTemplate.queryForList(dataSql)
: namedParameterJdbcTemplate.queryForList(dataSql, params);
for (Map<String, Object> row : rows) {
Map<String, Object> out = new LinkedHashMap<>();
for (Map.Entry<String, Object> e : row.entrySet()) {
String key = e.getKey();
if ("CNT".equalsIgnoreCase(key) || "cnt".equals(key)) {
out.put("count", e.getValue());
} else {
out.put(key != null ? key.toLowerCase() : key, e.getValue());
}
}
records.add(out);
}
} catch (Exception e) {
throw new RuntimeException("分组查询失败: " + e.getMessage(), e);
}
}
Map<String, Object> result = new HashMap<>();
result.put("records", records);
result.put("totalCount", total != null ? total : 0);
result.put("pageIndex", page);
result.put("size", size);
return result;
}
private String buildOraclePaginationSqlForGroupBy(String innerSql, int page, int size) {
int startRow = (page - 1) * size + 1;
int endRow = page * size;
return "SELECT * FROM (SELECT a.*, ROWNUM rn FROM (" + innerSql + ") a WHERE ROWNUM <= " + endRow + ") WHERE rn >= " + startRow;
}
/**
* 查询数据库数据列表(不分页)。当 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();
String groupName = paged.getGroupName();
boolean isGroupBy = groupName != null && !groupName.trim().isEmpty();
if (isGroupBy) {
return queryDatabaseDataListWithGroupBy(config, paged, tableName);
}
StringBuilder whereClause = new StringBuilder(" WHERE 1=1"); StringBuilder whereClause = new StringBuilder(" WHERE 1=1");
MapSqlParameterSource params = new MapSqlParameterSource(); MapSqlParameterSource params = new MapSqlParameterSource();
...@@ -142,9 +258,25 @@ public class DatabaseQueryService { ...@@ -142,9 +258,25 @@ public class DatabaseQueryService {
// 构建排序 // 构建排序
String orderBy = buildOrderBy(paged); String orderBy = buildOrderBy(paged);
String sql = "SELECT * FROM " + tableName + whereClause.toString() + orderBy; // 返回列:fields 有值时只查指定列
String selectClause = "*";
if (paged.getFields() != null && !paged.getFields().trim().isEmpty()) {
List<String> cols = parseFieldListToDbColumns(paged.getFields());
if (!cols.isEmpty()) {
selectClause = String.join(", ", cols);
}
}
boolean useFieldsOnly = !"*".equals(selectClause);
String sql = "SELECT " + selectClause + " FROM " + tableName + whereClause.toString() + orderBy;
try { try {
if (useFieldsOnly) {
List<Map<String, Object>> rows = params.getValues().isEmpty()
? jdbcTemplate.queryForList(sql)
: namedParameterJdbcTemplate.queryForList(sql, params);
return new ArrayList<>(normalizeMapKeysToLower(rows));
}
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()))); return new ArrayList<>(jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(config.getEntityClass())));
...@@ -163,6 +295,82 @@ public class DatabaseQueryService { ...@@ -163,6 +295,82 @@ public class DatabaseQueryService {
} }
} }
/** 解析 "id,name" 为数据库列名列表(大写),供 SELECT / GROUP BY 使用 */
private List<String> parseFieldListToDbColumns(String fieldList) {
List<String> cols = new ArrayList<>();
if (fieldList == null || fieldList.trim().isEmpty()) return cols;
for (String part : fieldList.split(",")) {
String trimmed = part.trim();
if (!trimmed.isEmpty()) {
cols.add(camelCaseToUnderScoreUpperCase(trimmed).toUpperCase());
}
}
return cols;
}
private List<Map<String, Object>> normalizeMapKeysToLower(List<Map<String, Object>> rows) {
List<Map<String, Object>> out = new ArrayList<>();
for (Map<String, Object> row : rows) {
Map<String, Object> m = new LinkedHashMap<>();
for (Map.Entry<String, Object> e : row.entrySet()) {
m.put(e.getKey() != null ? e.getKey().toLowerCase() : "", e.getValue());
}
out.add(m);
}
return out;
}
private List<Object> queryDatabaseDataListWithGroupBy(EntityConfig config, Paged paged, String tableName) {
StringBuilder whereClause = new StringBuilder(" WHERE 1=1");
MapSqlParameterSource params = new MapSqlParameterSource();
int paramIndex = 1;
if (paged.getConditions() != null && !paged.getConditions().isEmpty()) {
boolean isAnd = paged.getAnd() != null && paged.getAnd();
String logicalOperator = isAnd ? " AND " : " OR ";
List<String> conditionSqlList = new ArrayList<>();
for (ConditionEntity condition : paged.getConditions()) {
String conditionSql = buildConditionSql(condition, params, paramIndex);
if (conditionSql != null) {
conditionSqlList.add(conditionSql);
paramIndex++;
}
}
if (!conditionSqlList.isEmpty()) {
whereClause.append(" AND (").append(String.join(logicalOperator, conditionSqlList)).append(")");
}
}
List<String> groupCols = parseFieldListToDbColumns(paged.getGroupName());
if (groupCols.isEmpty()) {
return new ArrayList<>();
}
String groupColsStr = String.join(", ", groupCols);
String orderBy = buildOrderBy(paged);
String sql = "SELECT " + groupColsStr + ", COUNT(*) AS cnt FROM " + tableName + whereClause + " GROUP BY " + groupColsStr + orderBy;
try {
List<Map<String, Object>> rows = params.getValues().isEmpty()
? jdbcTemplate.queryForList(sql)
: namedParameterJdbcTemplate.queryForList(sql, params);
List<Object> result = new ArrayList<>();
for (Map<String, Object> row : rows) {
Map<String, Object> out = new LinkedHashMap<>();
for (Map.Entry<String, Object> e : row.entrySet()) {
String key = e.getKey();
if ("CNT".equalsIgnoreCase(key) || "cnt".equals(key)) {
out.put("count", e.getValue());
} else {
out.put(key != null ? key.toLowerCase() : key, e.getValue());
}
}
result.add(out);
}
return result;
} catch (Exception e) {
throw new RuntimeException("分组查询列表失败: " + e.getMessage(), e);
}
}
/** /**
* 根据ID查询单条数据 * 根据ID查询单条数据
*/ */
...@@ -189,16 +397,17 @@ public class DatabaseQueryService { ...@@ -189,16 +397,17 @@ public class DatabaseQueryService {
} }
/** /**
* 构建Oracle分页SQL * 构建Oracle分页SQL;selectClause 为 null 或空时使用 *。
*/ */
private String buildOraclePaginationSql(String tableName, String whereClause, String orderBy, int page, int size) { private String buildOraclePaginationSql(String tableName, String whereClause, String orderBy, int page, int size, String selectClause) {
int startRow = (page - 1) * size + 1; int startRow = (page - 1) * size + 1;
int endRow = page * size; int endRow = page * size;
String cols = (selectClause != null && !selectClause.trim().isEmpty()) ? selectClause : "*";
StringBuilder sql = new StringBuilder(); StringBuilder sql = new StringBuilder();
sql.append("SELECT * FROM ("); sql.append("SELECT * FROM (");
sql.append(" SELECT a.*, ROWNUM rn FROM ("); sql.append(" SELECT a.*, ROWNUM rn FROM (");
sql.append(" SELECT * FROM ").append(tableName).append(whereClause).append(orderBy); sql.append(" SELECT ").append(cols).append(" FROM ").append(tableName).append(whereClause).append(orderBy);
sql.append(" ) a WHERE ROWNUM <= ").append(endRow); sql.append(" ) a WHERE ROWNUM <= ").append(endRow);
sql.append(") WHERE rn >= ").append(startRow); sql.append(") WHERE rn >= ").append(startRow);
return sql.toString(); return sql.toString();
......
...@@ -233,6 +233,14 @@ public class LanuchServiceImpl implements LanuchService { ...@@ -233,6 +233,14 @@ public class LanuchServiceImpl implements LanuchService {
throw new RuntimeException("插入mes_order失败"); throw new RuntimeException("插入mes_order失败");
} }
// 构建 orderId -> mes_order.id 映射,供 dispatch 的 PART_TASK_READY_ID 使用
List<String> orderIds = prodLanuchList.stream().map(Order::getOrderId).distinct().collect(Collectors.toList());
List<MesOrder> savedMesOrders = mesOrderService.lambdaQuery()
.in(MesOrder::getMesCode, orderIds)
.list();
Map<String, Long> mesOrderIdByOrderId = savedMesOrders.stream()
.collect(Collectors.toMap(MesOrder::getMesCode, MesOrder::getId, (a, b) -> a));
// List<ProdProcessExec> processExecList = prodProcessExecService.lambdaQuery() // List<ProdProcessExec> processExecList = prodProcessExecService.lambdaQuery()
// .eq(ProdProcessExec::getSceneId, sceneId) // .eq(ProdProcessExec::getSceneId, sceneId)
// .list(); // .list();
...@@ -261,7 +269,13 @@ public class LanuchServiceImpl implements LanuchService { ...@@ -261,7 +269,13 @@ public class LanuchServiceImpl implements LanuchService {
dispatch.setOpe(entry1.getRoutingDetailName()); dispatch.setOpe(entry1.getRoutingDetailName());
dispatch.setRoutingDetailId(entry1.getRoutingDetailId()); dispatch.setRoutingDetailId(entry1.getRoutingDetailId());
dispatch.setStatus(12L); dispatch.setStatus(12L);
// PART_TASK_READY_ID:取对应 mes_order 的主键 id(按 orderId/mesCode 关联)
Long partTaskReadyId = mesOrderIdByOrderId.get(gaResult.getOrderId());
if (partTaskReadyId != null) {
dispatch.setPartTaskReadyId(partTaskReadyId);
}
dispatch.setShopid(entry1.getDepartmentId());
// 添加到列表中 // 添加到列表中
dispatches.add(dispatch); dispatches.add(dispatch);
} }
...@@ -561,8 +575,9 @@ public class LanuchServiceImpl implements LanuchService { ...@@ -561,8 +575,9 @@ public class LanuchServiceImpl implements LanuchService {
List<RoutingDetail> routingDetails = getRoutingDetails(routingHeader.getId()); List<RoutingDetail> routingDetails = getRoutingDetails(routingHeader.getId());
List<RoutingDetailEquip> routingDetailEquip = getRoutingDetailEquip(routingHeader.getId(),routingHeader.getCode()); List<RoutingDetailEquip> routingDetailEquip = getRoutingDetailEquip(routingHeader.getId(),routingHeader.getCode());
// 批量插入新的工序工单记录 // 批量插入新的工序工单记录(部门ID从工艺头带出)
batchInsertProcessExec(prodOrderMain, routingDetails, sceneId,routingDetailEquip); Integer departmentId = routingHeader.getDepartmentId() != null ? routingHeader.getDepartmentId() : null;
batchInsertProcessExec(prodOrderMain, routingDetails, sceneId, routingDetailEquip, departmentId);
return true; return true;
} }
...@@ -644,9 +659,10 @@ public class LanuchServiceImpl implements LanuchService { ...@@ -644,9 +659,10 @@ public class LanuchServiceImpl implements LanuchService {
*/ */
public void batchInsertProcessExec(ProdLaunchOrder prodOrderMain, public void batchInsertProcessExec(ProdLaunchOrder prodOrderMain,
List<RoutingDetail> routingDetails, List<RoutingDetail> routingDetails,
String sceneId, List<RoutingDetailEquip> routingDetailEquip) { String sceneId, List<RoutingDetailEquip> routingDetailEquip,
Integer departmentId) {
List<ProdProcessExec> processExecList = routingDetails.stream() List<ProdProcessExec> processExecList = routingDetails.stream()
.map(detail -> createProcessExec(prodOrderMain, detail, sceneId,routingDetailEquip)) .map(detail -> createProcessExec(prodOrderMain, detail, sceneId, routingDetailEquip, departmentId))
.collect(Collectors.toList()); .collect(Collectors.toList());
List<Equipinfo> list = equipinfoService.lambdaQuery().eq(Equipinfo::getIsdeleted, 0).list(); List<Equipinfo> list = equipinfoService.lambdaQuery().eq(Equipinfo::getIsdeleted, 0).list();
...@@ -673,7 +689,8 @@ public class LanuchServiceImpl implements LanuchService { ...@@ -673,7 +689,8 @@ public class LanuchServiceImpl implements LanuchService {
*/ */
public ProdProcessExec createProcessExec(ProdLaunchOrder prodOrderMain, public ProdProcessExec createProcessExec(ProdLaunchOrder prodOrderMain,
RoutingDetail detail, RoutingDetail detail,
String sceneId,List<RoutingDetailEquip> routingDetailEquip) { String sceneId, List<RoutingDetailEquip> routingDetailEquip,
Integer departmentId) {
ProdProcessExec prodProcessExec = new ProdProcessExec(); ProdProcessExec prodProcessExec = new ProdProcessExec();
prodProcessExec.setExecId(UUID.randomUUID().toString().replace("-", "")); prodProcessExec.setExecId(UUID.randomUUID().toString().replace("-", ""));
...@@ -726,7 +743,9 @@ public class LanuchServiceImpl implements LanuchService { ...@@ -726,7 +743,9 @@ public class LanuchServiceImpl implements LanuchService {
prodProcessExec.setRoutingCode(prodOrderMain.getRoutingCode()); prodProcessExec.setRoutingCode(prodOrderMain.getRoutingCode());
prodProcessExec.setConnectPropertyName(detail.getConnectPropertyName()); prodProcessExec.setConnectPropertyName(detail.getConnectPropertyName());
prodProcessExec.setCanInterrupt(detail.getCanInterrupt()); prodProcessExec.setCanInterrupt(detail.getCanInterrupt());
if (departmentId != null) {
prodProcessExec.setDepartmentId(departmentId);
}
prodProcessExec.setSpeed( prodProcessExec.setSpeed(
Optional.ofNullable(detail.getRuntime()) Optional.ofNullable(detail.getRuntime())
......
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