fix(flow): restore workflow task converted pages

This commit is contained in:
2026-06-17 20:44:52 +08:00
parent 5946afa6e6
commit 57c3412aff
6 changed files with 689 additions and 15 deletions

View File

@@ -64,6 +64,19 @@ public final class EngineclassDelta {
// 非 crud 加按钮,走整页改写器(MUTATORS)。 // 非 crud 加按钮,走整页改写器(MUTATORS)。
registerMutator("com.dsasp.client.viewframework.component.FuncDownloadComponent", registerMutator("com.dsasp.client.viewframework.component.FuncDownloadComponent",
EngineclassDelta::funcDownloadDelta); EngineclassDelta::funcDownloadDelta);
// 流程待办/已办:TaskComponentNew/FinishTaskComponentNew 在默认 GridTemplateComponent 之上加任务详情/处理按钮。
// 这些模板的主键列就是 Flowable taskId(不同库可能为 VIEW_ACT_TASK_ID 或 VIEW_ACT_RU_TASK_ID),
// 因此必须使用转换后 crud.primaryField,不能硬编码列名。
register("com.dsasp.client.wf.task.component.TaskComponentNew",
EngineclassDelta::taskDetailButton,
EngineclassDelta::taskHandleButton);
register("com.dsasp.client.wf.task.component.FinishTaskComponentNew",
EngineclassDelta::finishedTaskDetailButton);
registerMutator("com.dsasp.client.wf.task.component.TaskComponentNew",
EngineclassDelta::taskTodoDataSource);
registerMutator("com.dsasp.client.wf.task.component.FinishTaskComponentNew",
EngineclassDelta::taskDoneDataSource);
} }
private EngineclassDelta() { private EngineclassDelta() {
@@ -223,6 +236,79 @@ public final class EngineclassDelta {
return kept.isEmpty(); return kept.isEmpty();
} }
// ── 工作流任务 · 查看详细 / 处理 ────────────────────────────────────────
/** 待办任务数据源:老 VIEW_ACT_RU_TASK 视图为空,改走 Flowable 聚合后的 amis 兼容端点。 */
private static void taskTodoDataSource(Map<String, Object> schema, ConversionResult result) {
replaceCrudApi(schema, "/api/workflow/tasks/todo-amis");
if (result != null) {
result.note("engineclass[TaskComponentNew] 改写待办任务数据源为 /api/workflow/tasks/todo-amis");
}
}
/** 已办任务数据源:老 VIEW_ACT_TASK_COMPLETE 服务流不可用,改走 Flowable 聚合后的 amis 兼容端点。 */
private static void taskDoneDataSource(Map<String, Object> schema, ConversionResult result) {
replaceCrudApi(schema, "/api/workflow/tasks/done-amis");
if (result != null) {
result.note("engineclass[FinishTaskComponentNew] 改写已办任务数据源为 /api/workflow/tasks/done-amis");
}
}
@SuppressWarnings("unchecked")
private static void replaceCrudApi(Map<String, Object> schema, String api) {
Object bodyObj = schema.get("body");
if (bodyObj instanceof Map<?, ?> body && "crud".equals(body.get("type"))) {
((Map<String, Object>) body).put("api", api);
}
}
/** 待办任务「查看详细」:选 1 条 → 按 taskId 打开只读审批详情。 */
private static Map<String, Object> taskDetailButton(String pkField) {
return approvalDrawerButton("查看详细", "fa fa-search", pkField, true);
}
/** 待办任务「处理」:选 1 条 → 按 taskId 打开可办理审批抽屉。 */
private static Map<String, Object> taskHandleButton(String pkField) {
Map<String, Object> btn = approvalDrawerButton("处理", "fa fa-edit", pkField, false);
btn.put("level", "primary");
return btn;
}
/** 已办任务「查看详细」:历史 taskId 只读查看业务单据与轨迹,不暴露办理动作。 */
private static Map<String, Object> finishedTaskDetailButton(String pkField) {
return approvalDrawerButton("查看详细", "fa fa-search", pkField, true);
}
private static Map<String, Object> approvalDrawerButton(String label, String icon, String pkField,
boolean readOnly) {
Map<String, Object> args = mapOf(
"taskId", selectedSingleFieldExpr(pkField),
"taskName", "${selectedItems[0].TASKNAME || selectedItems[0].TASK_NAME || selectedItems[0].TITLE || ''}",
"processInstanceId", "${selectedItems[0].processInstanceId || selectedItems[0].PROCESSINSTANCEID || ''}",
"businessKey", "${selectedItems[0].businessKey || selectedItems[0].BUSINESSKEY || ''}",
"businessTable", "${selectedItems[0].businessTable || selectedItems[0].BUSINESSTABLE || ''}",
"businessSummary", "${selectedItems[0].businessSummary || {}}",
"readOnly", readOnly,
"mode", readOnly ? "read" : "handle");
Map<String, Object> action = mapOf(
"actionType", "openApprovalDrawer",
"args", args);
Map<String, Object> btn = new LinkedHashMap<>();
btn.put("type", "button");
btn.put("id", label);
btn.put("label", label);
btn.put("icon", icon);
btn.put("disabledOn", "${!selectedItems || selectedItems.length !== 1}");
btn.put("onEvent", mapOf("click", mapOf("actions", List.of(action))));
return btn;
}
private static String selectedSingleFieldExpr(String field) {
if (field == null || field.isBlank()) {
return "${selectedItems[0].id}";
}
return "${selectedItems[0]." + field + "}";
}
// ── 用户管理 · 设置主岗位 ────────────────────────────────────────────── // ── 用户管理 · 设置主岗位 ──────────────────────────────────────────────
/** /**
* 「设置主岗位」按钮:选 1 用户 → 弹窗 form。initApi 拉该用户岗位(SYS_POSITIONUSER_SEARCH by USERID), * 「设置主岗位」按钮:选 1 用户 → 弹窗 form。initApi 拉该用户岗位(SYS_POSITIONUSER_SEARCH by USERID),

View File

@@ -913,6 +913,78 @@ class TemplateToAmisConverterTest {
"下钻应内嵌登录历史(edc05980) schema"); "下钻应内嵌登录历史(edc05980) schema");
} }
/** engineclass=TaskComponentNew → 注入「查看详细」「处理」并按 crud.primaryField 传 taskId。 */
@Test
@SuppressWarnings("unchecked")
void engineclass_TaskComponentNew_注入任务详情和处理按钮() {
String xml = "<crud entityid='e1'><display/></crud>";
ConversionResult r = converter.convertGraded(xml, null,
"com.dsasp.client.wf.task.component.TaskComponentNew", "待办任务", new ArrayList<>(), noPage);
List<Object> toolbar = (List<Object>) body(r.getSchema()).get("headerToolbar");
Map<String, Object> detail = toolbar.stream()
.filter(o -> o instanceof Map && "查看详细".equals(((Map<String, Object>) o).get("label")))
.map(o -> (Map<String, Object>) o).findFirst().orElse(null);
Map<String, Object> handle = toolbar.stream()
.filter(o -> o instanceof Map && "处理".equals(((Map<String, Object>) o).get("label")))
.map(o -> (Map<String, Object>) o).findFirst().orElse(null);
assertNotNull(detail, "待办任务应注入「查看详细」");
assertNotNull(handle, "待办任务应注入「处理」");
assertEquals("/api/workflow/tasks/todo-amis", body(r.getSchema()).get("api"),
"TaskComponentNew 应改走 Flowable 聚合 amis 数据源,避免老 VIEW_ACT_RU_TASK 视图空数据");
assertTrue(toolbar.indexOf(detail) < toolbar.indexOf("pagination"), "按钮应插在 pagination 前");
assertTrue(toolbar.indexOf(handle) < toolbar.indexOf("pagination"), "按钮应插在 pagination 前");
assertEquals("${!selectedItems || selectedItems.length !== 1}", detail.get("disabledOn"));
assertEquals("primary", handle.get("level"));
Map<String, Object> detailAction = (Map<String, Object>) ((List<Object>) ((Map<String, Object>)
((Map<String, Object>) detail.get("onEvent")).get("click")).get("actions")).get(0);
Map<String, Object> detailArgs = (Map<String, Object>) detailAction.get("args");
assertEquals("openApprovalDrawer", detailAction.get("actionType"));
assertEquals("${selectedItems[0].PM_DEMO_ID}", detailArgs.get("taskId"));
assertEquals("${selectedItems[0].processInstanceId || selectedItems[0].PROCESSINSTANCEID || ''}",
detailArgs.get("processInstanceId"));
assertEquals("${selectedItems[0].businessKey || selectedItems[0].BUSINESSKEY || ''}",
detailArgs.get("businessKey"));
assertEquals("${selectedItems[0].businessTable || selectedItems[0].BUSINESSTABLE || ''}",
detailArgs.get("businessTable"));
assertEquals(true, detailArgs.get("readOnly"));
Map<String, Object> handleAction = (Map<String, Object>) ((List<Object>) ((Map<String, Object>)
((Map<String, Object>) handle.get("onEvent")).get("click")).get("actions")).get(0);
Map<String, Object> handleArgs = (Map<String, Object>) handleAction.get("args");
assertEquals("openApprovalDrawer", handleAction.get("actionType"));
assertEquals("${selectedItems[0].PM_DEMO_ID}", handleArgs.get("taskId"));
assertEquals(false, handleArgs.get("readOnly"));
}
/** engineclass=FinishTaskComponentNew → 只注入只读「查看详细」,不暴露办理。 */
@Test
@SuppressWarnings("unchecked")
void engineclass_FinishTaskComponentNew_仅注入只读查看详细() {
String xml = "<crud entityid='e1'><display/></crud>";
ConversionResult r = converter.convertGraded(xml, null,
"com.dsasp.client.wf.task.component.FinishTaskComponentNew", "已办任务", new ArrayList<>(), noPage);
List<Object> toolbar = (List<Object>) body(r.getSchema()).get("headerToolbar");
Map<String, Object> detail = toolbar.stream()
.filter(o -> o instanceof Map && "查看详细".equals(((Map<String, Object>) o).get("label")))
.map(o -> (Map<String, Object>) o).findFirst().orElse(null);
boolean hasHandle = toolbar.stream()
.anyMatch(o -> o instanceof Map && "处理".equals(((Map<String, Object>) o).get("label")));
assertNotNull(detail, "已办任务应注入「查看详细」");
assertFalse(hasHandle, "已办任务不应注入「处理」");
assertEquals("/api/workflow/tasks/done-amis", body(r.getSchema()).get("api"),
"FinishTaskComponentNew 应改走 Flowable 聚合 amis 数据源,避免老 VIEW_ACT_TASK_COMPLETE 服务流不可用");
Map<String, Object> action = (Map<String, Object>) ((List<Object>) ((Map<String, Object>)
((Map<String, Object>) detail.get("onEvent")).get("click")).get("actions")).get(0);
Map<String, Object> args = (Map<String, Object>) action.get("args");
assertEquals("openApprovalDrawer", action.get("actionType"));
assertEquals("${selectedItems[0].PM_DEMO_ID}", args.get("taskId"));
assertEquals(true, args.get("readOnly"));
assertEquals("read", args.get("mode"));
}
/** /**
* engineclass=FuncDownloadComponent(功能模板下载模板管理/设置,type=3 树页)→ 整页改写器(机制① MUTATORS): * engineclass=FuncDownloadComponent(功能模板下载模板管理/设置,type=3 树页)→ 整页改写器(机制① MUTATORS):
* 移除右表单「添加」按钮(空 toolbar 整条移除)+ 右表单标题改「编辑模板附件」。复刻 refreshRightLayout。 * 移除右表单「添加」按钮(空 toolbar 整条移除)+ 右表单标题改「编辑模板附件」。复刻 refreshRightLayout。

View File

@@ -1,10 +1,23 @@
package com.eip4.platform.flowgateway.web; package com.eip4.platform.flowgateway.web;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects;
import java.util.Set;
import org.springframework.dao.DataAccessException;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
@@ -45,15 +58,22 @@ import io.swagger.v3.oas.annotations.tags.Tag;
@RestController @RestController
public class TodoController { public class TodoController {
private static final int DEFAULT_AMIS_PER_PAGE = 10;
private static final int LEGACY_TASK_FETCH_LIMIT = 1_000;
private static final DateTimeFormatter LEGACY_DATE_TIME =
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
private final TodoAggregator todoAggregator; private final TodoAggregator todoAggregator;
private final FlowableClient flowableClient; private final FlowableClient flowableClient;
private final StatusWriteback statusWriteback; private final StatusWriteback statusWriteback;
private final JdbcTemplate jdbcTemplate;
public TodoController(TodoAggregator todoAggregator, FlowableClient flowableClient, public TodoController(TodoAggregator todoAggregator, FlowableClient flowableClient,
StatusWriteback statusWriteback) { StatusWriteback statusWriteback, JdbcTemplate jdbcTemplate) {
this.todoAggregator = todoAggregator; this.todoAggregator = todoAggregator;
this.flowableClient = flowableClient; this.flowableClient = flowableClient;
this.statusWriteback = statusWriteback; this.statusWriteback = statusWriteback;
this.jdbcTemplate = jdbcTemplate;
} }
@Operation(summary = "当前用户待办(含候选组待办)", @Operation(summary = "当前用户待办(含候选组待办)",
@@ -76,6 +96,42 @@ public class TodoController {
return todoAggregator.done(userId, firstResult, maxResults); return todoAggregator.done(userId, firstResult, maxResults);
} }
/**
* 转换页「流程管理/待办任务」兼容端点。
*
* <p>老模板列绑定的是 {@code VIEW_ACT_RU_TASK_*} 视图字段,但当前有效待办数据源是
* {@link TodoAggregator}。这里保持老列名与查询字段不变,底层改走 Flowable 聚合,供 amis CRUD 直接消费。
*/
@Operation(summary = "转换页待办任务数据(amis)", description = "返回老 VIEW_ACT_RU_TASK 字段形态,底层走 /api/todo 聚合口径")
@GetMapping("/api/workflow/tasks/todo-amis")
public Map<String, Object> todoAmis(@AuthenticationPrincipal AuthPrincipal principal,
@RequestParam Map<String, String> params) {
String userId = principal == null ? null : principal.userId();
List<String> candidateGroups = principal == null ? List.of() : principal.roles();
List<TodoItem> raw = todoAggregator.todo(userId, candidateGroups, 0, LEGACY_TASK_FETCH_LIMIT);
List<Map<String, Object>> rows = raw.stream()
.map(item -> legacyTaskRow(item, false))
.filter(row -> matchesLegacyFilters(row, params, false))
.toList();
resolveInitiatorDisplayNames(rows);
return amisCrud(rows, params);
}
/** 转换页「流程管理/已办任务」兼容端点;列名对齐 VIEW_ACT_TASK_COMPLETE_SEARCH/VIEW_ACT_FTASK_COMPLETE_SEARCH。 */
@Operation(summary = "转换页已办任务数据(amis)", description = "返回老 VIEW_ACT_TASK 字段形态,底层走 /api/done 聚合口径")
@GetMapping("/api/workflow/tasks/done-amis")
public Map<String, Object> doneAmis(@AuthenticationPrincipal AuthPrincipal principal,
@RequestParam Map<String, String> params) {
String userId = principal == null ? null : principal.userId();
List<TodoItem> raw = todoAggregator.done(userId, 0, LEGACY_TASK_FETCH_LIMIT);
List<Map<String, Object>> rows = raw.stream()
.map(item -> legacyTaskRow(item, true))
.filter(row -> matchesLegacyFilters(row, params, true))
.toList();
resolveInitiatorDisplayNames(rows);
return amisCrud(rows, params);
}
@Operation(summary = "办理任务 + 回写业务状态", @Operation(summary = "办理任务 + 回写业务状态",
description = "complete 后,若请求带 businessKey/processInstanceId,按老系统 ProcessCoreServiceImpl 语义回写 SYS_DATASTATUS(结束→3 通过,未结束→2 处理中,守卫单调递增)。挂起任务被引擎拒为 409(透传)") description = "complete 后,若请求带 businessKey/processInstanceId,按老系统 ProcessCoreServiceImpl 语义回写 SYS_DATASTATUS(结束→3 通过,未结束→2 处理中,守卫单调递增)。挂起任务被引擎拒为 409(透传)")
@PostMapping("/api/task/{id}/complete") @PostMapping("/api/task/{id}/complete")
@@ -143,6 +199,258 @@ public class TodoController {
return pi == null || pi.ended; return pi == null || pi.ended;
} }
private static Map<String, Object> amisCrud(List<Map<String, Object>> rows, Map<String, String> params) {
int page = parsePositive(params.get("page"), 1);
int perPage = parsePositive(params.get("perPage"), DEFAULT_AMIS_PER_PAGE);
int from = Math.min((page - 1) * perPage, rows.size());
int to = Math.min(from + perPage, rows.size());
Map<String, Object> data = new LinkedHashMap<>();
data.put("items", rows.subList(from, to));
data.put("total", rows.size());
Map<String, Object> resp = new LinkedHashMap<>();
resp.put("status", 0);
resp.put("msg", "");
resp.put("data", data);
return resp;
}
private static Map<String, Object> legacyTaskRow(TodoItem item, boolean done) {
Map<String, Object> row = new LinkedHashMap<>();
String taskId = trim(item.taskId);
if (done) {
row.put("VIEW_ACT_TASK_ID", taskId);
row.put("VIEW_ACT_FTASK_ID", taskId);
} else {
row.put("VIEW_ACT_RU_TASK_ID", taskId);
}
row.put("TASKID", taskId);
row.put("TITLE", titleOf(item));
row.put("PROCESSNAME", processName(item.processDefinitionId));
row.put("TASKNAME", item.taskName);
row.put("STARTTIME", formatMillis(item.createTimeMillis));
row.put("ENDTIME", formatMillis(item.endTimeMillis));
row.put("WFSTATUS", done ? 3 : 2);
String initUser = summaryString(item, "USER_ID", "USERID", "INITUSERID");
row.put("INITUSERID", initUser);
row.put("INITUSERID_DISPLAY__", initUser);
String initOrg = summaryString(item, "USERORGID", "INITUSERORGID", "ORGID");
row.put("INITUSERORGID", initOrg);
row.put("INITUSERORGID_DISPLAY__", initOrg);
row.put("processInstanceId", item.processInstanceId);
row.put("businessKey", item.businessKey);
row.put("businessTable", item.businessTable);
row.put("businessSummary", item.businessSummary == null ? Map.of() : item.businessSummary);
row.put("pageTemplateId", item.pageTemplateId);
row.put("pageUrl", item.pageUrl);
row.put("pageUrlReason", item.pageUrlReason);
return row;
}
private void resolveInitiatorDisplayNames(List<Map<String, Object>> rows) {
Set<String> userIds = new LinkedHashSet<>();
for (Map<String, Object> row : rows) {
String userId = trim(Objects.toString(row.get("INITUSERID"), ""));
if (userId != null && !userId.isBlank()) {
userIds.add(userId);
}
}
if (userIds.isEmpty()) {
return;
}
Map<String, String> displayById = new HashMap<>();
List<String> ids = new ArrayList<>(userIds);
for (int from = 0; from < ids.size(); from += 200) {
List<String> batch = ids.subList(from, Math.min(from + 200, ids.size()));
String placeholders = String.join(",", Collections.nCopies(batch.size(), "?"));
try {
List<Map<String, Object>> matches = jdbcTemplate.queryForList(
"SELECT TRIM(VIEW_SYS_USER_ID) AS USER_ID, DISPLAYNAME AS DISPLAY_NAME "
+ "FROM VIEW_SYS_USER WHERE TRIM(VIEW_SYS_USER_ID) IN (" + placeholders + ")",
batch.toArray());
if (matches == null) {
continue;
}
for (Map<String, Object> match : matches) {
String userId = rowString(match, "USER_ID", "user_id", "ID", "id");
String displayName = rowString(match, "DISPLAY_NAME", "display_name", "DISPLAYNAME", "displayname");
if (userId != null && !userId.isBlank() && displayName != null && !displayName.isBlank()) {
displayById.put(userId, displayName);
}
}
} catch (DataAccessException ignored) {
return;
}
}
for (Map<String, Object> row : rows) {
String userId = trim(Objects.toString(row.get("INITUSERID"), ""));
String displayName = displayById.get(userId);
if (displayName != null && !displayName.isBlank()) {
row.put("INITUSERID_DISPLAY__", displayName);
}
}
}
private static boolean matchesLegacyFilters(Map<String, Object> row, Map<String, String> params, boolean done) {
return contains(row, params, "TITLE")
&& contains(row, params, "PROCESSNAME")
&& contains(row, params, "TASKNAME")
&& equalsIfPresent(row, params, "INITUSERID")
&& equalsIfPresent(row, params, "INITUSERORGID")
&& inDateRange(row.get("STARTTIME"), params.get("STARTTIME"))
&& (!done || inDateRange(row.get("ENDTIME"), params.get("ENDTIME")))
&& (!done || equalsIfPresent(row, params, "WFSTATUS"));
}
private static boolean contains(Map<String, Object> row, Map<String, String> params, String key) {
String needle = trim(params.get(key));
if (needle == null || needle.isBlank()) {
return true;
}
String value = trim(Objects.toString(row.get(key), ""));
return value != null && value.toLowerCase().contains(needle.toLowerCase());
}
private static boolean equalsIfPresent(Map<String, Object> row, Map<String, String> params, String key) {
String expected = trim(params.get(key));
if (expected == null || expected.isBlank()) {
return true;
}
return expected.equals(trim(Objects.toString(row.get(key), "")));
}
private static boolean inDateRange(Object raw, String range) {
String value = trim(Objects.toString(raw, ""));
String trimmedRange = trim(range);
if (trimmedRange == null || trimmedRange.isBlank() || value == null || value.isBlank()) {
return true;
}
if (trimmedRange.startsWith("[") && trimmedRange.endsWith("]")) {
trimmedRange = trimmedRange.substring(1, trimmedRange.length() - 1);
}
LocalDateTime actual = parseDateTime(value);
if (actual == null) {
return true;
}
String[] parts = trimmedRange.split(",", -1);
LocalDateTime start = parts.length > 0 ? parseDateTime(parts[0]) : null;
LocalDateTime end = parts.length > 1 ? parseDateTime(parts[1]) : null;
return (start == null || !actual.isBefore(start)) && (end == null || !actual.isAfter(end));
}
private static LocalDateTime parseDateTime(String raw) {
String s = trim(raw);
if (s == null || s.isBlank()) {
return null;
}
s = stripDateToken(s);
if (s.matches("-?\\d+")) {
try {
long epoch = Long.parseLong(s);
long millis = Math.abs(epoch) < 10_000_000_000L ? epoch * 1_000L : epoch;
return LocalDateTime.ofInstant(Instant.ofEpochMilli(millis), ZoneId.systemDefault());
} catch (NumberFormatException ignored) {
return null;
}
}
try {
return LocalDateTime.parse(s.replace('T', ' ').replaceAll("Z$", ""), LEGACY_DATE_TIME);
} catch (DateTimeParseException ignored) {
try {
return LocalDateTime.parse(s);
} catch (DateTimeParseException ignoredAgain) {
return null;
}
}
}
private static String stripDateToken(String raw) {
String s = trim(raw);
if (s == null || s.length() < 2) {
return s;
}
if ((s.startsWith("\"") && s.endsWith("\"")) || (s.startsWith("'") && s.endsWith("'"))) {
return trim(s.substring(1, s.length() - 1));
}
return s;
}
private static String titleOf(TodoItem item) {
if (item.businessSummary != null) {
for (String key : List.of("TITLE", "NAME", "SUBJECT", "NO", "SERIALNO", "FORMNO")) {
String value = summaryString(item, key);
if (value != null && !value.isBlank()) {
return value;
}
}
}
if (item.businessKey != null && !item.businessKey.isBlank()) {
return item.businessKey;
}
return item.taskName;
}
private static String summaryString(TodoItem item, String... keys) {
if (item.businessSummary == null || item.businessSummary.isEmpty()) {
return null;
}
for (String key : keys) {
Object value = item.businessSummary.get(key);
if (value == null) {
value = item.businessSummary.get(key.toLowerCase());
}
String s = trim(Objects.toString(value, ""));
if (s != null && !s.isBlank()) {
return s;
}
}
return null;
}
private static String rowString(Map<String, Object> row, String... keys) {
for (String key : keys) {
Object value = row.get(key);
String s = trim(Objects.toString(value, ""));
if (s != null && !s.isBlank()) {
return s;
}
}
return null;
}
private static String processName(String processDefinitionId) {
String s = trim(processDefinitionId);
if (s == null || s.isBlank()) {
return "";
}
int colon = s.indexOf(':');
return colon > 0 ? s.substring(0, colon) : s;
}
private static String formatMillis(Long millis) {
if (millis == null) {
return null;
}
return LEGACY_DATE_TIME.format(Instant.ofEpochMilli(millis).atZone(ZoneId.systemDefault()));
}
private static int parsePositive(String raw, int fallback) {
try {
int value = Integer.parseInt(Objects.toString(raw, "").trim());
return value > 0 ? value : fallback;
} catch (NumberFormatException e) {
return fallback;
}
}
private static String trim(String value) {
return value == null ? null : value.strip();
}
private static boolean notBlank(String s) { private static boolean notBlank(String s) {
return s != null && !s.isBlank(); return s != null && !s.isBlank();
} }

