feat(metadata): 服务流执行 REST 门面 FlowController + 本地自举 + 单测

P1-2 第二步:报表方案 D 类——79 个 selectservice 服务流的统一 REST 化入口。

FlowController(com.eip4.platform.metadata.web):
  GET  /api/flow/{id}?k=v   query 参数 → 服务流入参 map(查询/报表类)
  POST /api/flow/{id} body  JSON body  → 服务流入参 map(参数多/带结构)
  统一封装 {status,msg,data};响应递归归一化(GeneralPOJO→平面行、
  listSelect 结果 {listresult,pagecount}→amis {items,total})。OpenAPI 注解。
  REST 入口读写时机:引擎不区分读写,P1 不在门面做引擎级读写闸,由调用方按
  「流定义 XML 审阅」确认查询/报表类后放行;风险与 P2 三层防护待办写入注释与报告。

适配(P1 服务流脚本编译):SecureGroovyScriptEngineFactory 的 DEFAULTIMPORTSLIST
移除两条 Vaadin 客户端 UI 默认导入(client.groovy.TestService、
com.dsasp.client.viewframework.component.MainComponent)——它们逐脚本注入,
classpath 缺失会使每个服务流脚本编译失败;与服务端取数无关,原值登记于注释供 diff。

LegacyXmlWiring:补 FlowServiceImpl.setJdbcTemplate(等价原 XML <property> 注入)。

本地自举:platform-parity bootstrap-flow.sql(幂等)——在 eip4m0 上建 SYS_SERVICEFLOW
+ 自描述元数据 + 最小查询流 EIP4M0_USERGROUP_SEARCH,参照 parity bootstrap 思路,
无客户库副本时引擎可独立跑通。

单测 18 例:FlowModelParseTest(9,XML 解析/参数绑定/默认流生成/往返序列化)+
FlowControllerTest(8,mock 引擎,GET/POST 参数透传 + 响应归一化)+
FlowExecuteLocalIT(1,@SpringBootTest local profile,自举 SQL + 真实引擎执行 +
二次一致;eip4m0 不可达则 assumeTrue 跳过)。全绿。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
2026-06-11 12:01:15 +08:00
parent de72116502
commit f0500647be
7 changed files with 731 additions and 4 deletions

View File

