feat: wire schedule notifications and data import downloads
Some checks failed
ci / build-test-parity (push) Has been cancelled

This commit is contained in:
2026-06-18 09:59:55 +08:00
parent 46dfa9c5a2
commit c9e4d35ca1
6 changed files with 1056 additions and 2 deletions

View File

@@ -107,10 +107,16 @@ public final class EngineclassDelta {
register("com.dsasp.client.tools.schedulejob.ScheduleJobDesignComponent", register("com.dsasp.client.tools.schedulejob.ScheduleJobDesignComponent",
EngineclassDelta::scheduleJobScriptButton); EngineclassDelta::scheduleJobScriptButton);
// 数据导入配置管理:DataImportConfigView 加「编辑转换脚本 / 编辑保存脚本」。 // 设置定时任务:ScheduleJobSettingComponent 加「设置提醒人」,结构化编辑 SENDINFO JSON。
register("com.dsasp.client.tools.schedulejob.ScheduleJobSettingComponent",
EngineclassDelta::scheduleJobNotifyButton);
// 数据导入配置管理:DataImportConfigView 加「编辑转换脚本 / 编辑保存脚本 / 下载模板 / 下载基础数据」。
register("com.dsasp.client.dataimport.view.DataImportConfigView", register("com.dsasp.client.dataimport.view.DataImportConfigView",
EngineclassDelta::dataImportConvertScriptButton, EngineclassDelta::dataImportConvertScriptButton,
EngineclassDelta::dataImportSaveScriptButton); EngineclassDelta::dataImportSaveScriptButton,
EngineclassDelta::dataImportTemplateDownloadButton,
EngineclassDelta::dataImportBaseDataDownloadButton);
// 功能/视图管理与自定义列表:先补高级配置 XML 源码编辑入口;可视化设计器另走独立路由。 // 功能/视图管理与自定义列表:先补高级配置 XML 源码编辑入口;可视化设计器另走独立路由。
register("com.dsasp.client.viewframework.component.UserFunDesignComponent", register("com.dsasp.client.viewframework.component.UserFunDesignComponent",
@@ -576,6 +582,161 @@ public final class EngineclassDelta {
"SYS_DATAIMPORTCONFIG", "SYS_DATAIMPORTCONFIG_ID", pkField, "SAVESCRIPT", "java"); "SYS_DATAIMPORTCONFIG", "SYS_DATAIMPORTCONFIG_ID", pkField, "SAVESCRIPT", "java");
} }
private static Map<String, Object> dataImportTemplateDownloadButton(String pkField) {
return downloadButton("下载模板", "fa fa-download",
"/api/dataimport/template?configId=" + selectedSingleFieldExpr(pkField));
}
private static Map<String, Object> dataImportBaseDataDownloadButton(String pkField) {
return downloadButton("下载基础数据", "fa fa-download", "/api/dataimport/basedata");
}
private static Map<String, Object> scheduleJobNotifyButton(String pkField) {
String idExpr = selectedSingleFieldExpr(pkField);
Map<String, Object> form = mapOf(
"type", "form",
"id", "schedulejob-notify-form",
"wrapWithPanel", false,
"initApi", mapOf(
"method", "get",
"url", "/api/schedulejob/" + idExpr + "/notify"),
"api", mapOf(
"method", "post",
"url", "/api/schedulejob/" + idExpr + "/notify",
"data", mapOf("items", "${items}")),
"body", List.of(scheduleJobNotifyTable()));
Map<String, Object> btn = new LinkedHashMap<>();
btn.put("type", "button");
btn.put("id", "设置提醒人");
btn.put("label", "设置提醒人");
btn.put("icon", "fa fa-bell");
btn.put("disabledOn", "${!selectedItems || selectedItems.length !== 1}");
btn.put("actionType", "dialog");
btn.put("dialog", mapOf(
"type", "dialog",
"title", "设置提醒人",
"size", "xl",
"body", form,
"actions", formActions()));
return btn;
}
private static Map<String, Object> scheduleJobNotifyTable() {
Map<String, Object> table = new LinkedHashMap<>();
table.put("type", "input-table");
table.put("name", "items");
table.put("label", false);
table.put("needConfirm", false);
table.put("addable", true);
table.put("removable", true);
table.put("copyable", false);
table.put("columns", List.of(
inputTableColumn("type", "基于", 140, mapOf(
"type", "select",
"name", "type",
"clearable", false,
"options", List.of(
mapOf("label", "用户", "value", "user"),
mapOf("label", "部门", "value", "depart"),
mapOf("label", "岗位", "value", "position"),
mapOf("label", "指定维度岗位类别负责人", "value", "fixedDimension"),
mapOf("label", "所属公司岗位类别", "value", "formSpecifiedDimension"),
mapOf("label", "基于项目角色", "value", "projectRoleType")))),
inputTableColumn("users", "用户", 280, notifyPicker("users",
"76d2f950-ef40-4eff-89ec-98ad9a4976b9"), "${type === 'user'}"),
inputTableColumn("departs", "部门", 280, notifyPicker("departs",
"138b7ca7-befb-4a0c-bfc6-ed8fb4d4e434"), "${type === 'depart'}"),
inputTableColumn("positions", "岗位", 280, notifyPicker("positions",
"feeee51d-d41b-410b-b7a4-67d61ec8c4df"), "${type === 'position'}"),
inputTableColumn("dimensionId", "维度", 180, mapOf(
"type", "select",
"name", "dimensionId",
"source", "/api/schedulejob/dimensions/options",
"clearable", true), "${type === 'fixedDimension'}"),
inputTableColumn("positionTypes", "岗位类别", 280, notifyPicker("positionTypes",
"8c19a765-047e-4a5c-8657-eb16c013ba65"),
"${type === 'fixedDimension' || type === 'formSpecifiedDimension'}"),
inputTableColumn("projectRoles", "项目角色", 260, mapOf(
"type", "checkboxes",
"name", "projectRoles",
"source", "/api/schedulejob/project-role-options"), "${type === 'projectRoleType'}"),
inputTableColumn("content", "原始内容", 220, mapOf(
"type", "input-text",
"name", "content",
"clearable", true),
"${type !== 'user' && type !== 'depart' && type !== 'position' "
+ "&& type !== 'fixedDimension' && type !== 'formSpecifiedDimension' "
+ "&& type !== 'projectRoleType'}"),
inputTableColumn("isSendMessage", "短消息", 80, mapOf(
"type", "checkbox",
"name", "isSendMessage")),
inputTableColumn("isSendMail", "邮件", 80, mapOf(
"type", "checkbox",
"name", "isSendMail")),
inputTableColumn("isSendPhone", "手机", 80, mapOf(
"type", "checkbox",
"name", "isSendPhone"))));
return table;
}
private static Map<String, Object> inputTableColumn(String name, String label, int width,
Map<String, Object> quickEdit) {
return inputTableColumn(name, label, width, quickEdit, null);
}
private static Map<String, Object> inputTableColumn(String name, String label, int width,
Map<String, Object> quickEdit, String visibleOn) {
Map<String, Object> col = new LinkedHashMap<>();
col.put("name", name);
col.put("label", label);
col.put("width", width);
col.put("quickEdit", quickEdit);
if (visibleOn != null && !visibleOn.isBlank()) {
col.put("visibleOn", visibleOn);
}
return col;
}
private static Map<String, Object> notifyPicker(String name, String dialogId) {
Map<String, Object> picker = new LinkedHashMap<>();
picker.put("type", "picker");
picker.put("name", name);
picker.put("multiple", true);
picker.put("joinValues", false);
picker.put("extractValue", false);
picker.put("valueField", "_id");
picker.put("labelField", "_label");
picker.put("source", "/api/picker/" + dialogId + "/list");
picker.put("modalMode", "dialog");
picker.put("overflowConfig", mapOf("maxTagCount", 1));
picker.put("pickerSchema", mapOf(
"mode", "table",
"filter", mapOf(
"title", "",
"body", List.of(mapOf(
"type", "input-text",
"name", "q",
"label", "关键字",
"clearable", true))),
"columns", List.of(mapOf("name", "_label", "label", "名称")),
"footerToolbar", List.of("pagination")));
return picker;
}
private static Map<String, Object> downloadButton(String label, String icon, String url) {
Map<String, Object> btn = new LinkedHashMap<>();
btn.put("type", "button");
btn.put("id", label);
btn.put("label", label);
btn.put("icon", icon);
if (!label.equals("下载基础数据")) {
btn.put("disabledOn", "${!selectedItems || selectedItems.length !== 1}");
}
btn.put("actionType", "download");
btn.put("api", mapOf("method", "get", "url", url));
return btn;
}
private static Map<String, Object> viewTemplateXmlButton(String pkField) { private static Map<String, Object> viewTemplateXmlButton(String pkField) {
return fieldEditorButton("高级配置", "fa fa-code", return fieldEditorButton("高级配置", "fa fa-code",
"VIEW_TEMPLATE", "VIEW_TEMPLATE_ID", pkField, "XML", "xml"); "VIEW_TEMPLATE", "VIEW_TEMPLATE_ID", pkField, "XML", "xml");

View File

@@ -1210,6 +1210,45 @@ class TemplateToAmisConverterTest {
assertTrue(labels.contains("编辑转换脚本")); assertTrue(labels.contains("编辑转换脚本"));
assertTrue(labels.contains("编辑保存脚本")); assertTrue(labels.contains("编辑保存脚本"));
assertTrue(labels.contains("下载模板"));
assertTrue(labels.contains("下载基础数据"));
Map<String, Object> download = toolbar.stream()
.filter(o -> o instanceof Map && "下载模板".equals(((Map<String, Object>) o).get("label")))
.map(o -> (Map<String, Object>) o).findFirst().orElseThrow();
assertEquals("download", download.get("actionType"));
Map<String, Object> api = (Map<String, Object>) download.get("api");
assertEquals("/api/dataimport/template?configId=${selectedItems[0].PM_DEMO_ID}", api.get("url"));
}
@Test
@SuppressWarnings("unchecked")
void engineclass_ScheduleJobSettingComponent_注入设置提醒人规则编辑器() {
String xml = "<crud entityid='e1'><display/></crud>";
ConversionResult r = converter.convertGraded(xml, null,
"com.dsasp.client.tools.schedulejob.ScheduleJobSettingComponent",
"设置定时任务", new ArrayList<>(), noPage);
Map<String, Object> crud = body(r.getSchema());
List<Object> toolbar = (List<Object>) crud.get("headerToolbar");
Map<String, Object> notify = toolbar.stream()
.filter(o -> o instanceof Map && "设置提醒人".equals(((Map<String, Object>) o).get("label")))
.map(o -> (Map<String, Object>) o).findFirst().orElseThrow();
assertEquals("dialog", notify.get("actionType"));
Map<String, Object> dialog = (Map<String, Object>) notify.get("dialog");
Map<String, Object> form = (Map<String, Object>) dialog.get("body");
assertEquals("/api/schedulejob/${selectedItems[0].PM_DEMO_ID}/notify",
((Map<String, Object>) form.get("initApi")).get("url"));
List<Object> body = (List<Object>) form.get("body");
Map<String, Object> table = (Map<String, Object>) body.get(0);
assertEquals("input-table", table.get("type"));
List<Map<String, Object>> columns = (List<Map<String, Object>>) table.get("columns");
assertTrue(columns.stream().anyMatch(c -> "users".equals(c.get("name"))));
Map<String, Object> userColumn = columns.stream()
.filter(c -> "users".equals(c.get("name"))).findFirst().orElseThrow();
Map<String, Object> quickEdit = (Map<String, Object>) userColumn.get("quickEdit");
assertEquals("picker", quickEdit.get("type"));
assertEquals("/api/picker/76d2f950-ef40-4eff-89ec-98ad9a4976b9/list", quickEdit.get("source"));
} }
/** engineclass=ProcessFormRemoveComponent → 审批表单删除注入查看和历史删除按钮。 */ /** engineclass=ProcessFormRemoveComponent → 审批表单删除注入查看和历史删除按钮。 */

View File

@@ -0,0 +1,315 @@
package com.eip4.platform.metadata.web;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
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.dataDic.bean.AbstractPOJOInfo;
import com.dsasp.server.common.dataDic.bean.DisplayType;
import com.dsasp.server.common.dataDic.bean.Enumerate;
import com.dsasp.server.common.dataDic.bean.EnumerateItem;
import com.dsasp.server.common.dataDic.bean.POJOInfo;
import com.eip4.platform.metadata.security.IdentifierWhitelist;
/**
* 数据导入配置自定义按钮端点。
*
* <p>旧 {@code DataImportConfigView} 的「下载模板 / 下载基础数据」只生成简单 Excel 表格。
* 这里用 SpreadsheetML 2003 生成可由 Excel/WPS 打开的 {@code .xls},避免为两个轻量按钮引入
* Apache POI 依赖。
*/
@RestController
@RequestMapping("/api/dataimport")
public class DataImportConfigController {
private final JdbcTemplate jdbcTemplate;
private final IdentifierWhitelist whitelist;
public DataImportConfigController(JdbcTemplate jdbcTemplate, IdentifierWhitelist whitelist) {
this.jdbcTemplate = jdbcTemplate;
this.whitelist = whitelist;
}
@GetMapping("/template")
public ResponseEntity<?> template(@RequestParam("configId") String configId) {
if (configId == null || configId.isBlank()) {
return fail(HttpStatus.BAD_REQUEST, "缺少数据导入配置主键");
}
try {
String entityId = jdbcTemplate.queryForObject(
"SELECT ENTITYID FROM SYS_DATAIMPORTCONFIG WHERE SYS_DATAIMPORTCONFIG_ID = ?",
String.class, configId);
if (entityId == null || entityId.isBlank()) {
return fail(HttpStatus.UNPROCESSABLE_ENTITY, "数据导入配置未选择实体");
}
String tableName = tableNameForEntity(entityId.trim());
if (tableName == null || tableName.isBlank()) {
return fail(HttpStatus.UNPROCESSABLE_ENTITY, "未找到配置实体");
}
whitelist.requireLegalTable(tableName);
POJOInfo info = poInfo(tableName);
if (info == null) {
return fail(HttpStatus.UNPROCESSABLE_ENTITY, "未找到实体元数据");
}
Sheet sheet = new Sheet(sheetName(info.getTableName()), templateRows(info));
return excel("data-import-template-" + safeFilePart(configId) + ".xls",
workbook(List.of(sheet)));
} catch (EmptyResultDataAccessException ex) {
return fail(HttpStatus.NOT_FOUND, "数据导入配置不存在或已删除");
}
}
@GetMapping("/basedata")
public ResponseEntity<?> baseData() {
List<Sheet> sheets = new ArrayList<>();
sheets.add(new Sheet("公司", companyRows()));
sheets.add(new Sheet("用户", userRows()));
sheets.add(new Sheet("部门", departRows()));
if (tableExists("pm_project")) {
sheets.add(new Sheet("工程", projectRows()));
}
return excel("data-import-base-data.xls", workbook(sheets));
}
String tableNameForEntity(String entityId) {
return AbstractPOJOInfo.getTableName(entityId);
}
POJOInfo poInfo(String tableName) {
return AbstractPOJOInfo.getPOInfo(tableName);
}
String enumerateHint(String enumerateType) {
if (enumerateType == null || enumerateType.isBlank()) {
return "";
}
List<EnumerateItem> items = Enumerate.getEnumerateItems(enumerateType);
if (items == null || items.isEmpty()) {
return "";
}
List<String> parts = new ArrayList<>();
for (EnumerateItem item : items) {
parts.add(item.getCodeValue() + ":" + item.getCodeDes());
}
return String.join(",", parts);
}
private List<List<Cell>> templateRows(POJOInfo info) {
List<Cell> names = new ArrayList<>();
List<Cell> labels = new ArrayList<>();
int count = info.getColumnCount();
for (int i = 0; i < count; i++) {
String type = info.getColumnDisplayType(i);
if (DisplayType.ID.equals(type) || DisplayType.List.equals(type)) {
continue;
}
String columnName = info.getColumnName(i);
if ("VERSION".equalsIgnoreCase(columnName) || "ISACTIVE".equalsIgnoreCase(columnName)) {
continue;
}
if (info.isVirtualColumn(i)) {
continue;
}
boolean required = info.isColumnMandatory(i);
names.add(new Cell(columnName, required));
labels.add(new Cell(columnLabel(info, i, type, columnName), required));
}
if (info.getColumnIndexByName("STATUS") > 0) {
for (int i = 0; i < 6; i++) {
boolean required = i == 0;
names.add(new Cell("WFUSER" + (i + 1), required));
labels.add(new Cell("审批人" + (i + 1), required));
names.add(new Cell("WFDATE" + (i + 1), required));
labels.add(new Cell("审批时间" + (i + 1), required));
}
}
return List.of(names, labels);
}
private String columnLabel(POJOInfo info, int index, String type, String columnName) {
String label = info.getColumnLabel(index);
if ("DOCUMENT".equalsIgnoreCase(columnName)) {
label = label + "(多个附件分号分隔,例如:附件1.doc;附件2.doc)";
}
if (DisplayType.YesNo.equals(type)) {
label = label + "(0:否,1:是)";
}
if (DisplayType.ENUMERATE.equals(type)) {
String hint = enumerateHint(info.getEnumerateType(columnName));
if (!hint.isBlank()) {
label = label + "(" + hint + ")";
}
}
return label;
}
private List<List<Cell>> companyRows() {
List<List<Cell>> rows = new ArrayList<>();
rows.add(row("公司名称"));
for (Map<String, Object> r : queryQuietly("SELECT NAME AS name FROM SYS_ORG ORDER BY PARENTID DESC, SEQ ASC")) {
rows.add(row(str(first(r, "name", "NAME"))));
}
return rows;
}
private List<List<Cell>> userRows() {
List<List<Cell>> rows = new ArrayList<>();
rows.add(row("用户名", "公司"));
String sql = "SELECT A.ACCOUNT || '(' || A.NAME || ')' AS user_name, B.NAME AS company "
+ "FROM SYS_USER A LEFT JOIN SYS_ORG B ON A.USERORGID = B.SYS_ORG_ID "
+ "WHERE A.STATE IN (1,2) ORDER BY A.ACCOUNT ASC";
for (Map<String, Object> r : queryQuietly(sql)) {
rows.add(row(str(first(r, "user_name", "USER_NAME")), str(first(r, "company", "COMPANY"))));
}
return rows;
}
private List<List<Cell>> departRows() {
List<List<Cell>> rows = new ArrayList<>();
rows.add(row("公司名称", "部门全称"));
if (!tableExists("view_depart_fullname")) {
return rows;
}
for (Map<String, Object> r : queryQuietly(
"SELECT ORGNAME AS orgname, DEPARTFULLNAME AS departfullname "
+ "FROM VIEW_DEPART_FULLNAME ORDER BY ORGNAME")) {
rows.add(row(str(first(r, "orgname", "ORGNAME")),
str(first(r, "departfullname", "DEPARTFULLNAME"))));
}
return rows;
}
private List<List<Cell>> projectRows() {
List<List<Cell>> rows = new ArrayList<>();
rows.add(row("工程名称", "公司"));
String sql = "SELECT A.PROJECTNAME AS projectname, B.NAME AS company "
+ "FROM PM_PROJECT A LEFT JOIN SYS_ORG B ON A.FILIALE = B.SYS_ORG_ID "
+ "WHERE A.PROJECTSTAGE >= 9 ORDER BY B.PARENTID DESC, B.SEQ ASC";
for (Map<String, Object> r : queryQuietly(sql)) {
rows.add(row(str(first(r, "projectname", "PROJECTNAME")),
str(first(r, "company", "COMPANY"))));
}
return rows;
}
private List<Map<String, Object>> queryQuietly(String sql) {
try {
return jdbcTemplate.queryForList(sql);
} catch (Exception ex) {
return List.of();
}
}
private boolean tableExists(String tableName) {
Boolean exists = jdbcTemplate.queryForObject("SELECT to_regclass(?) IS NOT NULL",
Boolean.class, tableName);
return Boolean.TRUE.equals(exists);
}
private ResponseEntity<byte[]> excel(String filename, String xml) {
byte[] body = xml.getBytes(StandardCharsets.UTF_8);
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType("application/vnd.ms-excel; charset=UTF-8"))
.contentLength(body.length)
.header(HttpHeaders.CONTENT_DISPOSITION,
ContentDisposition.attachment().filename(filename, StandardCharsets.UTF_8).build().toString())
.body(body);
}
private static ResponseEntity<Map<String, Object>> fail(HttpStatus status, String msg) {
Map<String, Object> body = new LinkedHashMap<>();
body.put("status", 1);
body.put("msg", msg);
return ResponseEntity.status(status).body(body);
}
private static String workbook(List<Sheet> sheets) {
StringBuilder sb = new StringBuilder();
sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
sb.append("<?mso-application progid=\"Excel.Sheet\"?>\n");
sb.append("<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\" ");
sb.append("xmlns:o=\"urn:schemas-microsoft-com:office:office\" ");
sb.append("xmlns:x=\"urn:schemas-microsoft-com:office:excel\" ");
sb.append("xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\">\n");
sb.append("<Styles><Style ss:ID=\"required\"><Font ss:Color=\"#FF0000\"/></Style></Styles>\n");
for (Sheet sheet : sheets) {
sb.append("<Worksheet ss:Name=\"").append(xml(sheetName(sheet.name()))).append("\"><Table>\n");
for (List<Cell> row : sheet.rows()) {
sb.append("<Row>");
for (Cell cell : row) {
sb.append("<Cell");
if (cell.required()) {
sb.append(" ss:StyleID=\"required\"");
}
sb.append("><Data ss:Type=\"String\">").append(xml(cell.value())).append("</Data></Cell>");
}
sb.append("</Row>\n");
}
sb.append("</Table></Worksheet>\n");
}
sb.append("</Workbook>");
return sb.toString();
}
private static List<Cell> row(String... cells) {
List<Cell> row = new ArrayList<>();
for (String cell : cells) {
row.add(new Cell(cell, false));
}
return row;
}
private static Object first(Map<String, Object> row, String... names) {
for (String name : names) {
if (row.containsKey(name)) {
return row.get(name);
}
}
return null;
}
private static String str(Object value) {
return value == null ? "" : String.valueOf(value);
}
private static String safeFilePart(String raw) {
return raw.replaceAll("[^A-Za-z0-9_.-]", "_");
}
private static String sheetName(String raw) {
String name = raw == null || raw.isBlank() ? "Sheet1" : raw.trim();
name = name.replaceAll("[\\\\/?*\\[\\]:]", "_");
return name.length() > 31 ? name.substring(0, 31) : name;
}
private static String xml(String raw) {
if (raw == null) {
return "";
}
return raw.replace("&", "&amp;")
.replace("<", "&lt;")
.replace(">", "&gt;")
.replace("\"", "&quot;");
}
private record Cell(String value, boolean required) {
}
private record Sheet(String name, List<List<Cell>> rows) {
}
}