View File

@@ -0,0 +1,132 @@
package com.eip4.platform.flowgateway;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.springframework.jdbc.core.JdbcTemplate;
import com.eip4.platform.auth.security.AuthPrincipal;
import com.eip4.platform.flowgateway.aggregate.TodoAggregator;
import com.eip4.platform.flowgateway.aggregate.TodoItem;
import com.eip4.platform.flowgateway.client.FlowableClient;
import com.eip4.platform.flowgateway.web.TodoController;
import com.eip4.platform.flowgateway.writeback.StatusWriteback;
/** 转换页流程待办/已办 amis 兼容数据端点单测。 */
class TodoControllerAmisTest {
private final TodoAggregator aggregator = mock(TodoAggregator.class);
private final JdbcTemplate jdbcTemplate = mock(JdbcTemplate.class);
private final TodoController controller = new TodoController(
aggregator, mock(FlowableClient.class), mock(StatusWriteback.class), jdbcTemplate);
private static AuthPrincipal principal() {
return new AuthPrincipal("U1", "u1", "张三", "D1", "O1", List.of("R1"));
}
private static TodoItem item(String taskId, String title) {
return item(taskId, title, 1_700_000_000_000L);
}
private static TodoItem item(String taskId, String title, long createTimeMillis) {
TodoItem it = new TodoItem();
it.taskId = taskId;
it.taskName = "办公室主任";
it.processInstanceId = "PI-" + taskId;
it.processDefinitionId = "新闻审批:3:55882";
it.businessKey = "BK-" + taskId;
it.businessTable = "OA_NEWSMANAGE";
it.businessSummary = Map.of("TITLE", title, "USER_ID", "U1");
it.createTimeMillis = createTimeMillis;
it.endTimeMillis = createTimeMillis + 100_000L;
return it;
}
private static long epochMillis(int year, int month, int day, int hour, int minute) {
return LocalDateTime.of(year, month, day, hour, minute)
.atZone(ZoneId.systemDefault())
.toInstant()
.toEpochMilli();
}
private static long epochSeconds(int year, int month, int day, int hour, int minute) {
return epochMillis(year, month, day, hour, minute) / 1_000L;
}
@Test
@SuppressWarnings("unchecked")
void todoAmis_映射老待办列并支持主题过滤() {
when(aggregator.todo("U1", List.of("R1"), 0, 1_000))
.thenReturn(List.of(item("T1", "测试标题"), item("T2", "其他标题")));
when(jdbcTemplate.queryForList(anyString(), any(Object[].class)))
.thenReturn(List.of(Map.of("USER_ID", "U1", "DISPLAY_NAME", "张三")));
Map<String, Object> resp = controller.todoAmis(principal(),
Map.of("TITLE", "测试", "page", "1", "perPage", "10"));
assertThat(resp).containsEntry("status", 0);
Map<String, Object> data = (Map<String, Object>) resp.get("data");
List<Map<String, Object>> items = (List<Map<String, Object>>) data.get("items");
assertThat(data).containsEntry("total", 1);
assertThat(items).hasSize(1);
Map<String, Object> row = items.get(0);
assertThat(row).containsEntry("VIEW_ACT_RU_TASK_ID", "T1");
assertThat(row).containsEntry("TITLE", "测试标题");
assertThat(row).containsEntry("PROCESSNAME", "新闻审批");
assertThat(row).containsEntry("TASKNAME", "办公室主任");
assertThat(row).containsEntry("INITUSERID", "U1");
assertThat(row).containsEntry("INITUSERID_DISPLAY__", "张三");
assertThat(row).containsEntry("processInstanceId", "PI-T1");
assertThat(row).containsEntry("businessKey", "BK-T1");
assertThat(row).containsEntry("businessTable", "OA_NEWSMANAGE");
}
@Test
@SuppressWarnings("unchecked")
void doneAmis_映射已办双主键列并分页() {
when(aggregator.done("U1", 0, 1_000))
.thenReturn(List.of(item("D1", "已办一"), item("D2", "已办二")));
Map<String, Object> resp = controller.doneAmis(principal(),
Map.of("page", "2", "perPage", "1"));
Map<String, Object> data = (Map<String, Object>) resp.get("data");
List<Map<String, Object>> items = (List<Map<String, Object>>) data.get("items");
assertThat(data).containsEntry("total", 2);
assertThat(items).hasSize(1);
Map<String, Object> row = items.get(0);
assertThat(row).containsEntry("VIEW_ACT_TASK_ID", "D2");
assertThat(row).containsEntry("VIEW_ACT_FTASK_ID", "D2");
assertThat(row).containsEntry("WFSTATUS", 3);
assertThat(row.get("ENDTIME")).isNotNull();
}
@Test
@SuppressWarnings("unchecked")
void todoAmis_支持amis秒级任务发起时间区间过滤() {
when(aggregator.todo("U1", List.of("R1"), 0, 1_000))
.thenReturn(List.of(
item("T0", "区间前", epochMillis(2026, 6, 15, 17, 29)),
item("T1", "区间内", epochMillis(2026, 6, 16, 9, 0))));
String start = String.valueOf(epochSeconds(2026, 6, 15, 20, 37));
String end = String.valueOf(epochSeconds(2026, 6, 17, 20, 37));
Map<String, Object> resp = controller.todoAmis(principal(),
Map.of("STARTTIME", start + "," + end, "page", "1", "perPage", "10"));
Map<String, Object> data = (Map<String, Object>) resp.get("data");
List<Map<String, Object>> items = (List<Map<String, Object>>) data.get("items");
assertThat(data).containsEntry("total", 1);
assertThat(items).hasSize(1);
assertThat(items.get(0)).containsEntry("TITLE", "区间内");
}
}