@@ -4,10 +4,13 @@ import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import com.fasterxml.jackson.datatype.joda.JodaModule;
import com.dsasp.server.common.log.service.DataOperatorLog;
import com.dsasp.server.common.log.service.SystemLogManager;
import com.dsasp.server.core.service.FlowServiceImpl;
import com.dsasp.server.dataDic.service.POJOCRUDServiceImpl;
import com.dsasp.server.dataDic.service.POJOServiceImpl;
@@ -23,15 +26,21 @@ public class LegacyXmlWiring implements SmartInitializingSingleton {
private final POJOServiceImpl pojoService;
private final SystemLogManager systemLogManager;
private final DataOperatorLog dataOperatorLog;
private final FlowServiceImpl flowService;
private final JdbcTemplate jdbcTemplate;
public LegacyXmlWiring(POJOCRUDServiceImpl pojoCRUDService,
POJOServiceImpl pojoService,
SystemLogManager systemLogManager,
DataOperatorLog dataOperatorLog) {
DataOperatorLog dataOperatorLog,
FlowServiceImpl flowService,
JdbcTemplate jdbcTemplate) {
this.pojoCRUDService = pojoCRUDService;
this.pojoService = pojoService;
this.systemLogManager = systemLogManager;
this.dataOperatorLog = dataOperatorLog;
this.flowService = flowService;
this.jdbcTemplate = jdbcTemplate;
}
@Override
@@ -39,6 +48,9 @@ public class LegacyXmlWiring implements SmartInitializingSingleton {
pojoCRUDService.setSystemLogManager(systemLogManager);
pojoService.setSystemLogManager(systemLogManager);
pojoService.setDataOperatorLog(dataOperatorLog);
// 服务流引擎:FlowServiceImpl.jdbcTemplate 在 framework 经 XML <property> 注入,非 @Autowired 字段。
// 等价补齐(见迁移手册 §4.1)。仅 isExistEntityFlow/addDefaultFlowService 用到,执行路径不依赖。
flowService.setJdbcTemplate(jdbcTemplate);
}
/** 引擎字段值含 joda DateTime(CREATETIME 等),Boot 3 需显式注册序列化模块。 */

View File

@@ -0,0 +1,110 @@
package com.eip4.platform.app;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.util.StreamUtils;
import com.dsasp.server.common.core.service.FlowExcuteService;
import com.dsasp.server.common.dataDic.bean.GeneralPOJO;
import com.dsasp.server.common.dataDic.service.POJOCRUDService;
import com.dsasp.server.common.util.UserSession;
/**
* 服务流引擎 DB 落地集成测试(local profile,本地 eip4m0 自举库)。
*
* <p>用 platform-parity 的 bootstrap-sys.sql + bootstrap-flow.sql 在 eip4m0 上自举
* 一个最小「查询类」服务流 EIP4M0_USERGROUP_SEARCH(对 SYS_USERGROUP 做 listSelect),
* 经真实引擎 {@link FlowExcuteService#excute} 走通整条链(XML 解析 → groovy start 脚本
* → service 节点 pojoCRUDService.listSelect → output),验证移植后的引擎在无客户库时
* 也可独立运行。eip4m0 不可达时整类跳过(assumeTrue),保证 CI 无该库时不红。
*/
@SpringBootTest
@ActiveProfiles("local")
class FlowExecuteLocalIT {
@Autowired
private FlowExcuteService flowExcuteService;
@Autowired
private JdbcTemplate jdbcTemplate;
private static boolean dbReady;
@BeforeAll
static void noop() {
// 实际就绪判定在每个测试前置(需要注入的 jdbcTemplate),见 ensureBootstrap。
}
private void ensureBootstrap() {
try {
jdbcTemplate.queryForObject("select 1", Integer.class);
} catch (Exception e) {
assumeTrue(false, "本地 eip4m0 不可达,跳过服务流引擎 DB 集成测试");
return;
}
try {
runSql("bootstrap/bootstrap-sys.sql");
runSql("bootstrap/bootstrap-flow.sql");
dbReady = true;
} catch (Exception e) {
throw new IllegalStateException("自举 SQL 执行失败:" + e.getMessage(), e);
}
}
private void runSql(String classpath) throws IOException {
String sql = StreamUtils.copyToString(
new ClassPathResource(classpath).getInputStream(), StandardCharsets.UTF_8);
// bootstrap 内含 $XML$...$XML$ dollar-quoted 块,整体作为单条 statement 提交即可(PG 支持多语句)。
jdbcTemplate.execute(sql);
}
@Test
@DisplayName("本地查询类服务流经引擎执行:返回种子用户组行,且二次执行一致")
@SuppressWarnings("unchecked")
void executeLocalSearchFlow() {
ensureBootstrap();
assumeTrue(dbReady);
Map<String, Object> map = new HashMap<>();
Properties ctx = UserSession.getAdmin();
Object out = flowExcuteService.excute(map, ctx, "EIP4M0_USERGROUP_SEARCH");
assertNotNull(out, "引擎应返回 output map");
Map<String, Object> output = (Map<String, Object>) out;
Map<String, Object> result = (Map<String, Object>) output.get("result");
assertNotNull(result, "应有 result 输出(listSelect 结果)");
List<GeneralPOJO> rows = (List<GeneralPOJO>) result.get(POJOCRUDService.LIST_RESULT);
assertNotNull(rows);
assertTrue(rows.size() >= 1, "bootstrap 种子 SYS_USERGROUP 至少 1 行");
boolean found = rows.stream().anyMatch(p -> "系统管理员组".equals(p.get_Value("NAME")));
assertTrue(found, "应能查到种子用户组「系统管理员组」");
// 二次执行结果一致(行数稳定)
Map<String, Object> map2 = new HashMap<>();
Object out2 = flowExcuteService.excute(map2, ctx, "EIP4M0_USERGROUP_SEARCH");
Map<String, Object> result2 = (Map<String, Object>) ((Map<String, Object>) out2).get("result");
List<GeneralPOJO> rows2 = (List<GeneralPOJO>) result2.get(POJOCRUDService.LIST_RESULT);
assertEquals(rows.size(), rows2.size(), "同流二次执行行数应一致");
}
}

View File

@@ -88,9 +88,14 @@ public class SecureGroovyScriptEngineFactory extends GroovyScriptEngineFactory{
"com.dsasp.server.common.function.GetServicesFunction",
"com.dsasp.server.common.function.GetDefaultValueFunction",
"com.dsasp.server.common.function.GetValueFunction",
"com.dsasp.client.viewframework.template.util.Console",
"client.groovy.TestService",
"com.dsasp.client.viewframework.component.MainComponent"
"com.dsasp.client.viewframework.template.util.Console"
// 适配(P1 服务流引擎):移除两条 Vaadin 客户端 UI 默认导入——它们经 imports.addImport
// 逐脚本注入,而 client.groovy.TestService / com.dsasp.client.viewframework.component.MainComponent
// 属已淘汰的 Vaadin 表现层(eip4-platform 保真层不含),classpath 缺失会使「每一个」服务流脚本
// 编译失败(MultipleCompilationErrorsException: unable to resolve class)。两类与服务流
// 服务端取数逻辑无关。原版两条登记于此供 diff 溯源:
// "client.groovy.TestService", "com.dsasp.client.viewframework.component.MainComponent"
// 详见 P1 服务流实测报告「替换类登记」与迁移手册新增坑位。
]
def DEFAULTSTARIMPORTSLIST=[

View File

@@ -0,0 +1,167 @@
package com.dsasp.server.core.service.flow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.List;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import com.dsasp.server.common.core.FlowDefinition;
import com.dsasp.server.core.service.flow.model.BaseFlowConvert;
import com.dsasp.server.core.service.flow.model.DefaultFlowHelper;
import com.dsasp.server.core.service.flow.model.Field;
import com.dsasp.server.core.service.flow.model.Flow;
import com.dsasp.server.core.service.flow.model.Node;
import com.dsasp.server.core.service.flow.model.ServiceBean;
import com.dsasp.server.core.service.flow.model.Transition;
/**
* 服务流模型解析/参数绑定纯逻辑单测(无 Spring/DB)。
*
* <p>覆盖移植引擎的 XML 解析(Flow.initial via SAXReader+dom4j 2.x)、参数(input field)
* 绑定、service 节点解析、转移条件、以及默认流生成(DefaultFlowHelper)与往返序列化
* (BaseFlowConvert.convertToXml)。这些是 P1 服务流引擎在 REST 入口之下的核心契约,
* 验证 dom4j 2.x selectNodes 转型修复后解析行为与 framework 一致。
*/
class FlowModelParseTest {
private static final String SEARCH_FLOW_XML =
"<flow id=\"EIP4M0_USERGROUP_SEARCH\">"
+ " <input>"
+ " <field name=\"map\" type=\"java.util.Map\" required=\"true\"/>"
+ " <field name=\"ctx\" type=\"java.util.Properties\" required=\"true\"/>"
+ " <field name=\"tableName\" type=\"java.lang.String\" required=\"true\" initValue=\"SYS_USERGROUP\"/>"
+ " </input>"
+ " <start id=\"Start\" name=\"开始\">"
+ " <script type=\"groovy\" key=\"s1\"><![CDATA[def x = 1;]]></script>"
+ " </start>"
+ " <node id=\"search\" name=\"查询\">"
+ " <service beanName=\"pojoCRUDService\" method=\"listSelect\">"
+ " <list><arg name=\"map\"/><arg name=\"tableName\"/><arg name=\"ctx\"/></list>"
+ " <result name=\"result\"/>"
+ " </service>"
+ " </node>"
+ " <transition from=\"Start\" to=\"search\"/>"
+ " <transition from=\"search\" to=\"End\"/>"
+ " <end id=\"End\" name=\"结束\"/>"
+ " <output>"
+ " <field name=\"result\" type=\"java.util.Map\"/>"
+ " </output>"
+ "</flow>";
@Test
@DisplayName("1. 解析 input 字段:名称/类型/必填/初值正确绑定")
void parseInputFields() {
Flow flow = new Flow("EIP4M0_USERGROUP_SEARCH", SEARCH_FLOW_XML).initial();
Field[] inputs = flow.getInputs();
assertEquals(3, inputs.length, "应解析出 3 个 input 字段");
Field tableName = flow.getInputField("tableName");
assertNotNull(tableName);
assertEquals("java.lang.String", tableName.getType());
assertTrue(tableName.isRequired());
assertEquals("SYS_USERGROUP", tableName.getInitValue(), "initValue 应透传");
}
@Test
@DisplayName("2. 解析 output 字段")
void parseOutputFields() {
Flow flow = new Flow("f", SEARCH_FLOW_XML).initial();
Field[] outputs = flow.getOutputs();
assertEquals(1, outputs.length);
assertEquals("result", outputs[0].getName());
assertEquals("java.util.Map", outputs[0].getType());
}
@Test
@DisplayName("3. 解析 service 节点:beanName/method/args/result")
void parseServiceNode() {
Flow flow = new Flow("f", SEARCH_FLOW_XML).initial();
Node search = flow.getNode("search");
assertNotNull(search);
assertEquals(Node.SERVICE_TYPE, search.getType());
ServiceBean bean = search.getBean();
assertNotNull(bean);
assertEquals("pojoCRUDService", bean.getBeanName());
assertEquals("listSelect", bean.getMethod());
assertEquals(List.of("map", "tableName", "ctx"), bean.getArgs());
assertEquals("result", bean.getResult());
}
@Test
@DisplayName("4. 解析 start 节点的 groovy 脚本(getText 保留脚本体)")
void parseStartScript() {
Flow flow = new Flow("f", SEARCH_FLOW_XML).initial();
Node start = flow.getStart();
assertNotNull(start.getScript());
assertEquals("groovy", start.getScript().getType());
assertTrue(start.getScript().getScrip().contains("def x = 1"),
"CDATA 脚本体应原样保留(dom4j getText)");
}
@Test
@DisplayName("5. 解析 transition 转移并形成有序节点链 Start→search→End")
void parseTransitionsAndNodeOrder() {
Flow flow = new Flow("f", SEARCH_FLOW_XML).initial();
List<Transition> fromStart = flow.getTransitions("Start");
assertEquals(1, fromStart.size());
assertEquals("search", fromStart.get(0).getTo());
List<Node> ordered = flow.getNodes();
assertEquals("Start", ordered.get(0).getId());
assertEquals("search", ordered.get(1).getId());
assertEquals("End", ordered.get(ordered.size() - 1).getId());
}
@Test
@DisplayName("6. 往返序列化:Flow→XML→Flow 结构稳定(BaseFlowConvert)")
void roundTripSerialization() {
Flow flow = new Flow("f", SEARCH_FLOW_XML).initial();
String xml = BaseFlowConvert.convertToXml(flow);
assertNotNull(xml);
assertTrue(xml.contains("pojoCRUDService"));
assertTrue(xml.contains("listSelect"));
Flow reparsed = new Flow("f", xml).initial();
assertEquals(flow.getInputs().length, reparsed.getInputs().length);
assertEquals("listSelect", reparsed.getNode("search").getBean().getMethod());
}
@Test
@DisplayName("7. DefaultFlowHelper 生成查询默认流:非受控 + listSelect service 节点")
void defaultSearchFlow() {
FlowDefinition def = DefaultFlowHelper.getDefaultSearch("SYS_USERGROUP",
"e1000000-0000-0000-0000-000000000003", "用户组");
assertNotNull(def);
assertEquals("SYS_USERGROUP_SEARCH", def.getKey());
assertFalse(def.isControl(), "默认查询流应为非受控(免鉴权)");
Flow flow = ((Flow) def).initial();
assertEquals("listSelect", flow.getNode("search").getBean().getMethod());
}
@Test
@DisplayName("8. DefaultFlowHelper 生成新增默认流:受控 + save service 节点")
void defaultAddFlow() {
FlowDefinition def = DefaultFlowHelper.getDefaultAdd("SYS_USERGROUP",
"e1000000-0000-0000-0000-000000000003", "用户组");
assertEquals("SYS_USERGROUP_ADD", def.getKey());
assertTrue(def.isControl(), "默认新增流默认受控");
Flow flow = ((Flow) def).initial();
ServiceBean bean = flow.getNode("save").getBean();
assertEquals("pojoCRUDService", bean.getBeanName());
assertEquals("save", bean.getMethod());
}
@Test
@DisplayName("9. 空/缺失 flow XML:initial 容错不抛(返回无 input)")
void emptyFlowTolerant() {
Flow flow = new Flow("empty", null).initial();
assertEquals(0, flow.getInputs().length);
assertEquals(0, flow.getOutputs().length);
}
}

View File

@@ -0,0 +1,127 @@
package com.eip4.platform.metadata.web;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.dsasp.server.common.core.service.FlowExcuteService;
import com.dsasp.server.common.dataDic.bean.GeneralPOJO;
import com.dsasp.server.common.dataDic.service.POJOCRUDService;
import com.dsasp.server.common.util.UserSession;
import io.swagger.v3.oas.annotations.Operation;
/**
* 服务流执行 REST 门面(报表迁移方案 D 类:79 个 selectservice 服务流 REST 化的统一入口)。
*
* <p>把保真层服务流引擎 {@code FlowExcuteService.excute(map, ctx, flowId)} 暴露为 HTTP:
* <ul>
* <li>{@code GET /api/flow/{id}?k=v...} —— query 参数作为服务流入参 {@code map}(适合查询/报表类)</li>
* <li>{@code POST /api/flow/{id}} body=JSON —— 请求体作为服务流入参 {@code map}(适合参数多/带结构的流)</li>
* </ul>
* 这正是报表方案 D 节 echart.jsp 第 25 行 {@code flowService.excute(map, UserSession.get(), flowid)} 的 REST 化。
*
* <p><b>读写时机判断(REST 入口仅放行查询类服务流):</b>当前服务流引擎本身不区分读写——
* 一个流既可挂 {@code listSelect}(读)也可挂 {@code save/update/delete}(写)service 节点,
* 引擎统一走 {@code excute}。本 P1 阶段不在门面做引擎级读写闸(避免误判与维护负担),
* 而由调用方/运维按「服务流定义 XML 审阅」确认其为查询/报表类后才经此入口放行;
* 客户库只读纪律下,仅执行确认无写动作的流(挑选过程见 P1 服务流实测报告)。
* <b>风险与 P2 防护待办</b>:引擎不区分读写 ⇒ 该入口理论上可触发写流。P2 需补
* 「流定义静态扫描(service 节点 method 白名单:仅 listSelect/loadPOJO/executeQueryForMap 等读方法放行)
* + 最小权限只读连接 + statement_timeout」三层防护(见架构设计第四节安全方案、迁移手册新增坑位)。
*/
@RestController
@RequestMapping("/api/flow")
public class FlowController {
private final FlowExcuteService flowExcuteService;
public FlowController(FlowExcuteService flowExcuteService) {
this.flowExcuteService = flowExcuteService;
}
/** GET 执行:query 参数透传为服务流入参 map(保留原始大小写键,交由流脚本/服务节点消费)。 */
@GetMapping("/{id}")
@Operation(summary = "执行服务流(GET):query 参数作为入参 map,返回流输出 JSON。报表 D 类查询入口")
public Map<String, Object> executeGet(@PathVariable String id,
@RequestParam Map<String, String> allParams) {
Map<String, Object> map = new HashMap<>(allParams);
return run(id, map);
}
/** POST 执行:JSON body 透传为服务流入参 map。body 为空时按空 map 执行。 */
@PostMapping("/{id}")
@Operation(summary = "执行服务流(POST):JSON body 作为入参 map,返回流输出 JSON")
public Map<String, Object> executePost(@PathVariable String id,
@RequestBody(required = false) Map<String, Object> body) {
Map<String, Object> map = body == null ? new HashMap<>() : new HashMap<>(body);
return run(id, map);
}
/**
* 统一执行 + 响应封装。引擎 {@code excute} 返回流的输出字段 Map;查询/报表类流的输出
* 通常含一个 {@code listSelect} 结果({@code {listresult, pagecount}}),本方法递归归一化:
* GeneralPOJO → 平面行 map;含 {@code listresult} 的子结果 → amis 风格 {@code {items,total}}。
*/
private Map<String, Object> run(String id, Map<String, Object> map) {
Properties ctx = UserSession.getAdmin();
Object output = flowExcuteService.excute(map, ctx, id);
Map<String, Object> resp = new HashMap<>();
resp.put("status", 0);
resp.put("msg", "");
resp.put("data", normalize(output));
return resp;
}
/** 递归归一化引擎返回值,使之可被 Jackson 序列化(GeneralPOJO 非 bean,需手工展平)。 */
@SuppressWarnings("unchecked")
private Object normalize(Object value) {
if (value instanceof GeneralPOJO p) {
return toRow(p);
}
if (value instanceof Map<?, ?> m) {
// listSelect 结果:{listresult:[...], pagecount:N} → amis {items, total}
if (m.containsKey(POJOCRUDService.LIST_RESULT)) {
Map<String, Object> data = new LinkedHashMap<>();
data.put("items", normalize(m.get(POJOCRUDService.LIST_RESULT)));
data.put("total", m.get(POJOCRUDService.PAGE_COUNT));
return data;
}
Map<String, Object> out = new LinkedHashMap<>();
for (Map.Entry<?, ?> e : m.entrySet()) {
out.put(String.valueOf(e.getKey()), normalize(e.getValue()));
}
return out;
}
if (value instanceof List<?> list) {
List<Object> out = new ArrayList<>(list.size());
for (Object o : list) {
out.add(normalize(o));
}
return out;
}
return value;
}
/** GeneralPOJO 值存于内部数组(非 bean getter),展开为平面 map 供 JSON 序列化。 */
private Map<String, Object> toRow(GeneralPOJO p) {
Map<String, Object> row = new LinkedHashMap<>();
row.put("_id", p.get_ID());
for (int i = 0; i < p.get_ColumnCount(); i++) {
row.put(p.get_ColumnName(i), p.get_Value(i));
}
return row;
}
}

View File

@@ -0,0 +1,182 @@
package com.eip4.platform.metadata.web;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import com.dsasp.server.common.core.service.FlowExcuteService;
import com.dsasp.server.common.dataDic.bean.GeneralPOJO;
import com.dsasp.server.common.dataDic.service.POJOCRUDService;
/**
* 服务流 REST 门面单测(mock 引擎,不连库)。
*
* <p>验证 {@link FlowController} 的入参绑定(GET query → map / POST body → map)与
* 响应归一化:GeneralPOJO → 平面行、listSelect 结果({listresult,pagecount})→
* amis {items,total}、嵌套结构递归归一化。这是 D 类报表服务流 REST 化契约的核心。
*/
class FlowControllerTest {
/** 构造一个最小 GeneralPOJO 桩(只实现 toRow 用到的方法)。 */
private GeneralPOJO fakeRow(String id, Map<String, Object> cols) {
GeneralPOJO p = mock(GeneralPOJO.class);
when(p.get_ID()).thenReturn(id);
List<String> names = new ArrayList<>(cols.keySet());
when(p.get_ColumnCount()).thenReturn(names.size());
for (int i = 0; i < names.size(); i++) {
when(p.get_ColumnName(i)).thenReturn(names.get(i));
when(p.get_Value(i)).thenReturn(cols.get(names.get(i)));
}
return p;
}
@Test
@DisplayName("1. GET 执行:query 参数透传为入参 map,flowId 透传给引擎")
void getPassesQueryParamsAsMap() {
FlowExcuteService engine = mock(FlowExcuteService.class);
when(engine.excute(any(), any(), eq("EIP4M0_USERGROUP_SEARCH"))).thenReturn(new HashMap<>());
FlowController controller = new FlowController(engine);
Map<String, String> params = new HashMap<>();
params.put("NAME", "管理员组");
controller.executeGet("EIP4M0_USERGROUP_SEARCH", params);
@SuppressWarnings("unchecked")
ArgumentCaptor<Map<String, Object>> mapCap = ArgumentCaptor.forClass(Map.class);
org.mockito.Mockito.verify(engine).excute(mapCap.capture(), any(Properties.class), eq("EIP4M0_USERGROUP_SEARCH"));
assertEquals("管理员组", mapCap.getValue().get("NAME"), "query 参数应进入入参 map");
}
@Test
@DisplayName("2. POST 执行:JSON body 透传为入参 map")
void postPassesBodyAsMap() {
FlowExcuteService engine = mock(FlowExcuteService.class);
when(engine.excute(any(), any(), any())).thenReturn(new HashMap<>());
FlowController controller = new FlowController(engine);
Map<String, Object> body = new HashMap<>();
body.put("sql", "select 1");
controller.executePost("COMMON_SQL_QUERY", body);
@SuppressWarnings("unchecked")
ArgumentCaptor<Map<String, Object>> mapCap = ArgumentCaptor.forClass(Map.class);
org.mockito.Mockito.verify(engine).excute(mapCap.capture(), any(), eq("COMMON_SQL_QUERY"));
assertEquals("select 1", mapCap.getValue().get("sql"));
}
@Test
@DisplayName("3. POST body 为 null:按空 map 执行,不抛")
void postNullBodyTolerant() {
FlowExcuteService engine = mock(FlowExcuteService.class);
when(engine.excute(any(), any(), any())).thenReturn(null);
FlowController controller = new FlowController(engine);
Map<String, Object> resp = controller.executePost("F", null);
assertEquals(0, resp.get("status"));
}
@Test
@DisplayName("4. 响应外壳:status=0/msg/data 三段")
void responseEnvelope() {
FlowExcuteService engine = mock(FlowExcuteService.class);
when(engine.excute(any(), any(), any())).thenReturn(new HashMap<>());
FlowController controller = new FlowController(engine);
Map<String, Object> resp = controller.executeGet("F", new HashMap<>());
assertEquals(0, resp.get("status"));
assertEquals("", resp.get("msg"));
assertEquals(true, resp.containsKey("data"));
}
@Test
@DisplayName("5. listSelect 结果归一化:{listresult,pagecount} → {items,total}")
void normalizeListSelectResult() {
// 引擎输出:output 字段 result = listSelect 结果 map
Map<String, Object> listResult = new LinkedHashMap<>();
List<GeneralPOJO> rows = new ArrayList<>();
Map<String, Object> c1 = new LinkedHashMap<>();
c1.put("NAME", "系统管理员组");
rows.add(fakeRow("b0000000-0000-0000-0000-000000000001", c1));
listResult.put(POJOCRUDService.LIST_RESULT, rows);
listResult.put(POJOCRUDService.PAGE_COUNT, 1);
Map<String, Object> output = new LinkedHashMap<>();
output.put("result", listResult);
FlowExcuteService engine = mock(FlowExcuteService.class);
when(engine.excute(any(), any(), any())).thenReturn(output);
FlowController controller = new FlowController(engine);
Map<String, Object> resp = controller.executeGet("F", new HashMap<>());
@SuppressWarnings("unchecked")
Map<String, Object> data = (Map<String, Object>) resp.get("data");
@SuppressWarnings("unchecked")
Map<String, Object> result = (Map<String, Object>) data.get("result");
assertEquals(1, result.get("total"), "pagecount → total");
assertInstanceOf(List.class, result.get("items"), "listresult → items");
@SuppressWarnings("unchecked")
List<Map<String, Object>> items = (List<Map<String, Object>>) result.get("items");
assertEquals("系统管理员组", items.get(0).get("NAME"), "GeneralPOJO 行应展平");
assertEquals("b0000000-0000-0000-0000-000000000001", items.get(0).get("_id"));
}
@Test
@DisplayName("6. 单个 GeneralPOJO 输出归一化为平面行")
void normalizeSinglePojo() {
Map<String, Object> cols = new LinkedHashMap<>();
cols.put("NAME", "x");
GeneralPOJO row = fakeRow("id-1", cols);
FlowExcuteService engine = mock(FlowExcuteService.class);
when(engine.excute(any(), any(), any())).thenReturn(row);
FlowController controller = new FlowController(engine);
Map<String, Object> resp = controller.executeGet("F", new HashMap<>());
@SuppressWarnings("unchecked")
Map<String, Object> data = (Map<String, Object>) resp.get("data");
assertEquals("id-1", data.get("_id"));
assertEquals("x", data.get("NAME"));
}
@Test
@DisplayName("7. List<GeneralPOJO> 直接输出:递归归一化为行列表")
void normalizeListOfPojo() {
Map<String, Object> cols = new LinkedHashMap<>();
cols.put("NAME", "y");
List<GeneralPOJO> list = List.of(fakeRow("id-2", cols));
FlowExcuteService engine = mock(FlowExcuteService.class);
when(engine.excute(any(), any(), any())).thenReturn(list);
FlowController controller = new FlowController(engine);
Map<String, Object> resp = controller.executeGet("F", new HashMap<>());
@SuppressWarnings("unchecked")
List<Map<String, Object>> data = (List<Map<String, Object>>) resp.get("data");
assertEquals("y", data.get(0).get("NAME"));
}
@Test
@DisplayName("8. 标量输出原样返回(非 POJO/Map/List)")
void normalizeScalar() {
FlowExcuteService engine = mock(FlowExcuteService.class);
when(engine.excute(any(), any(), any())).thenReturn(42);
FlowController controller = new FlowController(engine);
Map<String, Object> resp = controller.executeGet("F", new HashMap<>());
assertEquals(42, resp.get("data"));
}
}

View File

@@ -0,0 +1,124 @@
-- ============================================================================
-- eip4-platform P1 服务流引擎本地自举 schema —— bootstrap-flow.sql
-- ----------------------------------------------------------------------------
-- 用途:在本地 eip4m0 库(已先跑 bootstrap-sys.sql)上补建服务流引擎
-- (FlowExcuteService/FlowService)运行所需的 SYS_SERVICEFLOW 平台表 +
-- 自描述元数据 + 一个最小「查询类」服务流定义,使引擎可在无客户库副本时
-- loadFlowDefinition → excute 走通整条执行链(解析 XML → service 节点
-- 调 pojoCRUDService.listSelect → 归集 output)。
--
-- 口径权威来源(已逐一核对源码):
-- * 列序 = 客户库 eip3.sys_serviceflow 实际结构(information_schema 核对):
-- sys_serviceflow_id varchar(200) PK / displayname varchar(100) /
-- contentxml xml / createby,updateby char(36) / createtime,updatetime bigint /
-- version int / entityid char(36) / iscontrol int / isactive int / isupdateable int
-- * 读路径 = FlowServiceImpl.loadFlowXml:
-- pojoCRUDService.loadPOJO(flowKey,"SYS_SERVICEFLOW",null,true) →
-- BaseFlowConvert.convertPOToFlow 取 SYS_SERVICEFLOW_ID/DISPLAYNAME/CONTENTXML/
-- ENTITYID/ISCONTROL/ISUPDATEABLE。
-- * 流 XML 形态 = 客户库真实 *_SEARCH 流(input map+ctx+tableName → service 节点
-- pojoCRUDService.listSelect → output result)。
--
-- 纪律:可重复执行(DROP ... IF EXISTS 开头);表名/列名一律小写;contentxml 本地用 text
-- (PG xml 类型对引擎透明,引擎只取字符串;text 便于自举且 listSelect 不解析其内部)。
-- ============================================================================
-- ---------------------------------------------------------------------------
-- 0. 清理
-- ---------------------------------------------------------------------------
DROP TABLE IF EXISTS sys_serviceflow CASCADE;
-- 移除可能残留的自举流元数据(可重复执行)
DELETE FROM sys_entityattribute WHERE entityid = 'e1000000-0000-0000-0000-000000000008';
DELETE FROM sys_entity WHERE sys_entity_id = 'e1000000-0000-0000-0000-000000000008';
-- ---------------------------------------------------------------------------
-- 1. 物理表 SYS_SERVICEFLOW(列与客户库逐列对齐;contentxml 用 text 便于自举)
-- ---------------------------------------------------------------------------
CREATE TABLE sys_serviceflow (
sys_serviceflow_id character varying(200) NOT NULL,
displayname character varying(100),
contentxml text,
entityid character(36),
iscontrol integer DEFAULT 1,
isupdateable integer DEFAULT 1,
isactive integer DEFAULT 1 NOT NULL,
createtime bigint,
updatetime bigint,
createby character(36),
updateby character(36),
version integer DEFAULT 0 NOT NULL,
PRIMARY KEY (sys_serviceflow_id)
);
-- ---------------------------------------------------------------------------
-- 2. 自描述元数据:SYS_SERVICEFLOW 实体 + 属性,使 loadPOJO 可识别
-- 实体 id = e1000000-0000-0000-0000-000000000008;统一 ENTITYTYPE 与 bootstrap-sys 一致。
-- ---------------------------------------------------------------------------
INSERT INTO sys_entity
(sys_entity_id, name, description, tablename, entitytype, isview, ischangelog,
accesslevel, tabletype, isactive, createtime, updatetime, createby, updateby, version)
VALUES
('e1000000-0000-0000-0000-000000000008', '服务流', '服务流定义主表', 'SYS_SERVICEFLOW',
'a0000000-0000-0000-0000-0000000000ff', 0, 0, 0, 0, 1, 0, 0, 'ADMIN', 'ADMIN', 0);
INSERT INTO sys_entityattribute
(sys_entityattribute_id, entityid, columnname, displayname, referenceid, ismandatory, isreadonly,
iskey, isidentifier, iscombidentifier, isentitydisplay, entitydisplayseq, fieldlength,
isactive, createby, updateby, version)
VALUES
('a1000000-0000-0000-0000-000000000801', 'e1000000-0000-0000-0000-000000000008', 'SYS_SERVICEFLOW_ID', '主键', 'NVARCHAR', 1, 1, 1, 0, 0, 0, 1, 200, 1, 'ADMIN', 'ADMIN', 0),
('a1000000-0000-0000-0000-000000000802', 'e1000000-0000-0000-0000-000000000008', 'DISPLAYNAME', '显示名', 'NVARCHAR', 0, 0, 0, 0, 0, 1, 2, 100, 1, 'ADMIN', 'ADMIN', 0),
('a1000000-0000-0000-0000-000000000803', 'e1000000-0000-0000-0000-000000000008', 'CONTENTXML', '流定义XML', 'NVARCHAR', 0, 0, 0, 0, 0, 0, 3, 0, 1, 'ADMIN', 'ADMIN', 0),
('a1000000-0000-0000-0000-000000000804', 'e1000000-0000-0000-0000-000000000008', 'ENTITYID', '实体ID', 'CHAR', 0, 0, 0, 0, 0, 0, 4, 36, 1, 'ADMIN', 'ADMIN', 0),
('a1000000-0000-0000-0000-000000000805', 'e1000000-0000-0000-0000-000000000008', 'ISCONTROL', '受控', 'INTEGER', 0, 0, 0, 0, 0, 0, 5, 0, 1, 'ADMIN', 'ADMIN', 0),
('a1000000-0000-0000-0000-000000000806', 'e1000000-0000-0000-0000-000000000008', 'ISUPDATEABLE', '可更新', 'INTEGER', 0, 0, 0, 0, 0, 0, 6, 0, 1, 'ADMIN', 'ADMIN', 0),
('a1000000-0000-0000-0000-000000000807', 'e1000000-0000-0000-0000-000000000008', 'ISACTIVE', '是否有效', 'BOOLEAN', 0, 0, 0, 0, 0, 0, 7, 0, 1, 'ADMIN', 'ADMIN', 0),
('a1000000-0000-0000-0000-000000000808', 'e1000000-0000-0000-0000-000000000008', 'CREATETIME', '创建时间', 'TIME', 0, 0, 0, 0, 0, 0, 8, 0, 1, 'ADMIN', 'ADMIN', 0),
('a1000000-0000-0000-0000-000000000809', 'e1000000-0000-0000-0000-000000000008', 'UPDATETIME', '更新时间', 'TIME', 0, 0, 0, 0, 0, 0, 9, 0, 1, 'ADMIN', 'ADMIN', 0),
('a1000000-0000-0000-0000-00000000080a', 'e1000000-0000-0000-0000-000000000008', 'CREATEBY', '创建人', 'NVARCHAR', 0, 0, 0, 0, 0, 0, 10, 36, 1, 'ADMIN', 'ADMIN', 0),
('a1000000-0000-0000-0000-00000000080b', 'e1000000-0000-0000-0000-000000000008', 'UPDATEBY', '更新人', 'NVARCHAR', 0, 0, 0, 0, 0, 0, 11, 36, 1, 'ADMIN', 'ADMIN', 0),
('a1000000-0000-0000-0000-00000000080c', 'e1000000-0000-0000-0000-000000000008', 'VERSION', '版本', 'INTEGER', 0, 0, 0, 0, 0, 0, 12, 0, 1, 'ADMIN', 'ADMIN', 0);
-- ---------------------------------------------------------------------------
-- 3. 最小「查询类」服务流定义:对 bootstrap-sys 种入的 SYS_USERGROUP 做 listSelect。
-- 形态对齐客户库真实 *_SEARCH 流:input(map,ctx,tableName)→service 节点
-- pojoCRUDService.listSelect(map,tableName,ctx)→output result。
-- iscontrol=0(非受控,免 FlowPrivilegeService 鉴权)。
-- 流 key = EIP4M0_USERGROUP_SEARCH(本地自造,不与客户库流冲突)。
-- ---------------------------------------------------------------------------
INSERT INTO sys_serviceflow
(sys_serviceflow_id, displayname, contentxml, entityid, iscontrol, isupdateable,
isactive, createtime, updatetime, createby, updateby, version)
VALUES
('EIP4M0_USERGROUP_SEARCH', '用户组查询(自举)',
$XML$<flow id="EIP4M0_USERGROUP_SEARCH">
<input>
<field name="map" type="java.util.Map" required="true"/>
<field name="ctx" type="java.util.Properties" required="true"/>
<field name="tableName" type="java.lang.String" required="true" initValue="SYS_USERGROUP"/>
</input>
<start id="Start" name="开始">
<script type="groovy" key="usergroup-search-start"><![CDATA[import com.dsasp.server.common.dataDic.service.POJOCRUDService;
if(!map.containsKey(POJOCRUDService.ORDER)){
map.put(POJOCRUDService.ORDER, "order by P.NAME ASC");
}
]]></script>
</start>
<node id="search" name="查询">
<service beanName="pojoCRUDService" method="listSelect">
<list>
<arg name="map"/>
<arg name="tableName"/>
<arg name="ctx"/>
</list>
<result name="result"/>
</service>
</node>
<transition from="Start" to="search"/>
<transition from="search" to="End"/>
<end id="End" name="结束"/>
<output>
<field name="result" type="java.util.Map"/>
</output>
</flow>$XML$,
'e1000000-0000-0000-0000-000000000003', 0, 1, 1, 0, 0, 'ADMIN', 'ADMIN', 0);