View File

@@ -0,0 +1,397 @@
package com.eip4.platform.metadata.web;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
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.RestController;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* 定时任务「设置提醒人」保真端点。
*
* <p>旧 {@code ScheduleJobSettingComponent} 使用 {@code UserTable} 编辑
* {@code SYS_SCHEDULEJOB.SENDINFO},其存储格式为 {@code {"items":[...]}}。这里把它拆成
* amis input-table 可编辑的结构化行,再保存回旧 JSON 字符串。
*/
@RestController
@RequestMapping("/api/schedulejob")
public class ScheduleJobNotifyController {
private static final String TYPE_USER = "user";
private static final String TYPE_DEPART = "depart";
private static final String TYPE_POSITION = "position";
private static final String TYPE_FIXED_DIMENSION = "fixedDimension";
private static final String TYPE_FORM_SPECIFIED_DIMENSION = "formSpecifiedDimension";
private static final String TYPE_PROJECT_ROLE = "projectRoleType";
private static final String USER_PICKER = "76d2f950-ef40-4eff-89ec-98ad9a4976b9";
private static final String DEPART_PICKER = "138b7ca7-befb-4a0c-bfc6-ed8fb4d4e434";
private static final String POSITION_PICKER = "feeee51d-d41b-410b-b7a4-67d61ec8c4df";
private static final String POSITION_TYPE_PICKER = "8c19a765-047e-4a5c-8657-eb16c013ba65";
private final JdbcTemplate jdbcTemplate;
private final PickerController pickerController;
private final ObjectMapper objectMapper;
public ScheduleJobNotifyController(JdbcTemplate jdbcTemplate,
PickerController pickerController,
ObjectMapper objectMapper) {
this.jdbcTemplate = jdbcTemplate;
this.pickerController = pickerController;
this.objectMapper = objectMapper;
}
@GetMapping("/{id}/notify")
public Map<String, Object> load(@PathVariable String id) {
if (id == null || id.isBlank()) {
return fail("缺少定时任务主键");
}
try {
String sendInfo = jdbcTemplate.queryForObject(
"SELECT SENDINFO FROM SYS_SCHEDULEJOB WHERE SYS_SCHEDULEJOB_ID = ?",
String.class, id);
Map<String, Object> data = new LinkedHashMap<>();
data.put("items", parseItems(sendInfo));
Map<String, Object> resp = ok("加载成功");
resp.put("data", data);
return resp;
} catch (EmptyResultDataAccessException ex) {
return fail("定时任务不存在或已删除");
}
}
@PostMapping("/{id}/notify")
public Map<String, Object> save(@PathVariable String id, @RequestBody NotifySaveRequest req) {
if (id == null || id.isBlank()) {
return fail("缺少定时任务主键");
}
String sendInfo;
try {
sendInfo = serializeItems(req == null ? null : req.items);
} catch (JsonProcessingException ex) {
return fail("提醒人配置序列化失败: " + ex.getMessage());
}
int updated = jdbcTemplate.update(
"UPDATE SYS_SCHEDULEJOB SET SENDINFO = ? WHERE SYS_SCHEDULEJOB_ID = ?",
sendInfo, id);
if (updated <= 0) {
return fail("定时任务不存在或已删除");
}
return ok("保存成功");
}
@GetMapping("/dimensions/options")
public Map<String, Object> dimensions() {
List<Map<String, Object>> options = new ArrayList<>();
options.add(option("行政维度", "administrative"));
if (tableExists("sys_dimension")) {
List<Map<String, Object>> rows = jdbcTemplate.queryForList(
"SELECT SYS_DIMENSION_ID AS value, NAME AS label "
+ "FROM SYS_DIMENSION WHERE ISACTIVE = 1 ORDER BY SEQ, NAME");
for (Map<String, Object> row : rows) {
Object value = first(row, "value", "VALUE", "sys_dimension_id", "SYS_DIMENSION_ID");
Object label = first(row, "label", "LABEL", "name", "NAME");
if (value != null) {
options.add(option(label == null ? String.valueOf(value) : String.valueOf(label),
String.valueOf(value).trim()));
}
}
}
return ok(Map.of("options", options));
}
@GetMapping("/project-role-options")
public Map<String, Object> projectRoles() {
return ok(Map.of("options", projectRoleOptions()));
}
private List<Map<String, Object>> parseItems(String sendInfo) {
List<Map<String, Object>> rows = new ArrayList<>();
if (sendInfo == null || sendInfo.isBlank()) {
rows.add(defaultRow());
return rows;
}
try {
JsonNode root = objectMapper.readTree(sendInfo);
JsonNode items = root.path("items");
if (!items.isArray()) {
rows.add(defaultRow());
return rows;
}
for (JsonNode item : items) {
rows.add(expandItem(item));
}
} catch (Exception ex) {
Map<String, Object> row = defaultRow();
row.put("content", sendInfo);
rows.add(row);
}
if (rows.isEmpty()) {
rows.add(defaultRow());
}
return rows;
}
private Map<String, Object> expandItem(JsonNode item) {
String type = item.path("type").asText(TYPE_USER);
String content = item.path("content").asText("");
Map<String, Object> row = new LinkedHashMap<>();
row.put("type", type);
row.put("content", content);
row.put("isCandidate", item.path("isCandidate").asBoolean(true));
row.put("isSendMail", item.path("isSendMail").asBoolean(false));
row.put("isSendPhone", item.path("isSendPhone").asBoolean(false));
row.put("isSendMessage", item.path("isSendMessage").asBoolean(false));
switch (type) {
case TYPE_USER -> row.put("users", resolvePicker(USER_PICKER, content));
case TYPE_DEPART -> row.put("departs", resolvePicker(DEPART_PICKER, content));
case TYPE_POSITION -> row.put("positions", resolvePicker(POSITION_PICKER, content));
case TYPE_FIXED_DIMENSION -> {
List<String> parts = splitContent(content);
if (!parts.isEmpty()) {
row.put("dimensionId", parts.get(0));
if (parts.size() > 1) {
row.put("positionTypes", resolvePicker(POSITION_TYPE_PICKER,
String.join(",", parts.subList(1, parts.size()))));
}
}
}
case TYPE_FORM_SPECIFIED_DIMENSION -> row.put("positionTypes",
resolvePicker(POSITION_TYPE_PICKER, content));
case TYPE_PROJECT_ROLE -> row.put("projectRoles", selectedProjectRoleValues(content));
default -> row.put("content", content);
}
return row;
}
private String serializeItems(List<Map<String, Object>> rows) throws JsonProcessingException {
List<Map<String, Object>> items = new ArrayList<>();
if (rows != null) {
for (Map<String, Object> row : rows) {
if (row == null) {
continue;
}
Map<String, Object> item = new LinkedHashMap<>();
String type = stringValue(row.getOrDefault("type", TYPE_USER));
item.put("type", type.isBlank() ? TYPE_USER : type);
item.put("content", contentFor(type, row));
item.put("isCandidate", bool(row.get("isCandidate"), true));
item.put("isSendMail", bool(row.get("isSendMail"), false));
item.put("isSendPhone", bool(row.get("isSendPhone"), false));
item.put("isSendMessage", bool(row.get("isSendMessage"), false));
items.add(item);
}
}
if (items.isEmpty()) {
return "";
}
return objectMapper.writeValueAsString(Map.of("items", items));
}
private String contentFor(String type, Map<String, Object> row) {
return switch (type) {
case TYPE_USER -> joinedValues(row.get("users"));
case TYPE_DEPART -> joinedValues(row.get("departs"));
case TYPE_POSITION -> joinedValues(row.get("positions"));
case TYPE_FIXED_DIMENSION -> {
String dimension = stringValue(row.get("dimensionId"));
String positionTypes = joinedValues(row.get("positionTypes"));
if (dimension.isBlank()) {
yield positionTypes;
}
yield positionTypes.isBlank() ? dimension : dimension + "," + positionTypes;
}
case TYPE_FORM_SPECIFIED_DIMENSION -> joinedValues(row.get("positionTypes"));
case TYPE_PROJECT_ROLE -> projectRoleBooleanContent(row.get("projectRoles"));
default -> stringValue(row.get("content"));
};
}
private List<Map<String, Object>> resolvePicker(String dialogId, String content) {
if (content == null || content.isBlank()) {
return List.of();
}
List<Map<String, Object>> resolved = pickerController.resolveValuesToOptions(
dialogId, content, null, null, null, null, "_label", "_id");
for (Map<String, Object> item : resolved) {
item.put("label", item.get("_label"));
item.put("value", item.get("_id"));
}
return resolved;
}
private List<String> selectedProjectRoleValues(String content) {
List<String> flags = splitContent(content);
List<Map<String, Object>> options = projectRoleOptions();
List<String> selected = new ArrayList<>();
for (int i = 0; i < flags.size() && i < options.size(); i++) {
if (Boolean.parseBoolean(flags.get(i))) {
selected.add(String.valueOf(options.get(i).get("value")));
}
}
return selected;
}
private String projectRoleBooleanContent(Object selectedObj) {
Set<String> selected = new HashSet<>(values(selectedObj));
List<String> flags = new ArrayList<>();
for (Map<String, Object> option : projectRoleOptions()) {
flags.add(Boolean.toString(selected.contains(String.valueOf(option.get("value")))));
}
return String.join(",", flags);
}
private List<Map<String, Object>> projectRoleOptions() {
if (!tableExists("sys_enumerate")) {
return List.of();
}
List<Map<String, Object>> rows = jdbcTemplate.queryForList(
"SELECT CODEVALUE AS value, CODEDES AS label FROM SYS_ENUMERATE "
+ "WHERE UPPER(SYS_ENUMERATETYPE_ID) = 'PM_PROJECTMANAGERROLE' AND ISACTIVE = 1 "
+ "ORDER BY ORDERASC, CODEDES");
List<Map<String, Object>> options = new ArrayList<>();
for (Map<String, Object> row : rows) {
Object value = first(row, "value", "VALUE", "codevalue", "CODEVALUE");
Object label = first(row, "label", "LABEL", "codedes", "CODEDES");
if (value != null) {
options.add(option(label == null ? String.valueOf(value) : String.valueOf(label),
String.valueOf(value)));
}
}
return options;
}
private boolean tableExists(String tableName) {
Boolean exists = jdbcTemplate.queryForObject("SELECT to_regclass(?) IS NOT NULL",
Boolean.class, tableName);
return Boolean.TRUE.equals(exists);
}
private static Map<String, Object> defaultRow() {
Map<String, Object> row = new LinkedHashMap<>();
row.put("type", TYPE_USER);
row.put("users", List.of());
row.put("isCandidate", true);
row.put("isSendMail", false);
row.put("isSendPhone", false);
row.put("isSendMessage", false);
return row;
}
private static List<String> splitContent(String content) {
if (content == null || content.isBlank()) {
return List.of();
}
List<String> parts = new ArrayList<>();
for (String p : content.split(",")) {
String v = p == null ? "" : p.trim();
if (!v.isBlank() && !"null".equalsIgnoreCase(v)) {
parts.add(v);
}
}
return parts;
}
private static String joinedValues(Object value) {
return String.join(",", values(value));
}
@SuppressWarnings("unchecked")
private static List<String> values(Object value) {
if (value == null) {
return List.of();
}
List<String> out = new ArrayList<>();
if (value instanceof Iterable<?> list) {
for (Object one : list) {
addValue(out, one);
}
} else {
addValue(out, value);
}
return out;
}
@SuppressWarnings("unchecked")
private static void addValue(List<String> out, Object one) {
if (one instanceof Map<?, ?> map) {
Object id = first((Map<String, Object>) map, "_id", "value", "id");
if (id != null && !String.valueOf(id).isBlank()) {
out.add(String.valueOf(id).trim());
}
return;
}
String str = stringValue(one);
if (!str.isBlank()) {
out.add(str);
}
}
private static boolean bool(Object value, boolean defaultValue) {
if (value == null) {
return defaultValue;
}
if (value instanceof Boolean b) {
return b;
}
return Boolean.parseBoolean(String.valueOf(value));
}
private static String stringValue(Object value) {
return value == null ? "" : String.valueOf(value).trim();
}
private static Object first(Map<String, Object> row, String... names) {
for (String name : names) {
if (row.containsKey(name)) {
return row.get(name);
}
}
return null;
}
private static Map<String, Object> option(String label, String value) {
Map<String, Object> option = new LinkedHashMap<>();
option.put("label", label);
option.put("value", value);
return option;
}
private static Map<String, Object> ok(String msg) {
Map<String, Object> resp = new LinkedHashMap<>();
resp.put("status", 0);
resp.put("msg", msg);
return resp;
}
private static Map<String, Object> ok(Map<String, Object> data) {
Map<String, Object> resp = ok("");
resp.put("data", data);
return resp;
}
private static Map<String, Object> fail(String msg) {
Map<String, Object> resp = new LinkedHashMap<>();
resp.put("status", 1);
resp.put("msg", msg);
return resp;
}
public static class NotifySaveRequest {
public List<Map<String, Object>> items;
}
}