View File

@@ -7,6 +7,7 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Properties; import java.util.Properties;
import java.util.Set; import java.util.Set;
import java.util.function.Supplier;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@@ -284,7 +285,7 @@ public class FlowController {
yield forbiddenWriteViaGet(id); yield forbiddenWriteViaGet(id);
} }
Properties ctx = UserSession.getAdmin(); Properties ctx = UserSession.getAdmin();
Object output = flowExcuteService.excute(map, ctx, id); Object output = withEngineContext(ctx, () -> flowExcuteService.excute(map, ctx, id));
yield ok(output, null); yield ok(output, null);
} }
case NAMED_READ -> { case NAMED_READ -> {
@@ -297,7 +298,7 @@ public class FlowController {
inputCoercer.coerceSearchDatesByFlowId(id, map); inputCoercer.coerceSearchDatesByFlowId(id, map);
} }
Properties ctx = UserSession.getAdmin(); Properties ctx = UserSession.getAdmin();
Object output = flowExcuteService.excute(map, ctx, id); Object output = withEngineContext(ctx, () -> flowExcuteService.excute(map, ctx, id));
yield ok(output, flowNameResolver.entityTableForNamedFlow(id)); yield ok(output, flowNameResolver.entityTableForNamedFlow(id));
} }
case NAMED_WRITE -> { case NAMED_WRITE -> {
@@ -316,17 +317,20 @@ public class FlowController {
? inputCoercer.missingRequiredIdInput(id, map) : null; ? inputCoercer.missingRequiredIdInput(id, map) : null;
if (pkInput != null) { if (pkInput != null) {
Properties fanoutCtx = currentCtx(); Properties fanoutCtx = currentCtx();
List<Object> results = new ArrayList<>(); List<Object> results = withEngineContext(fanoutCtx, () -> {
for (String one : ((String) map.get("ids")).split(",")) { List<Object> fanoutResults = new ArrayList<>();
if (one.isBlank()) { for (String one : ((String) map.get("ids")).split(",")) {
continue; if (one.isBlank()) {
continue;
}
Map<String, Object> per = new HashMap<>(map);
per.remove("ids");
per.put(pkInput, one.trim());
inputCoercer.coerceByFlowId(id, per);
fanoutResults.add(flowExcuteService.excute(per, fanoutCtx, id));
} }
Map<String, Object> per = new HashMap<>(map); return fanoutResults;
per.remove("ids"); });
per.put(pkInput, one.trim());
inputCoercer.coerceByFlowId(id, per);
results.add(flowExcuteService.excute(per, fanoutCtx, id));
}
Map<String, Object> agg = new LinkedHashMap<>(); Map<String, Object> agg = new LinkedHashMap<>();
agg.put("count", results.size()); agg.put("count", results.size());
agg.put("results", results); agg.put("results", results);
@@ -339,7 +343,7 @@ public class FlowController {
inputCoercer.coerceByFlowId(id, map); inputCoercer.coerceByFlowId(id, map);
} }
Properties ctx = currentCtx(); Properties ctx = currentCtx();
Object output = flowExcuteService.excute(map, ctx, id); Object output = withEngineContext(ctx, () -> flowExcuteService.excute(map, ctx, id));
yield ok(output, null); yield ok(output, null);
} }
case SYNTHESIZED -> { case SYNTHESIZED -> {
@@ -352,7 +356,7 @@ public class FlowController {
if (inputCoercer != null) { if (inputCoercer != null) {
inputCoercer.coerceSearchDatesByTable(tableFromSearchKey(flowKey), map); inputCoercer.coerceSearchDatesByTable(tableFromSearchKey(flowKey), map);
} }
Object output = flowExcuteService.excute(map, ctx, flowKey); Object output = withEngineContext(ctx, () -> flowExcuteService.excute(map, ctx, flowKey));
// 合成搜索流的 key = <TABLE>_SEARCH,剥后缀即数据源实体表名,用于用户引用列 id→姓名解析 // 合成搜索流的 key = <TABLE>_SEARCH,剥后缀即数据源实体表名,用于用户引用列 id→姓名解析
yield ok(output, tableFromSearchKey(flowKey)); yield ok(output, tableFromSearchKey(flowKey));
} }
@@ -385,6 +389,26 @@ public class FlowController {
return UserSession.getAdmin(); return UserSession.getAdmin();
} }
/**
* 保真层脚本除接收 {@code ctx} 参数外,还会直接调用 {@link UserSession#get()}。
* JWT 请求已由 {@code JwtAuthFilter} 绑定 ThreadLocal;无 JWT 的本地/巡检调用则在此临时绑定
* 本次执行上下文,并在返回后清理,避免脚本 NPE 且不污染 Tomcat 复用线程。
*/
private static <T> T withEngineContext(Properties ctx, Supplier<T> action) {
boolean fallbackBound = false;
if (UserSession.get() == null && ctx != null) {
UserSession.set(ctx);
fallbackBound = true;
}
try {
return action.get();
} finally {
if (fallbackBound) {
UserSession.remove();
}
}
}
private ResponseEntity<Map<String, Object>> ok(Object output, String table) { private ResponseEntity<Map<String, Object>> ok(Object output, String table) {
Object data = unwrapCrudResult(normalize(output)); Object data = unwrapCrudResult(normalize(output));
// read-path issue D1=603:把元数据标记为用户引用的列 id/工号 → 姓名(仅在已知数据源实体的合成搜索流上) // read-path issue D1=603:把元数据标记为用户引用的列 id/工号 → 姓名(仅在已知数据源实体的合成搜索流上)

View File

@@ -154,6 +154,58 @@ class FlowControllerTest {
assertNotNull(resp.getBody().get("data")); assertNotNull(resp.getBody().get("data"));
} }
@Test
@DisplayName("4b. 无 JWT 上下文时,读流执行期间临时绑定 ADMIN UserSession,执行后清理")
void readFlowBindsAdminUserSessionWhenMissing() {
String flowId = "VIEW_ACT_RU_TASK_SEARCH";
UserSession.remove();
try {
FlowExcuteService engine = mock(FlowExcuteService.class);
when(engine.excute(any(), any(Properties.class), eq(flowId))).thenAnswer(inv -> {
Properties bound = UserSession.get();
assertNotNull(bound, "老脚本会直接 UserSession.get(),执行期间必须有上下文");
assertEquals(LoggedInUser.ADMIN, bound.getProperty(LoggedInUser.CURRENTUSER));
return new HashMap<>();
});
FlowController controller = new FlowController(engine, resolverReturning(flowId, namedHit()));
ResponseEntity<Map<String, Object>> resp = controller.executeGet(flowId, new HashMap<>());
assertEquals(HttpStatus.OK, resp.getStatusCode());
assertEquals(0, resp.getBody().get("status"));
assertNull(UserSession.get(), "临时绑定必须在请求结束后清理,避免污染复用线程");
} finally {
UserSession.remove();
}
}
@Test
@DisplayName("4c. 已有 JWT UserSession 时,读流不覆盖当前用户上下文")
void readFlowKeepsExistingUserSession() {
String flowId = "VIEW_ACT_RU_TASK_SEARCH";
Properties realUser = new Properties();
realUser.setProperty(LoggedInUser.CURRENTUSER, "USER-1");
UserSession.set(realUser);
try {
FlowExcuteService engine = mock(FlowExcuteService.class);
when(engine.excute(any(), any(Properties.class), eq(flowId))).thenAnswer(inv -> {
org.junit.jupiter.api.Assertions.assertSame(realUser, UserSession.get(),
"JWT 绑定的真实用户上下文不能被 ADMIN 兜底覆盖");
return new HashMap<>();
});
FlowController controller = new FlowController(engine, resolverReturning(flowId, namedHit()));
ResponseEntity<Map<String, Object>> resp = controller.executeGet(flowId, new HashMap<>());
assertEquals(HttpStatus.OK, resp.getStatusCode());
assertEquals(0, resp.getBody().get("status"));
org.junit.jupiter.api.Assertions.assertSame(realUser, UserSession.get(),
"已有上下文由 JwtAuthFilter 负责 finally 清理,FlowController 不能提前移除");
} finally {
UserSession.remove();
}
}
@Test @Test
@DisplayName("5. listSelect 结果归一化:{listresult,pagecount} → {items,total}") @DisplayName("5. listSelect 结果归一化:{listresult,pagecount} → {items,total}")
void normalizeListSelectResult() { void normalizeListSelectResult() {