View File

@@ -0,0 +1,67 @@
package com.eip4.platform.metadata.web;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.nio.charset.StandardCharsets;
import org.junit.jupiter.api.Test;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import com.dsasp.server.common.dataDic.bean.DisplayType;
import com.dsasp.server.common.dataDic.bean.POJOInfo;
import com.eip4.platform.metadata.security.IdentifierWhitelist;
/** 数据导入配置下载端点单测。 */
class DataImportConfigControllerTest {
private final JdbcTemplate jdbcTemplate = mock(JdbcTemplate.class);
private final IdentifierWhitelist whitelist = mock(IdentifierWhitelist.class);
@Test
void template_按实体元数据生成spreadsheetXml并跳过系统列() {
POJOInfo info = mock(POJOInfo.class);
when(info.getTableName()).thenReturn("OA_DEMO");
when(info.getColumnCount()).thenReturn(4);
when(info.getColumnDisplayType(0)).thenReturn(DisplayType.String);
when(info.getColumnName(0)).thenReturn("NAME");
when(info.getColumnLabel(0)).thenReturn("名称");
when(info.isColumnMandatory(0)).thenReturn(true);
when(info.getColumnDisplayType(1)).thenReturn(DisplayType.YesNo);
when(info.getColumnName(1)).thenReturn("ENABLED");
when(info.getColumnLabel(1)).thenReturn("启用");
when(info.getColumnDisplayType(2)).thenReturn(DisplayType.String);
when(info.getColumnName(2)).thenReturn("ISACTIVE");
when(info.getColumnDisplayType(3)).thenReturn(DisplayType.ID);
when(info.getColumnName(3)).thenReturn("OA_DEMO_ID");
when(info.getColumnIndexByName("STATUS")).thenReturn(-1);
when(jdbcTemplate.queryForObject(
eq("SELECT ENTITYID FROM SYS_DATAIMPORTCONFIG WHERE SYS_DATAIMPORTCONFIG_ID = ?"),
eq(String.class), eq("CFG1"))).thenReturn("ENTITY1");
DataImportConfigController controller = new DataImportConfigController(jdbcTemplate, whitelist) {
@Override
String tableNameForEntity(String entityId) {
return "OA_DEMO";
}
@Override
POJOInfo poInfo(String tableName) {
return info;
}
};
ResponseEntity<?> resp = controller.template("CFG1");
assertThat(resp.getStatusCode().is2xxSuccessful()).isTrue();
String body = new String((byte[]) resp.getBody(), StandardCharsets.UTF_8);
assertThat(body).contains("<Workbook").contains("NAME").contains("名称")
.contains("启用(0:否,1:是)")
.doesNotContain("ISACTIVE")
.doesNotContain("OA_DEMO_ID");
verify(whitelist).requireLegalTable("OA_DEMO");
}
}

View File

@@ -0,0 +1,75 @@
package com.eip4.platform.metadata.web;
import static org.assertj.core.api.Assertions.assertThat;
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.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.springframework.jdbc.core.JdbcTemplate;
import com.fasterxml.jackson.databind.ObjectMapper;
/** 定时任务提醒人 SENDINFO 结构化编辑端点单测。 */
class ScheduleJobNotifyControllerTest {
private final JdbcTemplate jdbcTemplate = mock(JdbcTemplate.class);
private final PickerController pickerController = mock(PickerController.class);
private final ScheduleJobNotifyController controller =
new ScheduleJobNotifyController(jdbcTemplate, pickerController, new ObjectMapper());
@Test
@SuppressWarnings("unchecked")
void load_把旧sendinfo解析成标准picker默认值() {
when(jdbcTemplate.queryForObject(
eq("SELECT SENDINFO FROM SYS_SCHEDULEJOB WHERE SYS_SCHEDULEJOB_ID = ?"),
eq(String.class), eq("JOB1")))
.thenReturn("{\"items\":[{\"type\":\"user\",\"content\":\"U1,U2\","
+ "\"isCandidate\":true,\"isSendMail\":false,"
+ "\"isSendPhone\":true,\"isSendMessage\":true}]}");
when(pickerController.resolveValuesToOptions(eq("76d2f950-ef40-4eff-89ec-98ad9a4976b9"),
eq("U1,U2"), any(), any(), any(), any(), eq("_label"), eq("_id")))
.thenReturn(List.of(option("张三[000001]", "U1"), option("李四[000002]", "U2")));
Map<String, Object> resp = controller.load("JOB1");
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(items).hasSize(1);
assertThat(items.get(0)).containsEntry("type", "user")
.containsEntry("isSendPhone", true)
.containsEntry("isSendMessage", true);
assertThat((List<Map<String, Object>>) items.get(0).get("users"))
.extracting(v -> v.get("_label"))
.containsExactly("张三[000001]", "李四[000002]");
}
@Test
void save_把picker对象数组序列化回旧sendinfo() {
when(jdbcTemplate.update(
eq("UPDATE SYS_SCHEDULEJOB SET SENDINFO = ? WHERE SYS_SCHEDULEJOB_ID = ?"),
any(), eq("JOB1"))).thenReturn(1);
ScheduleJobNotifyController.NotifySaveRequest req = new ScheduleJobNotifyController.NotifySaveRequest();
req.items = List.of(Map.of(
"type", "user",
"users", List.of(Map.of("_id", "U1", "_label", "张三"), Map.of("_id", "U2", "_label", "李四")),
"isSendMessage", true));
Map<String, Object> resp = controller.save("JOB1", req);
assertThat(resp).containsEntry("status", 0);
}
private static Map<String, Object> option(String label, String value) {
Map<String, Object> item = new LinkedHashMap<>();
item.put("_label", label);
item.put("_id", value);
return item;
}
}