修改问题、添加监管数据报送模块

这个提交包含在:
apple
2026-11-24 16:05:24 +08:00
父节点 fb47c07f7c
当前提交 c5760c74eb
共修改 74 个文件,包含 2631 行新增和 41 行删除
+16
查看文件
@@ -8,6 +8,22 @@
target/
!.mvn/wrapper/maven-wrapper.jar
# Generated packages and build outputs (existing tracked dependencies stay tracked).
dist/
node_modules/
coverage/
*.class
*.jar
*.war
*.ear
*.zip
*.tar
*.tar.gz
*.tgz
/deliverables/
!.mvn/wrapper/maven-wrapper.jar
!gradle/wrapper/gradle-wrapper.jar
######################################################################
# IDE
@@ -28,10 +28,19 @@ public final class UnifiedIngestionApi {
public record SourceSelection(long sourceId, long sourceVersion, String sourceName,
String sourceDatabase, String table) { }
public record DraftRequest(List<SourceSelection> items, StorageResourceType targetType) { }
public record FieldCompatibility(String field, String nativeType, String conversion, String error) { }
public record DraftItem(long sourceId, long sourceVersion, String sourceName, String sourceDatabase,
String sourceTable, String targetTable, String sourceFingerprint,
List<ColumnDefinition> columns, List<BatchFieldMappingCommand> mappings,
String errorSummary, String sourceTableComment, String sourceTableCommentState) {
String errorSummary, String sourceTableComment, String sourceTableCommentState,
List<FieldCompatibility> fieldCompatibility) {
public DraftItem(long sourceId, long sourceVersion, String sourceName, String sourceDatabase,
String sourceTable, String targetTable, String sourceFingerprint,
List<ColumnDefinition> columns, List<BatchFieldMappingCommand> mappings, String errorSummary,
String sourceTableComment, String sourceTableCommentState) {
this(sourceId, sourceVersion, sourceName, sourceDatabase, sourceTable, targetTable, sourceFingerprint,
columns, mappings, errorSummary, sourceTableComment, sourceTableCommentState, List.of());
}
public DraftItem(long sourceId, long sourceVersion, String sourceName, String sourceDatabase,
String sourceTable, String targetTable, String sourceFingerprint,
List<ColumnDefinition> columns, List<BatchFieldMappingCommand> mappings, String errorSummary) {
@@ -0,0 +1,88 @@
package cn.aixunkeji.datagov.integration.api.datasource;
import java.util.Locale;
import java.util.Set;
import static cn.aixunkeji.datagov.integration.api.datasource.DataSourceObjects.*;
/** Explicit value-preserving carriers for types without a common Hive/Doris scalar type.
* Native metadata is retained in the execution snapshot; this never casts to a bounded string.
*/
public final class BatchTextTypes {
private BatchTextTypes() { }
public record Carrier(String expression, boolean binary, String description) { }
public static Carrier carrier(Column c, String identifier) {
if (c == null) return null;
String raw = c.nativeType() == null ? c.type() : c.nativeType();
if (raw == null) return null;
raw = raw.toUpperCase(Locale.ROOT).trim();
String dialect = raw.contains(":") ? raw.substring(0, raw.indexOf(':')) : "MYSQL";
String type = raw.contains(":") ? raw.substring(raw.indexOf(':') + 1) : raw;
String base = type.replaceAll("\\([^)]*\\)", "").replace(" UNSIGNED", "").trim().replaceAll("\\s+", " ");
String x = identifier;
if (dialect.equals("MYSQL")) {
if (Set.of("TINYTEXT", "TEXT", "MEDIUMTEXT", "LONGTEXT", "STRING").contains(base)) return text(x, "文本完整保存");
if (Set.of("BINARY", "VARBINARY", "TINYBLOB", "BLOB", "MEDIUMBLOB", "LONGBLOB").contains(base)) return text("HEX("+x+")", "二进制保存为十六进制,可逆还原");
if (Set.of("GEOMETRY", "POINT", "LINESTRING", "POLYGON", "MULTIPOINT", "MULTILINESTRING", "MULTIPOLYGON", "GEOMETRYCOLLECTION", "GEOMCOLLECTION").contains(base))
return text("HEX("+x+")", "空间数据保存为含SRID的MySQL内部二进制十六进制");
if (Set.of("JSON", "ENUM", "SET", "TIME").contains(base) || wideDecimal(base,c,type))
return text("CAST("+x+" AS CHAR CHARACTER SET utf8mb4)", "原始值以文本保存,不保留源类型约束");
if (base.equals("BIT") && !Integer.valueOf(1).equals(dimension(c,type)))
return text("CAST(CAST("+x+" AS UNSIGNED) AS CHAR)", "位值保存为无符号十进制文本,位宽保留在源结构");
} else if (dialect.equals("SQLSERVER")) {
if (Set.of("TEXT", "NTEXT", "XML").contains(base) ||
Set.of("VARCHAR", "NVARCHAR").contains(base) && (type.contains("MAX") || c.precision()!=null && c.precision()>65535))
return text("CONVERT(nvarchar(max),"+x+")", "文本/XML完整保存");
if (base.equals("IMAGE") || base.equals("VARBINARY") && (type.contains("MAX") || c.precision()==null || c.precision()>8000))
return text("CONVERT(varchar(max),"+x+",2)", "二进制保存为十六进制,可逆还原");
if (Set.of("GEOMETRY", "GEOGRAPHY").contains(base))
return text("CONVERT(varchar(max),"+x+".Serialize(),2)", "空间对象完整序列化为十六进制(含SRID)");
if (base.equals("HIERARCHYID")) return text(x+".ToString()", "层级路径保存为文本");
} else if (dialect.equals("ORACLE") || dialect.equals("DAMENG")) {
if (Set.of("CLOB", "NCLOB", "TEXT", "LONG", "LONGVARCHAR").contains(base)) return text(x, "大文本完整保存");
if (Set.of("BLOB", "LONG RAW", "LONGVARBINARY").contains(base)) return binary(x);
if (dialect.equals("ORACLE") && base.equals("RAW")) return text("RAWTOHEX("+x+")", "二进制保存为十六进制,可逆还原");
if (dialect.equals("DAMENG") && Set.of("BINARY", "VARBINARY", "RAW").contains(base) &&
(c.precision()==null || c.precision()>16383)) return binary(x);
if (Set.of("NUMBER", "NUMERIC", "DECIMAL").contains(base) &&
(c.precision()==null || c.precision()<1 || c.precision()>38 || c.scale()==null || c.scale()<0 || c.scale()>c.precision()))
return text("TO_CHAR("+x+",'TM9','NLS_NUMERIC_CHARACTERS=''.,''')", "数值保存为完整精度文本");
if (base.startsWith("TIMESTAMP") && (base.contains("TIME ZONE") || c.scale()==null || c.scale()>6)) {
String format = "YYYY-MM-DD\"T\"HH24:MI:SS.FF9"+(base.contains("TIME ZONE") ? " TZH:TZM" : "");
return text("TO_CHAR("+x+",'"+format+"')", "时间保存为含小数秒/时区的文本");
}
if (base.startsWith("INTERVAL")) return text("TO_CHAR("+x+")", "时间间隔保存为文本");
if (Set.of("ROWID", "UROWID").contains(base)) return text("TO_CHAR("+x+")", "行标识保存为文本");
if (base.equals("XMLTYPE")) return text("XMLSERIALIZE(CONTENT "+x+" AS CLOB)", "XML完整保存");
if (base.equals("JSON")) return text("JSON_SERIALIZE("+x+" RETURNING CLOB)", "JSON完整保存为文本");
if (dialect.equals("DAMENG") && base.equals("DATE")) return text("TO_CHAR("+x+",'YYYY-MM-DD HH24:MI:SS')", "日期时间保存为文本,保留兼容模式下的时分秒");
if (dialect.equals("DAMENG") && (base.equals("TIME") || base.startsWith("TIME "))) return text("CAST("+x+" AS VARCHAR(64))", "时间保存为完整精度文本");
} else if (dialect.equals("KINGBASE")) {
if (Set.of("VARCHAR", "CHARACTER VARYING", "CHAR", "BPCHAR").contains(base) &&
(c.precision()==null || c.precision()<1 || c.precision()>65535))
return text("CAST("+x+" AS TEXT)", "无界或大容量字符字段完整保存为文本");
if (Set.of("BYTEA", "BLOB", "RAW", "BINARY", "VARBINARY").contains(base)) return binary(x);
if (Set.of("TEXT", "CLOB", "NCLOB", "JSON", "JSONB", "XML", "UUID", "BOOL", "BOOLEAN", "REAL", "FLOAT4", "FLOAT8", "DOUBLE PRECISION", "FLOAT", "TIMESTAMP", "TIMESTAMPTZ", "TIMESTAMP WITHOUT TIME ZONE", "TIMESTAMP WITH TIME ZONE", "TIME", "TIMETZ", "TIME WITHOUT TIME ZONE", "TIME WITH TIME ZONE", "INTERVAL", "MONEY", "INET", "CIDR", "MACADDR", "MACADDR8", "BIT", "VARBIT", "BIT VARYING", "POINT", "LINE", "LSEG", "BOX", "PATH", "POLYGON", "CIRCLE", "TSVECTOR", "TSQUERY", "INT4RANGE", "INT8RANGE", "NUMRANGE", "TSRANGE", "TSTZRANGE", "DATERANGE").contains(base) ||
base.startsWith("_") || base.endsWith("[]") ||
Set.of("NUMERIC", "DECIMAL", "NUMBER").contains(base) && (c.precision()==null || c.precision()<1 || c.precision()>38 || c.scale()==null || c.scale()<0 || c.scale()>c.precision()))
return text("CAST("+x+" AS TEXT)", "使用数据库完整文本表示,保留值及精度");
}
return null;
}
private static Integer dimension(Column c, String type) {
var m=java.util.regex.Pattern.compile("^[A-Z]+\\(([0-9]+)").matcher(type);
return m.find() ? Integer.valueOf(m.group(1)) : c.precision();
}
private static boolean wideDecimal(String base, Column c, String type) {
if (!Set.of("DECIMAL", "NUMERIC").contains(base)) return false;
Integer p=dimension(c,type);
return p!=null && p>38 && p<=65;
}
private static Carrier text(String expression, String description) { return new Carrier(expression,false,description); }
private static Carrier binary(String expression) { return new Carrier(expression,true,"二进制通过采集引擎完整编码为十六进制,可逆还原"); }
public static MysqlTargetType mapping(Column c, TargetEngine engine) {
Carrier carrier=carrier(c,"field");
return carrier==null ? null : new MysqlTargetType(c.name(),c.nativeType()==null?c.type():c.nativeType(),engine,true,"STRING","string",null,null);
}
}
@@ -97,6 +97,10 @@ public final class DataSourceObjects {
String errorCode, String errorSummary) implements java.io.Serializable { }
public static MysqlTargetType mysqlTargetType(Column column, TargetEngine engine) {
if (column != null && engine != null && column.name() != null && !column.name().isBlank()) {
MysqlTargetType text = BatchTextTypes.mapping(column, engine);
if (text != null) return text;
}
if (column != null && engine != null && column.nativeType() != null &&
column.nativeType().startsWith(KingbaseBatchTypes.PREFIX)) {
return KingbaseBatchTypes.targetType(column, engine);
@@ -211,9 +211,18 @@ public class UnifiedIngestionService {
try {
verifySource(actor, item.sourceId(), item.sourceVersion(), item.sourceName(), item.sourceDatabase());
var schema = schema(actor, item.sourceId(), item.sourceDatabase(), item.table());
List<ColumnDefinition> columns = schema.columns().stream()
List<FieldCompatibility> compatibility = new ArrayList<>();
List<Column> supported = new ArrayList<>();
for (Column column : schema.columns()) {
var mapped = cn.aixunkeji.datagov.integration.api.datasource.DataSourceObjects.mysqlTargetType(column, targetEngine);
var carrier = cn.aixunkeji.datagov.integration.api.datasource.BatchTextTypes.carrier(column, "field");
compatibility.add(new FieldCompatibility(column.name(), column.nativeType() == null ? column.type() : column.nativeType(),
carrier == null ? "按目标类型保存" : carrier.description(), mapped.supported() ? null : mapped.errorSummary()));
if (mapped.supported()) supported.add(column);
}
List<ColumnDefinition> columns = supported.stream()
.map(column -> BatchTargetTypePolicy.propose(column, targetEngine)).toList();
List<BatchFieldMappingCommand> mappings = BatchTargetWizardService.matchColumns(schema.columns(),
List<BatchFieldMappingCommand> mappings = BatchTargetWizardService.matchColumns(supported,
new cn.aixunkeji.datagov.integration.api.tablefile.TableFileIntegrationService.DirectoryResult(
cn.aixunkeji.datagov.integration.api.tablefile.TableFileIntegrationService.State.CONFIRMED,
List.of(item.table()), columns.stream().map(UnifiedIngestionService::directoryColumn).toList(), 1, null),
@@ -222,7 +231,7 @@ public class UnifiedIngestionService {
items.add(new DraftItem(item.sourceId(), item.sourceVersion(), item.sourceName(), item.sourceDatabase(),
item.table(), target, fingerprint(item.sourceId(), item.sourceDatabase(), item.table(),
schema.columns(), schema.tableComment()), columns, mappings, null,
schema.tableComment().value(), schema.tableComment().state().name()));
schema.tableComment().value(), schema.tableComment().state().name(), List.copyOf(compatibility)));
} catch (RuntimeException exception) {
items.add(new DraftItem(item.sourceId(), item.sourceVersion(), item.sourceName(), item.sourceDatabase(),
item.table(), item.table().replace('.', '_').toLowerCase(Locale.ROOT), null, List.of(), List.of(),
@@ -80,7 +80,7 @@ class BatchTargetTypePolicyTest {
assertThat(BatchTargetWizardService.matchColumns(List.of(source("TEXT",65535,0,65535L,true)),directory).getFirst().targetType()).isEqualTo("STRING");
}
assertThat(BatchTargetTypePolicy.propose(source("BIT",1,0,null,false)).type()).isEqualTo(ColumnType.BOOLEAN);
assertThatThrownBy(()->BatchTargetTypePolicy.propose(source("BIT",8,0,null,false))).isInstanceOf(BatchIngestionException.class);
assertThat(BatchTargetTypePolicy.propose(source("BIT",8,0,null,false)).type()).isEqualTo(ColumnType.STRING);
assertThatThrownBy(()->BatchTargetTypePolicy.requireFits(target(ColumnType.VARCHAR,400,null,true),target(ColumnType.VARCHAR,399,null,true)))
.hasMessageContaining("value").hasMessageContaining("VARCHAR(400)").hasMessageContaining("VARCHAR(399)").hasMessageContaining("字节长度不足");
assertThatThrownBy(()->BatchTargetTypePolicy.requireFits(target(ColumnType.DECIMAL,20,6,true),target(ColumnType.DECIMAL,20,8,true))).hasMessageContaining("整数位或小数位容量不足");
@@ -128,15 +128,15 @@ class BatchTargetTypePolicyTest {
assertThat(BatchTargetTypePolicy.propose(utf8, TargetEngine.DORIS).type()).isEqualTo(ColumnType.STRING);
assertThatThrownBy(() -> BatchTargetTypePolicy.propose(source("DECIMAL",null,null,null,true), TargetEngine.HIVE))
.hasMessageContaining("DECIMAL精度未知");
assertThatThrownBy(() -> BatchTargetTypePolicy.propose(source("JSON",null,null,null,true), TargetEngine.DORIS))
.hasMessageContaining("value").hasMessageContaining("JSON");
assertThat(BatchTargetTypePolicy.propose(source("JSON",null,null,null,true), TargetEngine.DORIS).type()).isEqualTo(ColumnType.STRING);
}
@Test void decimalRequiresBothIntegralAndFractionalCapacity() {
var input=BatchTargetTypePolicy.propose(source("DECIMAL",20,6,null,true));
assertThat(BatchTargetTypePolicy.fits(input,target(ColumnType.DECIMAL,22,8,true))).isTrue();
assertThat(BatchTargetTypePolicy.fits(input,target(ColumnType.DECIMAL,20,8,true))).isFalse();
assertThat(BatchTargetTypePolicy.fits(input,target(ColumnType.DECIMAL,22,5,true))).isFalse();
for(int precision:List.of(0,39,65)) assertThatThrownBy(() -> BatchTargetTypePolicy.propose(source("DECIMAL",precision,0,null,true))).isInstanceOf(BatchIngestionException.class);
for(int precision:List.of(0,66)) assertThatThrownBy(() -> BatchTargetTypePolicy.propose(source("DECIMAL",precision,0,null,true))).isInstanceOf(BatchIngestionException.class);
for(int precision:List.of(39,65)) assertThat(BatchTargetTypePolicy.propose(source("DECIMAL",precision,0,null,true)).type()).isEqualTo(ColumnType.STRING);
assertThat(BatchTargetTypePolicy.fits(input,target(ColumnType.DECIMAL,38,39,true))).isFalse();
}
@Test void narrowingNullabilityUnknownAndFractionalTimeFailClosed() {
@@ -144,7 +144,7 @@ class BatchTargetTypePolicyTest {
assertThat(BatchTargetTypePolicy.fits(input,target(ColumnType.BIGINT,null,null,false))).isFalse();
assertThat(BatchTargetTypePolicy.fits(input,target(ColumnType.INT,null,null,true))).isFalse();
for(String type:List.of("BLOB","JSON","MEDIUMTEXT","LONGTEXT","TIME","GEOMETRY"))
assertThatThrownBy(() -> BatchTargetTypePolicy.propose(source(type,100,0,null,true))).isInstanceOf(BatchIngestionException.class);
assertThat(BatchTargetTypePolicy.propose(source(type,100,0,null,true)).type()).isEqualTo(ColumnType.STRING);
for(Integer scale:java.util.Arrays.asList(null,-1,7))
assertThatThrownBy(() -> BatchTargetTypePolicy.propose(source("DATETIME",26,scale,null,true))).isInstanceOf(BatchIngestionException.class);
assertThat(BatchTargetTypePolicy.propose(source("TIMESTAMP",19,0,null,false)).type()).isEqualTo(ColumnType.DATETIME);
@@ -0,0 +1,39 @@
package cn.aixunkeji.datagov.dataops.batchingestion;
import java.util.List;
import org.junit.jupiter.api.Test;
import cn.aixunkeji.datagov.integration.api.datasource.DataSourceObjects.*;
import cn.aixunkeji.datagov.integration.api.tablefile.UnifiedIngestionSourceService.SchemaResult;
import cn.aixunkeji.datagov.dataops.api.storage.StorageResourceType;
import static org.mockito.Mockito.*;
import static org.assertj.core.api.Assertions.*;
class UnifiedIngestionTypeCompatibilityTest {
@Test void longtextNoLongerErasesTableAndUnknownFieldRemainsExplicit() {
var f=new UnifiedIngestionRecoveryTest.CommentFixture(null);
var text=new Column("award_name","LONGVARCHAR",2,true,false,"LONGTEXT",Integer.MAX_VALUE,null,4294967295L,null,SourceColumnComment.fromSource(null));
var unknown=new Column("special","OTHER",3,true,false,"CUSTOM_OBJECT",null,null,null,null,SourceColumnComment.fromSource(null));
when(f.sources.schema(1,2,3,"source_db","orders")).thenReturn(new SchemaResult("AVAILABLE",List.of(f.column,text,unknown),null,f.tableComment));
for (var target:List.of(StorageResourceType.HIVE,StorageResourceType.DORIS)) {
var draft=f.draft(target).items().getFirst();
assertThat(draft.errorSummary()).isNull();
assertThat(draft.columns()).extracting(c->c.name()).containsExactly("id","award_name");
assertThat(draft.mappings()).hasSize(2);
assertThat(draft.fieldCompatibility()).hasSize(3);
assertThat(draft.fieldCompatibility().get(1).nativeType()).isEqualTo("LONGTEXT");
assertThat(draft.fieldCompatibility().get(2).error()).contains("special");
assertThat(draft.sourceFingerprint()).isNotBlank();
var selected=UnifiedIngestionService.selectedFields(List.of(f.column,text,unknown),f.item(draft,true),target);
assertThat(selected.sourceColumns()).hasSize(2);
}
verifyNoInteractions(f.tables,f.collections);
}
@Test void allUnknownColumnsStillReturnFieldReasonsAndCannotSubmitEmptyMapping() {
var f=new UnifiedIngestionRecoveryTest.CommentFixture(null);
f.column=new Column("special","OTHER",1,true,false,"CUSTOM_OBJECT",null,null,null);
var draft=f.draft(StorageResourceType.DORIS).items().getFirst();
assertThat(draft.columns()).isEmpty();
assertThat(draft.fieldCompatibility()).singleElement().satisfies(x->assertThat(x.error()).isNotBlank());
assertThatThrownBy(()->UnifiedIngestionService.selectedFields(List.of(f.column),f.item(draft,true),StorageResourceType.DORIS)).isInstanceOf(BatchIngestionException.class);
}
}
@@ -117,6 +117,10 @@ final class M3CollectionJobFactory {
}
MysqlTargetType mapped = normalizedType(field, target.resourceType());
if (!mapped.supported()) return Capability.unsupported(mapped.errorCode(), mapped.errorSummary());
var carrier = textCarrier(field, "field");
if (carrier != null && carrier.binary() && (!"NONE".equals(field.transform()) ||
field.filterOperator() != null && !Set.of("IS_NULL", "IS_NOT_NULL").contains(field.filterOperator())))
return Capability.unsupported("BATCH_BINARY_TRANSFORM_UNSUPPORTED", "二进制大对象支持完整采集和空值过滤;文本转换及内容过滤请使用源视图");
if (!sameDeclaration(mapped.targetType(), field.targetType()) || !validBatchTransform(field, mapped)) {
return Capability.unsupported("MYSQL_TARGET_TYPE_MISMATCH",
"字段“" + field.sourceField() + "”的目标类型与规范化" + target.resourceType() + "映射不一致");
@@ -169,15 +173,31 @@ final class M3CollectionJobFactory {
input.put("decimal_type_narrowing", false);
input.put("query", selectSql(snapshot, sqlServer, oracle || dameng || kingbase, source.databaseName()));
ObjectNode fields = input.putObject("schema").putObject("fields");
boolean binaryEncoding = snapshot.mappings().stream().anyMatch(f -> textCarrier(f, "field") != null && textCarrier(f, "field").binary());
for (BatchFieldExecution field : snapshot.mappings()) {
MysqlTargetType mapped = normalizedType(field, target.resourceType());
if (!mapped.supported() || !sameDeclaration(mapped.targetType(), field.targetType())) {
throw new IllegalArgumentException("MYSQL_TARGET_TYPE_MISMATCH");
}
fields.put(field.targetField(), mapped.seaTunnelType());
var carrier = textCarrier(field, "field");
fields.put(field.targetField(), carrier != null && carrier.binary() ? "bytes" : mapped.seaTunnelType());
}
if (binaryEncoding) {
input.put("result_table_name", "batch_source");
ObjectNode encoder = root.putArray("transform").addObject();
encoder.put("plugin_name", "Sql");
encoder.put("source_table_name", "batch_source");
encoder.put("result_table_name", "batch_encoded");
encoder.put("query", "SELECT " + snapshot.mappings().stream().map(f -> {
String field = quoteIdentifier(f.targetField());
var carrier = textCarrier(f, field);
return carrier != null && carrier.binary() ? "RAWTOHEX(" + field + ") AS " + field : field;
}).collect(java.util.stream.Collectors.joining(", ")) + " FROM batch_source");
}
ObjectNode sink = root.putArray("sink").addObject();
if (binaryEncoding) sink.put("source_table_name", "batch_encoded");
String[] targetObject = objectParts(snapshot.targetObject(), target.externalSpaceId());
// Hive writes through its native connector and metastore contract; Doris keeps the approved MySQL wire sink.
boolean hive = "HIVE".equals(target.resourceType());
@@ -194,7 +214,7 @@ final class M3CollectionJobFactory {
} else {
sink.put("plugin_name", "Jdbc");
sink.put("url", mysqlUrl(target.endpointHost(), target.endpointPort(), targetObject[0], target.tlsEnabled()) +
"&forceConnectionTimeZoneToSession=true&preserveInstants=false");
"&forceConnectionTimeZoneToSession=true&preserveInstants=false&sessionVariables=enable_insert_strict=true");
sink.put("driver", "com.mysql.cj.jdbc.Driver");
sink.put("user", target.serviceAccount());
sink.put("password", targetPassword);
@@ -351,7 +371,10 @@ final class M3CollectionJobFactory {
String source = sqlServer ? "[" + checkedIdentifier(field.sourceField()) + "]"
: oracle ? oracleIdentifier(field.sourceField()) : quoteIdentifier(field.sourceField());
String nativeType = field.sourceNativeType() == null ? "" : field.sourceNativeType().toUpperCase(Locale.ROOT).replaceAll("\\(.*\\)$", "").trim();
if (sqlServer) {
var carrier = textCarrier(field, source);
if (carrier != null) {
source = carrier.expression();
} else if (sqlServer) {
source = switch (nativeType) {
case "SQLSERVER:BINARY", "SQLSERVER:VARBINARY", "SQLSERVER:TIMESTAMP", "SQLSERVER:ROWVERSION" -> "CONVERT(varchar(max)," + source + ",2)";
case "SQLSERVER:UNIQUEIDENTIFIER" -> "CONVERT(varchar(36)," + source + ")";
@@ -428,6 +451,12 @@ final class M3CollectionJobFactory {
return DataSourceObjects.mysqlTargetType(source, TargetEngine.valueOf(targetType));
}
private static cn.aixunkeji.datagov.integration.api.datasource.BatchTextTypes.Carrier textCarrier(BatchFieldExecution field, String identifier) {
return cn.aixunkeji.datagov.integration.api.datasource.BatchTextTypes.carrier(new Column(
field.sourceField(), field.sourceType(), field.order(), null, false, field.sourceNativeType(),
field.sourcePrecision(), field.sourceScale(), field.sourceOctetLength()), identifier);
}
private static boolean validBatchTransform(BatchFieldExecution field, MysqlTargetType mapped) {
if ("NONE".equals(field.transform()) || "DEFAULT_IF_NULL".equals(field.transform())) return true;
return "string".equals(mapped.seaTunnelType()) && Set.of("TRIM", "UPPER", "LOWER").contains(field.transform());
@@ -0,0 +1,20 @@
package cn.aixunkeji.datagov.integration.regulatoryreporting;
import cn.aixunkeji.common.satoken.utils.LoginHelper;
import cn.dev33.satoken.stp.StpUtil;
import org.springframework.stereotype.Component;
@Component
class ReportingActor {
static final String PREFIX = "aixun:integration:regulatory-reporting:";
Scope current(String action) {
Long user = LoginHelper.getUserId(), organization = LoginHelper.getDeptId();
if (user == null || organization == null || user <= 0 || organization <= 0
|| !StpUtil.hasPermission(PREFIX + action)) throw ReportingException.forbidden();
return new Scope(user, organization);
}
void credentials() {
if (!StpUtil.hasPermission(PREFIX + "credential")) throw ReportingException.forbidden();
}
record Scope(long user, long organization) { }
}
@@ -0,0 +1,24 @@
package cn.aixunkeji.datagov.integration.regulatoryreporting;
import java.util.List;
public final class ReportingApi {
private ReportingApi() { }
public enum Kind { DEPARTMENT, SYSTEM, TOPIC }
public record Department(String shortName, String level, String supervisor) { }
public record TargetSystem(String endpoint, String environment, String transport, String authentication,
int timeoutSeconds, int maxRetries, String defaultVersion, String fileNameRule,
boolean attachments, boolean batchSupport, boolean receiptQuery) { }
public record Topic(String responsibleDepartment, String period) { }
/** A null credential reference retains the current binding; an empty one removes it. */
public record Command(long version, Kind kind, String code, String name, String parentId, String description,
boolean enabled, Department department, TargetSystem system, Topic topic,
String credentialReference) { }
public record View(String id, long version, Kind kind, String code, String name, String parentId,
String parentName, String description, boolean enabled, Department department,
TargetSystem system, Topic topic, boolean credentialConfigured, String organizationId,
String updatedAt) { }
public record Page<T>(List<T> rows, long total) { }
public record Overview(long departments, long systems, long topics, long enabledTopics) { }
public record Audit(String id, String action, String actorId, long version, String reason, String occurredAt) { }
}
@@ -0,0 +1,32 @@
package cn.aixunkeji.datagov.integration.regulatoryreporting;
import cn.aixunkeji.common.core.domain.R;
import cn.aixunkeji.common.log.annotation.Log;
import cn.aixunkeji.common.log.enums.BusinessType;
import cn.dev33.satoken.annotation.SaCheckPermission;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import static cn.aixunkeji.datagov.integration.regulatoryreporting.ReportingApi.*;
@RestController @RequiredArgsConstructor
@RequestMapping("/api/integration/v1/regulatory-reporting")
class ReportingController {
private final ReportingService service;
@GetMapping("/overview") @SaCheckPermission(ReportingActor.PREFIX + "view")
public R<Overview> overview() { return R.ok(service.overview()); }
@GetMapping("/configs") @SaCheckPermission(ReportingActor.PREFIX + "view")
public R<Page<View>> list(@RequestParam Kind kind, @RequestParam(defaultValue = "") String keyword,
@RequestParam(required = false) String parentId, @RequestParam(required = false) Boolean enabled,
@RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "20") int pageSize) {
return R.ok(service.list(kind, keyword, parentId, enabled, pageNum, pageSize));
}
@GetMapping("/configs/{id}") @SaCheckPermission(ReportingActor.PREFIX + "view")
public R<View> get(@PathVariable String id) { return R.ok(service.get(id)); }
@GetMapping("/configs/{id}/audit") @SaCheckPermission(ReportingActor.PREFIX + "view")
public R<Page<Audit>> history(@PathVariable String id, @RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "20") int pageSize) {
return R.ok(service.history(id, pageNum, pageSize));
}
@PutMapping("/configs/{id}") @SaCheckPermission(ReportingActor.PREFIX + "edit")
@Log(title = "监管报送配置", businessType = BusinessType.UPDATE, isSaveRequestData = false, isSaveResponseData = false)
public R<View> save(@PathVariable String id, @RequestBody Command command) { return R.ok(service.save(id, command)); }
}
@@ -0,0 +1,9 @@
package cn.aixunkeji.datagov.integration.regulatoryreporting;
final class ReportingException extends RuntimeException {
final int status;
ReportingException(int status, String message) { super(message); this.status = status; }
static ReportingException invalid(String message) { return new ReportingException(400, message); }
static ReportingException conflict(String message) { return new ReportingException(409, message); }
static ReportingException forbidden() { return new ReportingException(403, "报送对象不存在或当前无访问权限"); }
}
@@ -0,0 +1,18 @@
package cn.aixunkeji.datagov.integration.regulatoryreporting;
import cn.aixunkeji.common.core.domain.R;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestControllerAdvice(assignableTypes = { ReportingController.class, ReportingStandardController.class })
class ReportingExceptionHandler {
@ExceptionHandler(ReportingException.class)
ResponseEntity<R<Void>> handle(ReportingException error) {
return ResponseEntity.status(error.status).body(R.fail(error.status, error.getMessage()));
}
@ExceptionHandler(DuplicateKeyException.class)
ResponseEntity<R<Void>> duplicate() {
return ResponseEntity.status(409).body(R.fail(409, "当前组织中该类型的编码或对象标识已存在,请刷新核对"));
}
}
@@ -0,0 +1,79 @@
package cn.aixunkeji.datagov.integration.regulatoryreporting;
import cn.aixunkeji.datagov.integration.secret.SecretRef;
import java.net.URI;
import java.util.Set;
import java.util.UUID;
import static cn.aixunkeji.datagov.integration.regulatoryreporting.ReportingApi.*;
import static cn.aixunkeji.datagov.integration.regulatoryreporting.ReportingException.*;
final class ReportingPolicy {
private ReportingPolicy() { }
static String id(String id) {
try { if (id == null || !UUID.fromString(id).toString().equals(id)) throw new IllegalArgumentException(); }
catch (IllegalArgumentException e) { throw invalid("对象标识格式无效"); }
return id;
}
static String text(String value, int max, boolean required, String label) {
String normalized = value == null ? "" : value.strip();
if ((required && normalized.isEmpty()) || normalized.length() > max || normalized.chars().anyMatch(c -> c < 32 && c != '\n' && c != '\t'))
throw invalid(label + "为空、过长或包含无效字符");
return normalized;
}
static Command normalize(Command c) {
if (c == null || c.kind() == null || c.version() < -1 || c.version() == Long.MAX_VALUE) throw invalid("配置版本或类型无效");
String code = text(c.code(), 64, true, "编码");
if (!code.matches("[A-Za-z][A-Za-z0-9_-]{0,63}")) throw invalid("编码须以字母开头,仅包含字母、数字、下划线和连字符");
String parent = c.kind() == Kind.DEPARTMENT ? null : id(c.parentId());
if (c.kind() == Kind.DEPARTMENT && c.parentId() != null && !c.parentId().isBlank()) throw invalid("监管部门不能设置所属系统");
Department department = null;
TargetSystem system = null;
Topic topic = null;
if (c.kind() == Kind.DEPARTMENT) {
if (c.department() == null || c.system() != null || c.topic() != null) throw invalid("部门配置无效");
var d = c.department();
department = new Department(text(d.shortName(), 80, false, "简称"), text(d.level(), 80, false, "层级"), text(d.supervisor(), 200, false, "主管机构"));
} else if (c.kind() == Kind.SYSTEM) {
if (c.system() == null || c.department() != null || c.topic() != null) throw invalid("系统配置无效");
var s = c.system();
if (!Set.of("DEVELOPMENT", "TEST", "PRODUCTION").contains(s.environment() == null ? "" : s.environment())
|| !"HTTP_POST".equals(s.transport()) || !Set.of("NONE", "SECRET_REF").contains(s.authentication() == null ? "" : s.authentication())
|| s.timeoutSeconds() < 1 || s.timeoutSeconds() > 120 || s.maxRetries() < 0 || s.maxRetries() > 5)
throw invalid("环境、传输方式、认证或超时重试配置无效");
String endpoint = text(s.endpoint(), 1000, c.enabled(), "接收端地址");
if (!endpoint.isEmpty()) {
try {
URI uri = URI.create(endpoint);
if (!Set.of("http", "https").contains(uri.getScheme() == null ? "" : uri.getScheme()) || uri.getHost() == null
|| uri.getRawUserInfo() != null || uri.getRawQuery() != null || uri.getRawFragment() != null
|| (uri.getPort() != -1 && (uri.getPort() < 1 || uri.getPort() > 65535))) throw new IllegalArgumentException();
} catch (IllegalArgumentException e) { throw invalid("接收端须为 HTTP(S) 地址,不能包含用户名、密码、查询参数或片段"); }
}
system = new TargetSystem(endpoint, s.environment(), s.transport(), s.authentication(), s.timeoutSeconds(), s.maxRetries(),
text(s.defaultVersion(), 64, false, "默认版本"), text(s.fileNameRule(), 200, false, "命名规则"), s.attachments(), s.batchSupport(), s.receiptQuery());
} else {
if (c.topic() == null || c.department() != null || c.system() != null) throw invalid("主题配置无效");
var t = c.topic();
if (!Set.of("ON_DEMAND", "MONTHLY", "QUARTERLY", "HALF_YEARLY", "YEARLY").contains(t.period() == null ? "" : t.period())) throw invalid("统计周期无效");
topic = new Topic(text(t.responsibleDepartment(), 200, false, "责任部门"), t.period());
}
String credential = c.credentialReference();
if (credential != null) {
if (c.kind() != Kind.SYSTEM) throw invalid("只有上报系统可配置凭据引用");
credential = credential.strip();
if (!credential.isEmpty()) {
if (!credential.startsWith("env://") && !credential.startsWith("file:///")) throw invalid("请使用受管凭据引用,不得填写明文凭据");
try { new SecretRef(credential); } catch (IllegalArgumentException e) { throw invalid("请使用带版本的受管凭据引用,不得填写明文凭据"); }
}
}
return new Command(c.version(), c.kind(), code, text(c.name(), 160, true, "名称"), parent,
text(c.description(), 2000, false, "说明"), c.enabled(), department, system, topic, credential);
}
static void identity(Command c, ReportingRepository.Stored before) {
if (before.kind() != c.kind() || !before.code().equals(c.code()) || !java.util.Objects.equals(before.parentId(), c.parentId()))
throw conflict("对象类型、编码和所属关系创建后不可修改,请停用原配置后新建");
if (before.kind() == Kind.SYSTEM && before.credential() != null && !before.credential().isBlank()
&& !before.command().system().environment().equals(c.system().environment()) && c.credentialReference() == null)
throw conflict("切换环境必须明确清除或重新绑定该环境的凭据");
}
}
@@ -0,0 +1,100 @@
package cn.aixunkeji.datagov.integration.regulatoryreporting;
import lombok.RequiredArgsConstructor;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import tools.jackson.databind.json.JsonMapper;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import static cn.aixunkeji.datagov.integration.regulatoryreporting.ReportingApi.*;
@Repository @RequiredArgsConstructor
class ReportingRepository {
private final JdbcTemplate jdbc;
private final JsonMapper json;
record Stored(String id, long organization, Kind kind, String code, String parentId, String rootId,
long version, String hash, Command command, String credential, String updatedAt) { }
Stored find(ReportingActor.Scope actor, String id, boolean lock) {
return jdbc.query("SELECT * FROM dg_reporting_config WHERE organization_id=? AND config_id=?" + (lock ? " FOR UPDATE" : ""),
this::map, actor.organization(), id).stream().findFirst().orElse(null);
}
Stored required(ReportingActor.Scope actor, String id, boolean lock) {
Stored value = find(actor, id, lock);
if (value == null) throw ReportingException.forbidden();
return value;
}
private Stored map(ResultSet r, int row) throws SQLException {
return new Stored(r.getString("config_id"), r.getLong("organization_id"), Kind.valueOf(r.getString("config_kind")),
r.getString("config_code"), r.getString("parent_id"), r.getString("root_id"), r.getLong("version"),
r.getString("command_sha256"), json.readValue(r.getString("state_json"), Command.class),
r.getString("credential_ref"), r.getTimestamp("update_time").toLocalDateTime().toString());
}
View view(ReportingActor.Scope actor, Stored s) {
var c = s.command();
Stored parent = s.parentId() == null ? null : find(actor, s.parentId(), false);
return new View(s.id(), s.version(), s.kind(), s.code(), c.name(), s.parentId(), parent == null ? null : parent.command().name(),
c.description(), c.enabled(), c.department(), c.system(), c.topic(), s.credential() != null && !s.credential().isBlank(),
Long.toString(s.organization()), s.updatedAt());
}
Page<View> list(ReportingActor.Scope actor, Kind kind, String keyword, String parent, Boolean enabled, int page, int size) {
String where = " WHERE organization_id=? AND config_kind=?";
List<Object> args = new ArrayList<>(List.of(actor.organization(), kind.name()));
if (!keyword.isEmpty()) { where += " AND (INSTR(LOWER(config_name),LOWER(?))>0 OR INSTR(LOWER(config_code),LOWER(?))>0)"; args.add(keyword); args.add(keyword); }
if (parent != null) { where += " AND parent_id=?"; args.add(parent); }
if (enabled != null) { where += " AND enabled=?"; args.add(enabled ? 1 : 0); }
long total = jdbc.queryForObject("SELECT COUNT(*) FROM dg_reporting_config" + where, Long.class, args.toArray());
args.add(size); args.add((page - 1) * size);
var rows = jdbc.query("SELECT * FROM dg_reporting_config" + where + " ORDER BY update_time DESC,config_id LIMIT ? OFFSET ?", this::map, args.toArray());
return new Page<>(rows.stream().map(s -> view(actor, s)).toList(), total);
}
boolean activeChildren(ReportingActor.Scope actor, String id) {
return jdbc.queryForObject("SELECT COUNT(*) FROM dg_reporting_config WHERE organization_id=? AND parent_id=? AND enabled=1", Long.class, actor.organization(), id) > 0;
}
void save(ReportingActor.Scope a, String id, String root, Command c, String credential, String hash) {
// Credentials are stored only in their dedicated reference column, never in JSON or audit payloads.
var safe = new Command(c.version(), c.kind(), c.code(), c.name(), c.parentId(), c.description(), c.enabled(), c.department(), c.system(), c.topic(), null);
String payload = json.writeValueAsString(safe);
if (c.version() == -1) {
jdbc.update("INSERT INTO dg_reporting_config(config_id,organization_id,config_kind,config_code,config_name,parent_id,root_id,enabled,state_json,credential_ref,version,command_sha256,create_dept,create_by,update_by) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
id, a.organization(), c.kind().name(), c.code(), c.name(), c.parentId(), root, c.enabled() ? 1 : 0, payload, credential, 0, hash, a.organization(), a.user(), a.user());
} else if (jdbc.update("UPDATE dg_reporting_config SET config_name=?,enabled=?,state_json=?,credential_ref=?,version=version+1,command_sha256=?,update_by=?,update_time=CURRENT_TIMESTAMP WHERE organization_id=? AND config_id=? AND version=?",
c.name(), c.enabled() ? 1 : 0, payload, credential, hash, a.user(), a.organization(), id, c.version()) != 1) {
throw ReportingException.conflict("配置已被修改,请刷新后重试");
}
audit(a, id, c.version() == -1 ? "CREATE" : "UPDATE", c.version() + 1);
if (c.credentialReference() != null) audit(a, id, "CREDENTIAL_BINDING_CHANGED", c.version() + 1);
}
void audit(ReportingActor.Scope a, String id, String action, long version) {
audit(a, id, action, version, null);
}
void audit(ReportingActor.Scope a, String id, String action, long version, String reason) {
jdbc.update("INSERT INTO dg_reporting_audit(audit_id,organization_id,object_id,action_name,actor_id,object_version,reason) VALUES(?,?,?,?,?,?,?)",
UUID.randomUUID().toString(), a.organization(), id, action, a.user(), version, reason);
}
Page<Audit> history(ReportingActor.Scope a, String id, int page, int size) {
required(a, id, false);
return objectHistory(a, id, page, size);
}
Page<Audit> objectHistory(ReportingActor.Scope a, String id, int page, int size) {
long total = jdbc.queryForObject("SELECT COUNT(*) FROM dg_reporting_audit WHERE organization_id=? AND object_id=?", Long.class, a.organization(), id);
var rows = jdbc.query("SELECT * FROM dg_reporting_audit WHERE organization_id=? AND object_id=? ORDER BY create_time DESC,audit_id LIMIT ? OFFSET ?",
(r, n) -> new Audit(r.getString("audit_id"), r.getString("action_name"), Long.toString(r.getLong("actor_id")), r.getLong("object_version"), r.getString("reason"), r.getTimestamp("create_time").toLocalDateTime().toString()),
a.organization(), id, size, (page - 1) * size);
return new Page<>(rows, total);
}
Overview overview(ReportingActor.Scope a) {
long[] counts = new long[4];
jdbc.query("SELECT config_kind,enabled,COUNT(*) AS amount FROM dg_reporting_config WHERE organization_id=? GROUP BY config_kind,enabled", r -> {
long amount = r.getLong("amount");
switch (Kind.valueOf(r.getString("config_kind"))) {
case DEPARTMENT -> counts[0] += amount;
case SYSTEM -> counts[1] += amount;
case TOPIC -> { counts[2] += amount; if (r.getInt("enabled") == 1) counts[3] += amount; }
}
}, a.organization());
return new Overview(counts[0], counts[1], counts[2], counts[3]);
}
}
@@ -0,0 +1,76 @@
package cn.aixunkeji.datagov.integration.regulatoryreporting;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tools.jackson.databind.json.JsonMapper;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HexFormat;
import static cn.aixunkeji.datagov.integration.regulatoryreporting.ReportingApi.*;
@Service @RequiredArgsConstructor
class ReportingService {
private final ReportingRepository repository;
private final ReportingActor actors;
private final JsonMapper json;
Page<View> list(Kind kind, String keyword, String parent, Boolean enabled, int page, int size) {
paging(page, size);
if (kind == null) throw ReportingException.invalid("请选择配置类型");
if (parent != null && !parent.isBlank()) ReportingPolicy.id(parent); else parent = null;
return repository.list(actors.current("view"), kind, ReportingPolicy.text(keyword, 100, false, "关键词"), parent, enabled, page, size);
}
View get(String id) {
var actor = actors.current("view");
return repository.view(actor, repository.required(actor, ReportingPolicy.id(id), false));
}
Overview overview() { return repository.overview(actors.current("view")); }
Page<Audit> history(String id, int page, int size) {
paging(page, size);
return repository.history(actors.current("view"), ReportingPolicy.id(id), page, size);
}
static void paging(int page, int size) {
if (page < 1 || page > 100000 || size < 1 || size > 100) throw ReportingException.invalid("分页范围无效");
}
@Transactional
public View save(String id, Command raw) {
var actor = actors.current("edit");
ReportingPolicy.id(id);
var command = ReportingPolicy.normalize(raw);
if (command.credentialReference() != null) actors.credentials();
String hash = hash(json.writeValueAsString(command));
var before = repository.find(actor, id, false);
if (before != null) {
// One department root serializes descendant edits, including disable versus child creation.
repository.required(actor, before.rootId(), true);
before = repository.required(actor, id, true);
if (hash.equals(before.hash())) return repository.view(actor, before);
ReportingPolicy.identity(command, before);
if (before.version() != command.version()) throw ReportingException.conflict("配置版本已变化,请刷新后重试");
} else if (command.version() != -1) throw ReportingException.forbidden();
String root = id;
if (command.parentId() != null) {
var parent = repository.required(actor, command.parentId(), false);
root = parent.rootId();
var department = repository.required(actor, root, true);
parent = repository.required(actor, command.parentId(), true);
Kind expected = command.kind() == Kind.SYSTEM ? Kind.DEPARTMENT : Kind.SYSTEM;
if (parent.kind() != expected) throw ReportingException.invalid("所属对象类型不正确");
if (command.enabled() && (!parent.command().enabled() || !department.command().enabled())) throw ReportingException.conflict("所属部门或系统已停用,不能启用当前配置");
}
if (!command.enabled() && before != null && repository.activeChildren(actor, id)) throw ReportingException.conflict("请先停用下属已启用的系统或主题");
String credential = command.credentialReference() == null ? (before == null ? null : before.credential()) : command.credentialReference();
if (command.kind() == Kind.SYSTEM) {
if ("NONE".equals(command.system().authentication()) && credential != null && !credential.isBlank()) throw ReportingException.invalid("无认证方式不能保留凭据绑定,请明确清除凭据");
if (command.enabled() && "SECRET_REF".equals(command.system().authentication()) && (credential == null || credential.isBlank())) throw ReportingException.invalid("请先绑定受管凭据再启用系统");
}
repository.save(actor, id, root, command, credential, hash);
return repository.view(actor, repository.required(actor, id, false));
}
static String hash(String value) {
try { return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8))); }
catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e); }
}
}
@@ -0,0 +1,17 @@
package cn.aixunkeji.datagov.integration.regulatoryreporting;
import java.util.List;
public final class ReportingStandardApi {
private ReportingStandardApi() { }
public record Field(String name, String label, String type, boolean required, Integer maxLength, Integer precision, Integer scale) { }
public record Resource(String code, String name, List<Field> fields, String templateId) { }
public record Definition(String code, String name, String versionLabel, String publisher, String description, List<Resource> resources) { }
public record Save(long version, Definition definition) { }
public record Action(long version, String reason) { }
public record TemplateImport(String xml, String recordElement) { }
public record Template(String id, String sha256, String recordElement, List<String> fields) { }
public record Difference(String resourceCode, TemplateConsistency.Result result, String templateSha256) { }
public record View(String id, long version, String status, Definition definition, List<Difference> differences,
String differenceConfirmation, String updatedAt) { }
}
@@ -0,0 +1,37 @@
package cn.aixunkeji.datagov.integration.regulatoryreporting;
import cn.aixunkeji.common.core.domain.R;
import cn.aixunkeji.common.log.annotation.Log;
import cn.aixunkeji.common.log.enums.BusinessType;
import cn.dev33.satoken.annotation.SaCheckPermission;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import static cn.aixunkeji.datagov.integration.regulatoryreporting.ReportingStandardApi.*;
@RestController @RequiredArgsConstructor
@RequestMapping("/api/integration/v1/regulatory-reporting")
class ReportingStandardController {
private final ReportingStandardService service;
@GetMapping("/standards") @SaCheckPermission(ReportingActor.PREFIX + "view")
public R<ReportingApi.Page<View>> list(@RequestParam(defaultValue = "") String keyword, @RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "20") int pageSize) {
return R.ok(service.list(keyword, pageNum, pageSize));
}
@GetMapping("/standards/{id}") @SaCheckPermission(ReportingActor.PREFIX + "view")
public R<View> get(@PathVariable String id) { return R.ok(service.get(id)); }
@GetMapping("/standards/{id}/audit") @SaCheckPermission(ReportingActor.PREFIX + "view")
public R<ReportingApi.Page<ReportingApi.Audit>> history(@PathVariable String id, @RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "20") int pageSize) {
return R.ok(service.history(id, pageNum, pageSize));
}
@PutMapping("/standards/{id}") @SaCheckPermission(ReportingActor.PREFIX + "standard")
@Log(title = "报送标准版本", businessType = BusinessType.UPDATE, isSaveRequestData = false, isSaveResponseData = false)
public R<View> save(@PathVariable String id, @RequestBody Save command) { return R.ok(service.save(id, command)); }
@PostMapping("/standards/{id}/publish") @SaCheckPermission(ReportingActor.PREFIX + "standard")
@Log(title = "发布报送标准", businessType = BusinessType.UPDATE, isSaveRequestData = false, isSaveResponseData = false)
public R<View> publish(@PathVariable String id, @RequestBody Action command) { return R.ok(service.publish(id, command)); }
@PostMapping("/standards/{id}/disable") @SaCheckPermission(ReportingActor.PREFIX + "standard")
@Log(title = "停用报送标准", businessType = BusinessType.UPDATE, isSaveRequestData = false, isSaveResponseData = false)
public R<View> disable(@PathVariable String id, @RequestBody Action command) { return R.ok(service.disable(id, command)); }
@PostMapping("/templates") @SaCheckPermission(ReportingActor.PREFIX + "standard")
@Log(title = "导入报送目标模板", businessType = BusinessType.INSERT, isSaveRequestData = false, isSaveResponseData = false)
public R<Template> importTemplate(@RequestBody TemplateImport input) { return R.ok(service.importTemplate(input)); }
}
@@ -0,0 +1,154 @@
package cn.aixunkeji.datagov.integration.regulatoryreporting;
import lombok.RequiredArgsConstructor;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tools.jackson.databind.json.JsonMapper;
import java.util.*;
import static cn.aixunkeji.datagov.integration.regulatoryreporting.ReportingStandardApi.*;
import static cn.aixunkeji.datagov.integration.regulatoryreporting.ReportingException.*;
@Service @RequiredArgsConstructor
class ReportingStandardService {
private final JdbcTemplate jdbc;
private final JsonMapper json;
private final ReportingActor actors;
private final ReportingRepository audit;
record Stored(String id, long version, String status, Definition definition, String commandHash, String confirmation, String updatedAt) { }
ReportingApi.Page<View> list(String keyword, int page, int size) {
var a = actors.current("view"); ReportingService.paging(page, size);
String key = ReportingPolicy.text(keyword, 100, false, "关键词");
String where = " WHERE organization_id=? AND (INSTR(LOWER(standard_name),LOWER(?))>0 OR INSTR(LOWER(standard_code),LOWER(?))>0)";
long total = jdbc.queryForObject("SELECT COUNT(*) FROM dg_reporting_standard" + where, Long.class, a.organization(), key, key);
var rows = jdbc.query("SELECT standard_id FROM dg_reporting_standard" + where + " ORDER BY update_time DESC,standard_id LIMIT ? OFFSET ?",
(r, n) -> r.getString(1), a.organization(), key, key, size, (page - 1) * size);
return new ReportingApi.Page<>(rows.stream().map(id -> view(a, read(a, id, false))).toList(), total);
}
View get(String id) { var a = actors.current("view"); return view(a, read(a, ReportingPolicy.id(id), false)); }
ReportingApi.Page<ReportingApi.Audit> history(String id, int page, int size) {
var a = actors.current("view"); ReportingService.paging(page, size);
if (read(a, ReportingPolicy.id(id), false) == null) throw forbidden();
return audit.objectHistory(a, id, page, size);
}
Stored read(ReportingActor.Scope a, String id, boolean lock) {
return jdbc.query("SELECT * FROM dg_reporting_standard WHERE organization_id=? AND standard_id=?" + (lock ? " FOR UPDATE" : ""),
(r, n) -> new Stored(id, r.getLong("version"), r.getString("standard_status"), json.readValue(r.getString("definition_json"), Definition.class),
r.getString("command_sha256"), r.getString("difference_confirmation"), r.getTimestamp("update_time").toLocalDateTime().toString()),
a.organization(), id).stream().findFirst().orElse(null);
}
private View view(ReportingActor.Scope a, Stored s) {
if (s == null) throw forbidden();
return new View(s.id(), s.version(), s.status(), s.definition(), differences(a, s.definition()), s.confirmation(), s.updatedAt());
}
private List<Difference> differences(ReportingActor.Scope a, Definition d) {
return d.resources().stream().map(r -> {
if (r.templateId() == null || r.templateId().isBlank()) return new Difference(r.code(), null, null);
var template = template(a, r.templateId());
return new Difference(r.code(), TemplateConsistency.compare(r.fields().stream().map(Field::name).toList(), template.fields()), template.sha256());
}).toList();
}
Template template(ReportingActor.Scope a, String id) {
return jdbc.query("SELECT * FROM dg_reporting_template WHERE organization_id=? AND template_id=?",
(r, n) -> new Template(id, r.getString("file_sha256"), r.getString("record_element"), Arrays.asList(json.readValue(r.getString("fields_json"), String[].class))),
a.organization(), id).stream().findFirst().orElseThrow(ReportingException::forbidden);
}
@Transactional
public Template importTemplate(TemplateImport input) {
var a = actors.current("standard");
if (input == null) throw invalid("模板不能为空");
var fields = ReportingTemplateParser.fields(input.xml(), input.recordElement());
String digest = ReportingService.hash(input.xml());
var existing = jdbc.query("SELECT template_id FROM dg_reporting_template WHERE organization_id=? AND file_sha256=? AND record_element=?",
(r, n) -> r.getString(1), a.organization(), digest, input.recordElement());
if (!existing.isEmpty()) return template(a, existing.getFirst());
String id = UUID.randomUUID().toString();
jdbc.update("INSERT INTO dg_reporting_template(template_id,organization_id,file_sha256,record_element,fields_json,create_by) VALUES(?,?,?,?,?,?)",
id, a.organization(), digest, input.recordElement(), json.writeValueAsString(fields), a.user());
audit.audit(a, id, "TEMPLATE_IMPORT", 0);
return new Template(id, digest, input.recordElement(), fields);
}
@Transactional
public View save(String id, Save request) {
var a = actors.current("standard"); ReportingPolicy.id(id);
if (request == null || request.version() < -1 || request.version() == Long.MAX_VALUE) throw invalid("标准版本无效");
Definition definition = normalize(request.definition());
differences(a, definition); // Every template must belong to the authenticated organization.
String hash = ReportingService.hash(json.writeValueAsString(new Save(request.version(), definition)));
var before = read(a, id, true);
if (before != null && hash.equals(before.commandHash())) return view(a, before);
if (before == null && request.version() != -1) throw forbidden();
if (before != null) {
if (!"DRAFT".equals(before.status()) || before.version() != request.version()) throw conflict("标准已冻结或版本已变化,请新建版本或刷新");
if (!before.definition().code().equals(definition.code()) || !before.definition().versionLabel().equals(definition.versionLabel())) throw conflict("标准编码和版本号创建后不可修改");
if (jdbc.update("UPDATE dg_reporting_standard SET standard_name=?,definition_json=?,version=version+1,command_sha256=?,difference_confirmation=NULL,update_by=?,update_time=CURRENT_TIMESTAMP WHERE organization_id=? AND standard_id=? AND version=?",
definition.name(), json.writeValueAsString(definition), hash, a.user(), a.organization(), id, request.version()) != 1) throw conflict("标准版本已变化");
} else {
jdbc.update("INSERT INTO dg_reporting_standard(standard_id,organization_id,standard_code,standard_name,version_label,standard_status,definition_json,version,command_sha256,create_by,update_by) VALUES(?,?,?,?,?,'DRAFT',?,0,?,?,?)",
id, a.organization(), definition.code(), definition.name(), definition.versionLabel(), json.writeValueAsString(definition), hash, a.user(), a.user());
}
audit.audit(a, id, before == null ? "STANDARD_CREATE" : "STANDARD_UPDATE", request.version() + 1);
return view(a, read(a, id, false));
}
@Transactional
public View publish(String id, Action command) {
var a = actors.current("standard"); ReportingPolicy.id(id);
var before = read(a, id, true);
if (before == null) throw forbidden();
if (command == null || command.version() < 0) throw invalid("发布版本无效");
String reason = ReportingPolicy.text(command.reason(), 1000, false, "差异确认说明");
String hash = ReportingService.hash("PUBLISH:" + json.writeValueAsString(new Action(command.version(), reason)));
if ("PUBLISHED".equals(before.status()) && hash.equals(before.commandHash())) return view(a, before);
if (!"DRAFT".equals(before.status()) || before.version() != command.version()) throw conflict("标准已冻结或版本已变化");
var differences = differences(a, before.definition());
if (differences.stream().anyMatch(d -> d.result() == null)) throw conflict("每张资源表必须导入实际目标模板后才能发布");
boolean mismatch = differences.stream().anyMatch(d -> !d.result().consistent());
if (mismatch && reason.isBlank()) throw conflict("标准与模板有差异,请核对并填写差异确认说明后发布");
jdbc.update("UPDATE dg_reporting_standard SET standard_status='PUBLISHED',version=version+1,command_sha256=?,difference_confirmation=?,update_by=?,update_time=CURRENT_TIMESTAMP WHERE organization_id=? AND standard_id=?",
hash, mismatch ? reason : null, a.user(), a.organization(), id);
audit.audit(a, id, mismatch ? "STANDARD_PUBLISH_CONFIRMED_DIFF" : "STANDARD_PUBLISH", before.version() + 1, reason);
return view(a, read(a, id, false));
}
@Transactional
public View disable(String id, Action command) {
var a = actors.current("standard"); ReportingPolicy.id(id);
var before = read(a, id, true);
if (before == null) throw forbidden();
if (command == null || command.version() < 0) throw invalid("停用版本无效");
String reason = ReportingPolicy.text(command.reason(), 1000, true, "停用原因");
String hash = ReportingService.hash("DISABLE:" + json.writeValueAsString(new Action(command.version(), reason)));
if ("DISABLED".equals(before.status()) && hash.equals(before.commandHash())) return view(a, before);
if (!"PUBLISHED".equals(before.status()) || before.version() != command.version()) throw conflict("仅可停用当前已发布版本,请刷新后重试");
jdbc.update("UPDATE dg_reporting_standard SET standard_status='DISABLED',version=version+1,command_sha256=?,update_by=?,update_time=CURRENT_TIMESTAMP WHERE organization_id=? AND standard_id=?",
hash, a.user(), a.organization(), id);
audit.audit(a, id, "STANDARD_DISABLE", before.version() + 1, reason);
return view(a, read(a, id, false));
}
static Definition normalize(Definition d) {
if (d == null || d.resources() == null || d.resources().isEmpty() || d.resources().size() > 50) throw invalid("标准需要 1 至 50 张资源表");
String code = token(d.code(), "标准编码"), version = ReportingPolicy.text(d.versionLabel(), 64, true, "标准版本");
Set<String> resources = new HashSet<>(); int fieldCount = 0;
for (Resource r : d.resources()) {
if (r == null || !resources.add(token(r.code(), "资源编码")) || r.fields() == null || r.fields().isEmpty() || r.fields().size() > 500) throw invalid("资源编码重复或字段数量无效");
ReportingPolicy.text(r.name(), 160, true, "资源名称");
Set<String> fields = new HashSet<>();
for (Field f : r.fields()) {
if (f == null || !fields.add(token(f.name(), "字段名")) || !Set.of("STRING", "INTEGER", "DECIMAL", "DATE", "DATETIME", "BOOLEAN").contains(f.type() == null ? "" : f.type())) throw invalid("字段重复或字段类型无效");
ReportingPolicy.text(f.label(), 160, false, "字段说明");
if (f.maxLength() != null && (f.maxLength() < 1 || f.maxLength() > 1000000)) throw invalid("字段长度无效");
if (f.precision() != null && (f.precision() < 1 || f.precision() > 38)) throw invalid("精度须在 1 至 38 之间");
if (f.scale() != null && (f.precision() == null || f.scale() < 0 || f.scale() > f.precision())) throw invalid("小数位数不能超过精度");
}
fieldCount += r.fields().size();
if (r.templateId() != null && !r.templateId().isBlank()) ReportingPolicy.id(r.templateId());
}
if (fieldCount > 2000) throw invalid("单个标准版本字段总数不能超过 2000");
return new Definition(code, ReportingPolicy.text(d.name(), 160, true, "标准名称"), version,
ReportingPolicy.text(d.publisher(), 160, false, "发布机构"), ReportingPolicy.text(d.description(), 2000, false, "变更说明"), List.copyOf(d.resources()));
}
private static String token(String value, String label) {
if (value == null || !value.matches("[A-Za-z_][A-Za-z0-9_.-]{0,127}")) throw invalid(label + "格式无效");
return value;
}
}
@@ -0,0 +1,57 @@
package cn.aixunkeji.datagov.integration.regulatoryreporting;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
final class ReportingTemplateParser {
private ReportingTemplateParser() { }
static List<String> fields(String xml, String recordElement) {
if (xml == null || xml.isBlank() || xml.length() > 262144 || recordElement == null || !recordElement.matches("[A-Za-z_][A-Za-z0-9_.-]{0,127}"))
throw ReportingException.invalid("请提供不超过 256 KiB 字符的 XML 模板及有效记录节点名");
try {
var factory = DocumentBuilderFactory.newInstance();
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
factory.setXIncludeAware(false);
factory.setExpandEntityReferences(false);
var builder = factory.newDocumentBuilder();
builder.setErrorHandler(new DefaultHandler() {
@Override public void error(org.xml.sax.SAXParseException e) throws SAXException { throw e; }
@Override public void fatalError(org.xml.sax.SAXParseException e) throws SAXException { throw e; }
});
var document = builder.parse(new InputSource(new StringReader(xml)));
var records = document.getElementsByTagName(recordElement);
if (records.getLength() == 0 || records.getLength() > 1000) throw ReportingException.invalid("模板未找到记录节点或记录节点过多");
List<String> result = null;
for (int i = 0; i < records.getLength(); i++) {
var names = new ArrayList<String>();
var children = records.item(i).getChildNodes();
for (int j = 0; j < children.getLength(); j++) {
Node node = children.item(j);
if (node instanceof Element element) {
if (element.getElementsByTagName("*").getLength() != 0 || element.getTagName().contains(":")) throw ReportingException.invalid("仅支持记录节点下的平面字段模板,嵌套或命名空间模板需专用适配");
names.add(element.getTagName());
}
}
if (names.size() > 500) throw ReportingException.invalid("单张资源表字段不得超过 500 个");
TemplateConsistency.compare(names, names);
if (result != null && !result.equals(names)) throw ReportingException.invalid("多个记录节点的字段或顺序不一致");
result = List.copyOf(names);
}
return result;
} catch (ReportingException e) { throw e; }
catch (Exception e) { throw ReportingException.invalid("XML 模板无效,或含重复字段、DTD、外部实体等不支持内容"); }
}
}
@@ -0,0 +1,39 @@
package cn.aixunkeji.datagov.integration.regulatoryreporting;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/** Compares the ordered fields of a standard resource with the actual target template. */
public final class TemplateConsistency {
private TemplateConsistency() {}
public record Result(List<String> missingFromTemplate, List<String> extraInTemplate,
boolean orderMismatch) {
public boolean consistent() {
return missingFromTemplate.isEmpty() && extraInTemplate.isEmpty() && !orderMismatch;
}
}
public static Result compare(List<String> standard, List<String> template) {
validate(standard);
validate(template);
Set<String> standardSet = new HashSet<>(standard);
Set<String> templateSet = new HashSet<>(template);
List<String> missing = standard.stream().filter(field -> !templateSet.contains(field)).toList();
List<String> extra = template.stream().filter(field -> !standardSet.contains(field)).toList();
List<String> standardCommon = new ArrayList<>(standard);
standardCommon.retainAll(templateSet);
List<String> templateCommon = new ArrayList<>(template);
templateCommon.retainAll(standardSet);
return new Result(missing, extra, !standardCommon.equals(templateCommon));
}
private static void validate(List<String> fields) {
if (fields == null || fields.isEmpty() || fields.stream().anyMatch(f -> f == null || f.isBlank())
|| new HashSet<>(fields).size() != fields.size()) {
throw new IllegalArgumentException("字段列表不能为空或包含空字段、重复字段");
}
}
}
@@ -0,0 +1,60 @@
package cn.aixunkeji.datagov.integration.batchingestion;
import cn.aixunkeji.datagov.integration.api.datasource.*;
import cn.aixunkeji.datagov.integration.api.datasource.DataSourceObjects.*;
import cn.aixunkeji.datagov.integration.api.DataCollectionIntegrationService.*;
import java.util.*;
import org.junit.jupiter.api.*;
import static org.assertj.core.api.Assertions.*;
class BatchExtendedTypesTest {
@BeforeAll static void json() { M3SeaTunnelCollectionContractTest.initializeJsonMapper(); }
static Column column(String type) { return new Column("payload",type,1,true,false,type,null,null,null); }
@Test void extendedFamiliesMapForBothStorageEngines() {
for (String type : List.of("LONGTEXT","MEDIUMTEXT","JSON","ENUM","SET","BLOB","LONGBLOB","BINARY(16)","VARBINARY(64)","BIT(64)","TIME(6)","DECIMAL(65,30)","GEOMETRY",
"SQLSERVER:TEXT","SQLSERVER:NTEXT","SQLSERVER:VARCHAR(MAX)","SQLSERVER:NVARCHAR(MAX)","SQLSERVER:VARBINARY(MAX)","SQLSERVER:IMAGE","SQLSERVER:XML","SQLSERVER:GEOGRAPHY","SQLSERVER:HIERARCHYID",
"ORACLE:CLOB","ORACLE:NCLOB","ORACLE:BLOB","ORACLE:RAW","ORACLE:LONG RAW","ORACLE:XMLTYPE","ORACLE:JSON","ORACLE:NUMBER","ORACLE:TIMESTAMP(9)","ORACLE:TIMESTAMP(9) WITH TIME ZONE","ORACLE:INTERVAL DAY(2) TO SECOND(9)",
"DAMENG:CLOB","DAMENG:TEXT","DAMENG:BLOB","DAMENG:DATE","DAMENG:NUMBER","DAMENG:TIMESTAMP(9)",
"KINGBASE:TEXT","KINGBASE:BYTEA","KINGBASE:JSONB","KINGBASE:XML","KINGBASE:UUID","KINGBASE:_INT4","KINGBASE:TIMESTAMPTZ","KINGBASE:NUMERIC","KINGBASE:BOOL","KINGBASE:VARCHAR","KINGBASE:CHARACTER VARYING")) {
for (var engine:TargetEngine.values()) {
var mapped=DataSourceObjects.mysqlTargetType(column(type),engine);
assertThat(mapped.supported()).as("%s -> %s",type,engine).isTrue();
assertThat(mapped.targetType()).isEqualTo("STRING");
assertThat(BatchTextTypes.carrier(column(type),"payload")).isNotNull();
}
}
}
@Test void mysqlQueryPerformsExplicitReversibleConversionsAndStrictTargetWrites() {
var fields=new ArrayList<BatchFieldExecution>();
for (String type:List.of("LONGTEXT","JSON","BLOB","TIME(6)","DECIMAL(65,30)","BIT(64)","GEOMETRY")) {
String name="field_"+fields.size();
fields.add(new BatchFieldExecution(fields.size()+1,name,name,"STRING","STRING","NONE",null,null,List.of(),type,null,null,null));
}
var snapshot=new BatchExecutionSnapshot("ORDER","sales.sample","analytics.sample","FULL",null,null,1,false,null,fields);
assertThat(M3CollectionJobFactory.batchCapability(M3BatchTemporalPrecisionTest.source(),11,21,"JDBC","DORIS",snapshot,M3BatchTemporalPrecisionTest.target()).supported()).isTrue();
var job=M3CollectionJobFactory.batchJob(M3BatchTemporalPrecisionTest.source(),"test",M3BatchTemporalPrecisionTest.target(),"test",snapshot);
assertThat(job.get("source").get(0).get("query").asText())
.contains("`field_0` AS `field_0`", "CAST(`field_1` AS CHAR CHARACTER SET utf8mb4)", "HEX(`field_2`)",
"CAST(`field_3` AS CHAR CHARACTER SET utf8mb4)","CAST(`field_4` AS CHAR CHARACTER SET utf8mb4)","CAST(CAST(`field_5` AS UNSIGNED) AS CHAR)","HEX(`field_6`)")
.doesNotContain("SUBSTR", "LEFT(");
assertThat(job.get("sink").get(0).get("url").asText()).contains("sessionVariables=enable_insert_strict=true");
}
@Test void binaryLobIsReadAsBytesAndEncodedAfterReadingWithoutSubstr() {
var source=new cn.aixunkeji.datagov.integration.api.DataSourceView(11L,"source","ORACLE","oracle.internal",1521,"FREEPDB1","READER",
"file:///test?version=v1",cn.aixunkeji.datagov.integration.api.NormalizedExternalStatus.SUCCEEDED,"aixun-dataops",20L,
"SALES","ORDER","JDBC","BASIC",Map.of("useSsl","false"),1L,null,null,null,null,null,null,java.time.LocalDateTime.now());
var field=new BatchFieldExecution(1,"PAYLOAD","payload","STRING","STRING","NONE",null,null,List.of(),"ORACLE:BLOB",null,null,null);
var snapshot=new BatchExecutionSnapshot("ORDER","FREEPDB1.SALES.SAMPLE","analytics.sample","FULL",null,null,1,false,null,List.of(field));
var job=M3CollectionJobFactory.batchJob(source,"test",M3BatchTemporalPrecisionTest.target(),"test",snapshot);
assertThat(job.get("source").get(0).get("schema").get("fields").get("payload").asText()).isEqualTo("bytes");
assertThat(job.get("source").get(0).get("query").asText()).isEqualTo("SELECT \"PAYLOAD\" AS \"payload\" FROM \"SALES\".\"SAMPLE\"");
assertThat(job.get("transform").get(0).get("query").asText()).isEqualTo("SELECT RAWTOHEX(`payload`) AS `payload` FROM batch_source");
assertThat(job.get("sink").get(0).get("source_table_name").asText()).isEqualTo("batch_encoded");
}
@Test void sqlTemplatesNeverUseSourceTypeAsExecutableText() {
assertThat(BatchTextTypes.carrier(column("ORACLE:EVIL); DROP TABLE x"),"value")).isNull();
assertThat(DataSourceObjects.mysqlTargetType(column("CUSTOM_OBJECT"),TargetEngine.DORIS).supported()).isFalse();
assertThat(BatchTextTypes.carrier(column("ORACLE:NUMBER"),"value").expression()).contains("NLS_NUMERIC_CHARACTERS");
assertThat(BatchTextTypes.carrier(column("ORACLE:TIMESTAMP(9) WITH TIME ZONE"),"value").expression()).contains("FF9 TZH:TZM");
}
}
@@ -25,8 +25,8 @@ class DamengBatchTypesTest {
for (String binary : List.of("BINARY", "VARBINARY", "RAW")) {
assertThat(type(binary, 32, null).targetType()).isEqualTo("VARCHAR(64)");
assertThat(type(binary, 16383, null).targetType()).isEqualTo("VARCHAR(32766)");
assertThat(type(binary, 16384, null).supported()).isFalse();
assertThat(type(binary, null, null).supported()).isFalse();
assertThat(type(binary, 16384, null).targetType()).isEqualTo("STRING");
assertThat(type(binary, null, null).targetType()).isEqualTo("STRING");
}
for (String primitive : List.of("BIT", "BOOLEAN", "TINYINT", "REAL", "FLOAT", "DOUBLE", "DOUBLE PRECISION"))
assertThat(type(primitive, 24, null).supported()).as(primitive).isTrue();
@@ -34,11 +34,11 @@ class DamengBatchTypesTest {
assertThat(type("NVARCHAR", 20, null).targetType()).isEqualTo("VARCHAR(80)");
assertThat(type("BIGINT", 19, 0).targetType()).isEqualTo("BIGINT");
assertThat(type("TIMESTAMP", 36, 6).targetType()).isEqualTo("DATETIME(6)");
assertThat(type("TIMESTAMP", 36, 7).supported()).isFalse();
assertThat(type("TIMESTAMP", 36, null).supported()).isFalse();
assertThat(type("NUMBER", 0, -127).supported()).isFalse();
assertThat(type("DATE", null, null).supported()).isFalse();
assertThat(type("CLOB", null, null).supported()).isFalse();
assertThat(type("TIMESTAMP", 36, 7).targetType()).isEqualTo("STRING");
assertThat(type("TIMESTAMP", 36, null).targetType()).isEqualTo("STRING");
assertThat(type("NUMBER", 0, -127).targetType()).isEqualTo("STRING");
assertThat(type("DATE", null, null).targetType()).isEqualTo("STRING");
assertThat(type("CLOB", null, null).targetType()).isEqualTo("STRING");
}
@Test void generatesScopedDamengQueryWithoutOpeningUnverifiedCapability() {
var source = new DataSourceView(11L, "source", "DAMENG", "dameng.internal", 5236, "TEST", "READER",
@@ -37,9 +37,9 @@ class KingbaseBatchTypesTest {
new Column("event_at", "TIMESTAMP", 1, true, false, "date", 29, 6, null)),
TargetEngine.DORIS).supported()).isFalse();
assertThat(type("varchar", 20, null).targetType()).isEqualTo("VARCHAR(80)");
assertThat(type("numeric", 0, 0).supported()).isFalse();
assertThat(type("timestamp", 26, 6).supported()).isFalse();
assertThat(type("bytea", 0, 0).supported()).isFalse();
assertThat(type("numeric", 0, 0).targetType()).isEqualTo("STRING");
assertThat(type("timestamp", 26, 6).targetType()).isEqualTo("STRING");
assertThat(type("bytea", 0, 0).targetType()).isEqualTo("STRING");
}
@Test void generatesNativeDriverQueryButKeepsCapabilityClosed() {
var source = new DataSourceView(11L, "source", "KINGBASE", "kingbase.internal", 54321, "test", "reader",
@@ -38,6 +38,11 @@ class MysqlTargetTypeMatrixTest {
hive.put("VARCHAR(512)", "VARCHAR(512)");
hive.put("TEXT", "STRING");
hive.put("MEDIUMTEXT", "STRING");
hive.put("LONGTEXT", "STRING");
hive.put("JSON", "STRING");
hive.put("BLOB", "STRING");
hive.put("TIME(6)", "STRING");
hive.put("DECIMAL(65,30)", "STRING");
hive.put("DATE", "DATE");
hive.put("YEAR", "INT");
hive.put("DATETIME(6)", "TIMESTAMP");
@@ -46,7 +51,6 @@ class MysqlTargetTypeMatrixTest {
.as("Hive %s", source).isEqualTo(target));
Map<String, String> doris = new LinkedHashMap<>(hive);
doris.remove("MEDIUMTEXT");
doris.put("DATETIME(6)", "DATETIME(6)");
doris.put("TIMESTAMP(3)", "DATETIME(3)");
doris.forEach((source, target) -> assertThat(mapping(source, TargetEngine.DORIS).targetType())
@@ -55,8 +59,7 @@ class MysqlTargetTypeMatrixTest {
@Test void unsupportedTypesFailWithFieldAndReasonWithoutDroppingOrStringCoercion() {
for (TargetEngine engine : TargetEngine.values()) {
for (String source : List.of("DECIMAL(39,2)", "BIT(8)", "LONGTEXT", "BINARY(16)",
"VARBINARY(64)", "BLOB", "TIME(6)", "JSON", "ENUM", "SET")) {
for (String source : List.of("DECIMAL(66,2)", "UNRECOGNIZED", "VARCHAR", "FLOAT(54)")) {
var result = mapping(source, engine);
assertThat(result.supported()).as("%s %s", engine, source).isFalse();
assertThat(result.field()).isEqualTo("source_field");
@@ -66,7 +69,7 @@ class MysqlTargetTypeMatrixTest {
assertThat(result.errorSummary()).contains("source_field");
}
}
assertThat(mapping("MEDIUMTEXT", TargetEngine.DORIS).supported()).isFalse();
assertThat(mapping("MEDIUMTEXT", TargetEngine.DORIS).targetType()).isEqualTo("STRING");
}
@Test void characterCapacityUsesCharactersForHiveAndBytesForDoris() {
@@ -93,7 +96,7 @@ class MysqlTargetTypeMatrixTest {
}
private static DataSourceObjects.MysqlTargetType mapping(String declaration, TargetEngine engine) {
Integer precision = declaration.startsWith("VARCHAR") || declaration.startsWith("CHAR") ?
Integer precision = declaration.startsWith("VARCHAR(") || declaration.startsWith("CHAR(") ?
Integer.valueOf(declaration.replaceAll(".*\\(([0-9]+)\\).*", "$1")) : null;
Long octets = precision == null ? null : precision.longValue();
return DataSourceObjects.mysqlTargetType(new Column("source_field", declaration, 1, true, false,
@@ -27,12 +27,13 @@ class OracleBatchTypesTest {
assertThat(type("NUMBER", 18, 4).targetType()).isEqualTo("DECIMAL(18,4)");
assertThat(type("NVARCHAR2", 20, null).targetType()).isEqualTo("VARCHAR(80)");
}
@Test void rejectsUnknownPrecisionAndUnverifiedLossyTypes() {
assertThat(type("NUMBER", 0, -127).supported()).isFalse();
assertThat(type("TIMESTAMP", 26, 9).supported()).isFalse();
assertThat(type("TIMESTAMP", 26, null).supported()).isFalse();
assertThat(type("CLOB", null, null).supported()).isFalse();
assertThat(type("TIMESTAMP WITH TIME ZONE", 35, 6).supported()).isFalse();
@Test void preservesExtendedValuesThroughExplicitTextCarriers() {
assertThat(type("NUMBER", 0, -127).targetType()).isEqualTo("STRING");
assertThat(type("TIMESTAMP", 26, 9).targetType()).isEqualTo("STRING");
assertThat(type("TIMESTAMP", 26, null).targetType()).isEqualTo("STRING");
assertThat(type("CLOB", null, null).targetType()).isEqualTo("STRING");
assertThat(type("TIMESTAMP WITH TIME ZONE", 35, 6).targetType()).isEqualTo("STRING");
assertThat(type("CUSTOM_OBJECT", null, null).supported()).isFalse();
}
@Test void oracleQueryUsesServiceForConnectionAndSchemaForSql() {
var source = new DataSourceView(11L, "source", "ORACLE", "oracle.internal", 1521, "FREEPDB1", "READER",
@@ -0,0 +1,40 @@
package cn.aixunkeji.datagov.integration.regulatoryreporting;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import static cn.aixunkeji.datagov.integration.regulatoryreporting.ReportingApi.*;
class ReportingPolicyTest {
static final String ROOT = "6df18399-cc0d-4c0a-8ee8-3413e9da3a89";
static Command department(long version, boolean enabled) {
return new Command(version, Kind.DEPARTMENT, "REGULATOR", "监管部门", null, "", enabled, new Department("", "", ""), null, null, null);
}
static Command system(String endpoint, String environment, String authentication, String credential, boolean enabled) {
return new Command(-1, Kind.SYSTEM, "TARGET", "上报系统", ROOT, "", enabled, null,
new TargetSystem(endpoint, environment, "HTTP_POST", authentication, 30, 0, "", "", true, true, false), null, credential);
}
@Test void permitsDisabledIncompleteSystemButRequiresEndpointWhenEnabling() {
assertDoesNotThrow(() -> ReportingPolicy.normalize(system("", "TEST", "NONE", null, false)));
assertThrows(ReportingException.class, () -> ReportingPolicy.normalize(system("", "TEST", "NONE", null, true)));
}
@Test void rejectsCredentialsInEndpointAndPlaintextReference() {
for (String endpoint : new String[]{"https://user:pass@example.org/upload", "https://example.org/upload?token=hidden", "file:///tmp/source", "https://example.org/#secret"}) {
assertThrows(ReportingException.class, () -> ReportingPolicy.normalize(system(endpoint, "TEST", "NONE", null, false)));
}
assertThrows(ReportingException.class, () -> ReportingPolicy.normalize(system("https://example.org/upload", "TEST", "SECRET_REF", "plaintext", true)));
}
@Test void acceptsOnlyVersionedReference() {
assertDoesNotThrow(() -> ReportingPolicy.normalize(system("https://example.org/upload", "TEST", "SECRET_REF", "env://REPORTING_TEST?version=1", true)));
assertThrows(ReportingException.class, () -> ReportingPolicy.normalize(system("https://example.org/upload", "TEST", "SECRET_REF", "env://REPORTING_TEST", true)));
}
@Test void environmentSwitchCannotSilentlyCarryCredential() {
var before = new ReportingRepository.Stored(ROOT, 9, Kind.SYSTEM, "TARGET", ROOT, ROOT, 0, "hash",
system("https://example.org/upload", "TEST", "SECRET_REF", null, true), "env://REPORTING_TEST?version=1", "now");
assertThrows(ReportingException.class, () -> ReportingPolicy.identity(system("https://example.org/upload", "PRODUCTION", "SECRET_REF", null, true), before));
}
@Test void rejectsInvalidCodeAndParentIdentity() {
assertThrows(ReportingException.class, () -> ReportingPolicy.id("not-a-uuid"));
var value = department(-1, true);
assertThrows(ReportingException.class, () -> ReportingPolicy.normalize(new Command(-1, value.kind(), "bad code", value.name(), null, "", true, value.department(), null, null, null)));
}
}
@@ -0,0 +1,62 @@
package cn.aixunkeji.datagov.integration.regulatoryreporting;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import tools.jackson.databind.json.JsonMapper;
import java.util.HashMap;
import java.util.Map;
import static org.mockito.Mockito.*;
import static org.mockito.ArgumentMatchers.*;
import static org.junit.jupiter.api.Assertions.*;
import static cn.aixunkeji.datagov.integration.regulatoryreporting.ReportingApi.*;
import static cn.aixunkeji.datagov.integration.regulatoryreporting.ReportingPolicyTest.*;
class ReportingServiceTest {
final ReportingRepository repository = mock(ReportingRepository.class);
final ReportingActor actors = mock(ReportingActor.class);
final ReportingActor.Scope actor = new ReportingActor.Scope(7, 9);
final ReportingService service = new ReportingService(repository, actors, JsonMapper.builder().build());
final Map<String, ReportingRepository.Stored> states = new HashMap<>();
final String systemId = "e8d386e0-5ad7-477c-9f40-62ef70789234";
@BeforeEach void setup() {
when(actors.current(anyString())).thenReturn(actor);
when(repository.find(eq(actor), anyString(), anyBoolean())).thenAnswer(i -> states.get(i.getArgument(1)));
when(repository.required(eq(actor), anyString(), anyBoolean())).thenAnswer(i -> { var value = states.get(i.getArgument(1)); if (value == null) throw ReportingException.forbidden(); return value; });
doAnswer(i -> {
Command c = i.getArgument(3); String id = i.getArgument(1);
states.put(id, new ReportingRepository.Stored(id, 9, c.kind(), c.code(), c.parentId(), i.getArgument(2), c.version() + 1, i.getArgument(5), c, i.getArgument(4), "now")); return null;
}).when(repository).save(eq(actor), anyString(), anyString(), any(), nullable(String.class), anyString());
}
@Test void replayDoesNotCreateSecondMutationOrAudit() {
service.save(ROOT, department(-1, true)); service.save(ROOT, department(-1, true));
verify(repository, times(1)).save(eq(actor), eq(ROOT), eq(ROOT), any(), isNull(), anyString());
}
@Test void staleVersionCannotOverwriteCurrentConfiguration() {
service.save(ROOT, department(-1, true)); service.save(ROOT, department(0, false));
assertThrows(ReportingException.class, () -> service.save(ROOT, department(0, true)));
assertEquals(1, states.get(ROOT).version());
}
@Test void disabledParentPreventsEnabledChild() {
service.save(ROOT, department(-1, false));
assertThrows(ReportingException.class, () -> service.save(systemId, system("https://example.org", "TEST", "NONE", null, true)));
assertFalse(states.containsKey(systemId));
}
@Test void activeChildPreventsParentDisable() {
service.save(ROOT, department(-1, true)); when(repository.activeChildren(actor, ROOT)).thenReturn(true);
assertThrows(ReportingException.class, () -> service.save(ROOT, department(0, false)));
assertTrue(states.get(ROOT).command().enabled());
}
@Test void crossOrganizationParentIsNotAccepted() {
assertThrows(ReportingException.class, () -> service.save(systemId, system("https://example.org", "TEST", "NONE", null, true)));
verify(repository, never()).save(any(), anyString(), anyString(), any(), any(), anyString());
}
@Test void credentialMutationRequiresSeparatePermission() {
doThrow(ReportingException.forbidden()).when(actors).credentials();
assertThrows(ReportingException.class, () -> service.save(systemId, system("https://example.org", "TEST", "SECRET_REF", "env://REPORTING_TEST?version=1", true)));
verifyNoInteractions(repository);
}
@Test void configuredAuthenticationCannotEnableWithoutBinding() {
service.save(ROOT, department(-1, true));
assertThrows(ReportingException.class, () -> service.save(systemId, system("https://example.org", "TEST", "SECRET_REF", null, true)));
}
}
@@ -0,0 +1,87 @@
package cn.aixunkeji.datagov.integration.regulatoryreporting;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.jdbc.core.JdbcTemplate;
import tools.jackson.databind.json.JsonMapper;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
import static org.mockito.ArgumentMatchers.*;
import static cn.aixunkeji.datagov.integration.regulatoryreporting.ReportingStandardApi.*;
class ReportingStandardServiceTest {
final JdbcTemplate jdbc = mock(JdbcTemplate.class);
final ReportingActor actors = mock(ReportingActor.class);
final ReportingRepository audit = mock(ReportingRepository.class);
final ReportingActor.Scope actor = new ReportingActor.Scope(7, 9);
final ReportingStandardService service = spy(new ReportingStandardService(jdbc, JsonMapper.builder().build(), actors, audit));
final String id = "6df18399-cc0d-4c0a-8ee8-3413e9da3a89", template = "e8d386e0-5ad7-477c-9f40-62ef70789234";
@BeforeEach void setup() { when(actors.current(anyString())).thenReturn(actor); }
Definition definition(String templateId) { return new Definition("STD", "测试标准", "1.0", "测试机构", "", List.of(new Resource("ROW", "资源表", List.of(new Field("ID", "标识", "STRING", true, 36, null, null)), templateId))); }
ReportingStandardService.Stored state(String status, Definition d) { return new ReportingStandardService.Stored(id, 0, status, d, "previous", null, "now"); }
@Test void publishedVersionCannotBeOverwritten() {
doReturn(state("PUBLISHED", definition(null))).when(service).read(actor, id, true);
assertThrows(ReportingException.class, () -> service.save(id, new Save(0, definition(null))));
verifyNoInteractions(jdbc, audit);
}
@Test void missingTemplatePreventsPublishing() {
doReturn(state("DRAFT", definition(null))).when(service).read(actor, id, true);
assertThrows(ReportingException.class, () -> service.publish(id, new Action(0, "确认")));
verifyNoInteractions(jdbc, audit);
}
@Test void differencesNeedExplicitConfirmation() {
doReturn(state("DRAFT", definition(template))).when(service).read(actor, id, true);
doReturn(new Template(template, "hash", "ROW", List.of("ID", "EXTRA"))).when(service).template(actor, template);
assertThrows(ReportingException.class, () -> service.publish(id, new Action(0, "")));
verifyNoInteractions(jdbc, audit);
}
@Test void stalePublishCannotFreezeNewerDefinition() {
doReturn(state("DRAFT", definition(template))).when(service).read(actor, id, true);
assertThrows(ReportingException.class, () -> service.publish(id, new Action(1, "确认")));
verifyNoInteractions(jdbc, audit);
}
@Test void templateLookupUsesAuthenticatedOrganization() {
doThrow(ReportingException.forbidden()).when(service).template(actor, template);
assertThrows(ReportingException.class, () -> service.save(id, new Save(-1, definition(template))));
verify(service).template(actor, template); verifyNoInteractions(jdbc, audit);
}
@Test void duplicateFieldsAndInvalidPrecisionAreRejected() {
var field = new Field("ID", "标识", "STRING", true, 36, null, null);
assertThrows(ReportingException.class, () -> ReportingStandardService.normalize(new Definition("STD", "标准", "1", "", "", List.of(new Resource("ROW", "资源", List.of(field, field), null)))));
var decimal = new Field("AMOUNT", "金额", "DECIMAL", true, null, 3, 4);
assertThrows(ReportingException.class, () -> ReportingStandardService.normalize(new Definition("STD", "标准", "1", "", "", List.of(new Resource("ROW", "资源", List.of(decimal), null)))));
}
@Test void unchangedPublishRetryReturnsFrozenVersionWithoutSecondAudit() {
var command = new Action(0, "");
String hash = ReportingService.hash("PUBLISH:" + JsonMapper.builder().build().writeValueAsString(command));
var frozen = new ReportingStandardService.Stored(id, 1, "PUBLISHED", definition(template), hash, null, "now");
doReturn(frozen).when(service).read(actor, id, true);
doReturn(new Template(template, "hash", "ROW", List.of("ID"))).when(service).template(actor, template);
assertEquals("PUBLISHED", service.publish(id, command).status());
verifyNoInteractions(jdbc, audit);
}
@Test void confirmedDifferenceCanPublishWithAuditedReason() {
doReturn(state("DRAFT", definition(template))).when(service).read(actor, id, true);
doReturn(new ReportingStandardService.Stored(id, 1, "PUBLISHED", definition(template), "hash", "已核对目标模板", "now"))
.when(service).read(actor, id, false);
doReturn(new Template(template, "hash", "ROW", List.of("ID", "EXTRA"))).when(service).template(actor, template);
var result = service.publish(id, new Action(0, "已核对目标模板"));
assertEquals("PUBLISHED", result.status());
assertEquals("已核对目标模板", result.differenceConfirmation());
assertEquals(List.of("EXTRA"), result.differences().getFirst().result().extraInTemplate());
verify(audit).audit(actor, id, "STANDARD_PUBLISH_CONFIRMED_DIFF", 1, "已核对目标模板");
}
@Test void disablingRetainsDefinitionAndRequiresReason() {
doReturn(state("PUBLISHED", definition(template))).when(service).read(actor, id, true);
assertThrows(ReportingException.class, () -> service.disable(id, new Action(0, " ")));
verifyNoInteractions(jdbc, audit);
doReturn(new ReportingStandardService.Stored(id, 1, "DISABLED", definition(template), "hash", null, "now"))
.when(service).read(actor, id, false);
doReturn(new Template(template, "hash", "ROW", List.of("ID"))).when(service).template(actor, template);
var result = service.disable(id, new Action(0, "规范已换版"));
assertEquals("DISABLED", result.status());
assertEquals(definition(template), result.definition());
verify(audit).audit(actor, id, "STANDARD_DISABLE", 1, "规范已换版");
}
}
@@ -0,0 +1,24 @@
package cn.aixunkeji.datagov.integration.regulatoryreporting;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
class ReportingTemplateParserTest {
@Test void extractsOrderedFieldsWithoutPersistingData() {
assertEquals(List.of("ID", "NAME"), ReportingTemplateParser.fields("<ROOT><ROW><ID>1</ID><NAME>测试</NAME></ROW><ROW><ID>2</ID><NAME>另一条</NAME></ROW></ROOT>", "ROW"));
}
@Test void rejectsExternalEntitiesAndDoctype() {
assertThrows(ReportingException.class, () -> ReportingTemplateParser.fields("<!DOCTYPE ROW [<!ENTITY xxe SYSTEM 'file:///etc/passwd'>]><ROW><ID>&xxe;</ID></ROW>", "ROW"));
}
@Test void rejectsInconsistentRepeatedRecords() {
assertThrows(ReportingException.class, () -> ReportingTemplateParser.fields("<ROOT><ROW><ID/></ROW><ROW><NAME/></ROW></ROOT>", "ROW"));
}
@Test void rejectsNestedAndDuplicateFieldsAndMissingNode() {
for (String xml : List.of("<ROW><ID/><ID/></ROW>", "<ROW><ID><VALUE/></ID></ROW>", "<ROOT><ID/></ROOT>"))
assertThrows(ReportingException.class, () -> ReportingTemplateParser.fields(xml, "ROW"));
}
@Test void enforcesInputLimit() {
assertThrows(ReportingException.class, () -> ReportingTemplateParser.fields(" ".repeat(262145), "ROW"));
}
}
@@ -0,0 +1,26 @@
package cn.aixunkeji.datagov.integration.regulatoryreporting;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
class TemplateConsistencyTest {
@Test void identifiesMissingExtraAndOrderDifferences() {
var result = TemplateConsistency.compare(List.of("ID", "NAME", "VALUE"), List.of("VALUE", "ID", "OTHER"));
assertEquals(List.of("NAME"), result.missingFromTemplate());
assertEquals(List.of("OTHER"), result.extraInTemplate());
assertTrue(result.orderMismatch());
assertFalse(result.consistent());
}
@Test void acceptsOnlyIdenticalFieldsAndOrder() {
assertTrue(TemplateConsistency.compare(List.of("ID", "NAME"), List.of("ID", "NAME")).consistent());
assertFalse(TemplateConsistency.compare(List.of("ID", "NAME"), List.of("NAME", "ID")).consistent());
}
@Test void rejectsAmbiguousFieldLists() {
assertThrows(IllegalArgumentException.class, () -> TemplateConsistency.compare(List.of("ID", "ID"), List.of("ID")));
assertThrows(IllegalArgumentException.class, () -> TemplateConsistency.compare(List.of(" "), List.of("ID")));
assertThrows(IllegalArgumentException.class, () -> TemplateConsistency.compare(List.of(), List.of("ID")));
}
}
@@ -0,0 +1,43 @@
import type { AxiosPromise } from '@/utils/api-types';
import request from '@/utils/request';
export type ConfigKind = 'DEPARTMENT' | 'SYSTEM' | 'TOPIC';
export interface Department { shortName: string; level: string; supervisor: string }
export interface TargetSystem {
endpoint: string; environment: 'DEVELOPMENT' | 'TEST' | 'PRODUCTION'; transport: 'HTTP_POST';
authentication: 'NONE' | 'SECRET_REF'; timeoutSeconds: number; maxRetries: number;
defaultVersion: string; fileNameRule: string; attachments: boolean; batchSupport: boolean; receiptQuery: boolean;
}
export interface Topic { responsibleDepartment: string; period: string }
export interface ConfigCommand {
version: number; kind: ConfigKind; code: string; name: string; parentId: string | null; description: string;
enabled: boolean; department: Department | null; system: TargetSystem | null; topic: Topic | null;
credentialReference: string | null;
}
export interface ConfigView extends Omit<ConfigCommand, 'credentialReference'> {
id: string; parentName: string | null; credentialConfigured: boolean; organizationId: string; updatedAt: string;
}
export interface Page<T> { rows: T[]; total: number }
export interface ConfigQuery { kind: ConfigKind; keyword?: string; parentId?: string; enabled?: boolean; pageNum: number; pageSize: number }
export interface Overview { departments: number; systems: number; topics: number; enabledTopics: number }
export interface Audit { id: string; action: string; actorId: string; version: number; reason: string | null; occurredAt: string }
const base = '/api/integration/v1/regulatory-reporting';
export const listConfigs = (params: ConfigQuery): AxiosPromise<Page<ConfigView>> => request({ url: `${base}/configs`, params });
export const getConfig = (id: string): AxiosPromise<ConfigView> => request({ url: `${base}/configs/${id}` });
export const saveConfig = (id: string, data: ConfigCommand): AxiosPromise<ConfigView> =>
request({ url: `${base}/configs/${id}`, method: 'put', data, headers: { repeatSubmit: false } });
export const getOverview = (): AxiosPromise<Overview> => request({ url: `${base}/overview` });
export const getAudit = (id: string, pageNum: number, pageSize: number): AxiosPromise<Page<Audit>> =>
request({ url: `${base}/configs/${id}/audit`, params: { pageNum, pageSize } });
export function emptyConfig(kind: ConfigKind): ConfigCommand {
return { version: -1, kind, code: '', name: '', parentId: null, description: '', enabled: false, credentialReference: null,
department: kind === 'DEPARTMENT' ? { shortName: '', level: '', supervisor: '' } : null,
system: kind === 'SYSTEM' ? { endpoint: '', environment: 'TEST', transport: 'HTTP_POST', authentication: 'NONE', timeoutSeconds: 30,
maxRetries: 0, defaultVersion: '', fileNameRule: '', attachments: false, batchSupport: false, receiptQuery: false } : null,
topic: kind === 'TOPIC' ? { responsibleDepartment: '', period: 'ON_DEMAND' } : null };
}
export function editConfig(row: ConfigView): ConfigCommand {
return structuredClone({ version: row.version, kind: row.kind, code: row.code, name: row.name, parentId: row.parentId,
description: row.description, enabled: row.enabled, department: row.department, system: row.system, topic: row.topic, credentialReference: null });
}
@@ -0,0 +1,21 @@
import type { AxiosPromise } from '@/utils/api-types';
import request from '@/utils/request';
import type { Page, Audit } from './index';
export interface StandardField { name: string; label: string; type: string; required: boolean; maxLength: number | null; precision: number | null; scale: number | null }
export interface StandardResource { code: string; name: string; fields: StandardField[]; templateId: string | null }
export interface StandardDefinition { code: string; name: string; versionLabel: string; publisher: string; description: string; resources: StandardResource[] }
export interface TemplateDifference { resourceCode: string; result: { missingFromTemplate: string[]; extraInTemplate: string[]; orderMismatch: boolean } | null; templateSha256: string | null }
export interface StandardView { id: string; version: number; status: 'DRAFT' | 'PUBLISHED' | 'DISABLED'; definition: StandardDefinition; differences: TemplateDifference[]; differenceConfirmation: string | null; updatedAt: string }
export interface TargetTemplate { id: string; sha256: string; recordElement: string; fields: string[] }
const base = '/api/integration/v1/regulatory-reporting';
export const listStandards = (params: { keyword: string; pageNum: number; pageSize: number }): AxiosPromise<Page<StandardView>> => request({ url: `${base}/standards`, params });
export const getStandard = (id: string): AxiosPromise<StandardView> => request({ url: `${base}/standards/${id}` });
export const getStandardAudit = (id: string, pageNum: number, pageSize: number): AxiosPromise<Page<Audit>> => request({ url: `${base}/standards/${id}/audit`, params: { pageNum, pageSize } });
export const saveStandard = (id: string, version: number, definition: StandardDefinition): AxiosPromise<StandardView> => request({ url: `${base}/standards/${id}`, method: 'put', data: { version, definition }, headers: { repeatSubmit: false } });
export const publishStandard = (id: string, version: number, reason: string): AxiosPromise<StandardView> => request({ url: `${base}/standards/${id}/publish`, method: 'post', data: { version, reason }, headers: { repeatSubmit: false } });
export const disableStandard = (id: string, version: number, reason: string): AxiosPromise<StandardView> => request({ url: `${base}/standards/${id}/disable`, method: 'post', data: { version, reason }, headers: { repeatSubmit: false } });
export const importTemplate = (xml: string, recordElement: string): AxiosPromise<TargetTemplate> => request({ url: `${base}/templates`, method: 'post', data: { xml, recordElement }, headers: { repeatSubmit: false } });
export const blankField = (): StandardField => ({ name: '', label: '', type: 'STRING', required: false, maxLength: null, precision: null, scale: null });
export const blankResource = (): StandardResource => ({ code: '', name: '', fields: [blankField()], templateId: null });
export const blankStandard = (): StandardDefinition => ({ code: '', name: '', versionLabel: '', publisher: '', description: '', resources: [blankResource()] });
export const hasDifference = (difference: TemplateDifference): boolean => !!difference.result && (difference.result.orderMismatch || difference.result.missingFromTemplate.length > 0 || difference.result.extraInTemplate.length > 0);
@@ -25,7 +25,8 @@ export interface FieldMapping { sourceField: string; targetField: string; source
transform: 'NONE'; filterValues: string[] }
export interface DraftRequest { items: SourceSelection[]; targetType: TargetType }
export interface DraftItem extends IngestionSelection { targetTable: string; sourceFingerprint?: string;
columns: ColumnDefinition[]; mappings: FieldMapping[]; errorSummary?: string }
columns: ColumnDefinition[]; mappings: FieldMapping[]; errorSummary?: string;
fieldCompatibility?: { field: string; nativeType: string; conversion: string; error?: string }[] }
export interface Draft { items: DraftItem[] }
export interface SubmitItem extends IngestionSelection { targetTable: string; sourceFingerprint?: string;
createTarget: boolean; columns: ColumnDefinition[]; mappings: FieldMapping[] }
@@ -8,6 +8,11 @@ const root = (path: string): RouteRecordRaw => ({
});
describe('permission-filtered navigation groups', () => {
it('keeps regulatory reporting independent and hides it without permitted children', () => {
const reporting = root('/datagov-regulatory-reporting');
expect(buildNavigationGroups([reporting]).map(g => g.title)).toEqual(['监管数据报送']);
expect(buildNavigationGroups([{ path: '/datagov-regulatory-reporting', component: {} } as RouteRecordRaw])).toEqual([]);
});
it('assigns each existing root exactly once in the requested order', () => {
const paths = ['', '/visual-workspace', '/datagov-workbench', '/datagov-integration', '/datagov-storage',
'/datagov-architecture', '/datagov-development', '/datagov-metadata', '/datagov-master-data',
+1
查看文件
@@ -23,6 +23,7 @@ const definitions = [
['assets', '资产', 'table', ['/datagov-assets']],
['metrics', '指标', 'chart', ['/datagov-metrics']],
['services', '服务', 'server', ['/datagov-services']],
['regulatory-reporting', '监管数据报送', 'documentation', ['/datagov-regulatory-reporting']],
['operations', '运维', 'monitor', ['/datagov-operations', '/monitor', '/datagov-security']],
['datasets', '数集', 'table', ['/datagov-high-quality-datasets']],
['settings', '设置', 'system', ['/system']]
@@ -102,13 +102,13 @@
<el-table-column label="来源" min-width="220"><template #default="{ row }">{{ `${row.sourceName || '--'} / ${row.sourceDatabase || '--'}` }}</template></el-table-column>
<el-table-column label="源表" prop="sourceTable" min-width="170"><template #default="{ row }">{{ row.sourceTable || '--' }}</template></el-table-column>
<el-table-column label="目标表" min-width="190"><template #default="{ row }"><el-input v-model="row.targetTable" maxlength="128" :disabled="Boolean(row.errorSummary)" /></template></el-table-column>
<el-table-column label="采集字段" min-width="170" align="center"><template #default="{ row }">{{ `${row.mappings.length} / ${row.availableMappings.length} 个${copyOnly ? '原配置' : ''}字段` }}</template></el-table-column>
<el-table-column label="采集字段" min-width="170" align="center"><template #default="{ row }">{{ `${row.mappings.length} / ${row.fieldCompatibility?.length || row.availableMappings.length} 个${copyOnly ? '原配置' : ''}字段` }}</template></el-table-column>
<el-table-column label="建表方式" width="156" align="center"><template #default="{ row }"><el-button-group class="create-mode-buttons">
<el-button size="small" :type="row.createTarget ? 'primary' : 'default'" :plain="!row.createTarget" :disabled="Boolean(row.errorSummary)" @click="setCreateTarget(row as SelectableDraftItem, true)">新建</el-button>
<el-button size="small" :type="row.createTarget ? 'default' : 'primary'" :plain="row.createTarget" :disabled="Boolean(row.errorSummary)" @click="setCreateTarget(row as SelectableDraftItem, false)">已有</el-button>
</el-button-group></template></el-table-column>
<el-table-column label="检查结果" width="150" show-overflow-tooltip><template #default="{ row }"><el-text v-if="copyOnly" type="info">历史配置,未重新校验</el-text><el-tag v-else-if="!mappingValidation(row)" type="success" effect="plain">可提交</el-tag><el-text v-else type="danger">{{ mappingValidation(row) }}</el-text></template></el-table-column>
<el-table-column width="180" class-name="dg-row-actions" label="操作" align="center" fixed="right"><template #default="{ row }"><RowActions><el-button icon="Operation" link type="primary" :disabled="!row.availableMappings.length" @click="showMapping(row)">选择字段</el-button></RowActions></template></el-table-column>
<el-table-column width="180" class-name="dg-row-actions" label="操作" align="center" fixed="right"><template #default="{ row }"><RowActions><el-button icon="Operation" link type="primary" :disabled="!row.availableMappings.length && !row.fieldCompatibility?.length" @click="showMapping(row)">选择字段</el-button></RowActions></template></el-table-column>
</el-table>
</section>
@@ -174,15 +174,17 @@
<el-dialog v-model="mappingDialog" :title="`${mappingItem?.sourceTable || ''} 选择采集字段`" width="820px" append-to-body @closed="mappingItem = undefined">
<el-alert title="默认采集全部字段;可取消不需要的字段。至少保留一个字段,字段顺序将作为目标建表顺序。" type="info" show-icon :closable="false" class="mb-3" />
<el-alert title="长文本按实际内容写入;二进制以十六进制保存,复杂类型及超精度数值以文本保存。目标容量超限会报错,不会截断。" type="info" show-icon :closable="false" class="mb-3" />
<el-alert v-for="issue in mappingItem?.fieldCompatibility?.filter(item => item.error) || []" :key="issue.field" :title="`${issue.field}(${issue.nativeType}):${issue.error};本次不采集此字段,请确认其余字段。`" type="warning" show-icon :closable="false" class="mb-3" />
<el-table ref="mappingTableRef" :data="mappingItem?.availableMappings || []" row-key="sourceField" border class="data-table" max-height="520" empty-text="暂无字段映射" @selection-change="onMappingSelectionChange">
<el-table-column type="selection" width="55" align="center" />
<el-table-column label="源字段" prop="sourceField" min-width="150"><template #default="{ row }">{{ row.sourceField || '--' }}</template></el-table-column>
<el-table-column label="源类型" prop="sourceType" min-width="130"><template #default="{ row }">{{ row.sourceType || '--' }}</template></el-table-column>
<el-table-column label="源类型" prop="sourceType" min-width="130"><template #default="{ row }">{{ mappingItem?.fieldCompatibility?.find(item => item.field === row.sourceField)?.nativeType || row.sourceType || '--' }}</template></el-table-column>
<el-table-column label="目标字段" prop="targetField" min-width="150"><template #default="{ row }">{{ row.targetField || '--' }}</template></el-table-column>
<el-table-column label="目标类型" prop="targetType" min-width="130"><template #default="{ row }">{{ row.targetType || '--' }}</template></el-table-column>
<el-table-column label="处理方式" width="100" align="center"><template #default="{ row }">{{ row.transform === 'NONE' ? '原样写入' : row.transform || '--' }}</template></el-table-column>
<el-table-column label="保存方式" min-width="220"><template #default="{ row }">{{ row.transform === 'NONE' ? mappingItem?.fieldCompatibility?.find(item => item.field === row.sourceField)?.conversion || '按映射类型保存' : row.transform || '--' }}</template></el-table-column>
</el-table>
<template #footer><div class="dialog-footer"><el-text type="info">已选择 {{ mappingItem?.mappings.length || 0 }} 个字段</el-text><el-button type="primary" :disabled="!mappingItem?.mappings.length" @click="mappingDialog = false">确认选择</el-button></div></template>
<template #footer><div class="dialog-footer"><el-text type="info">已选择 {{ mappingItem?.mappings.length || 0 }} 个字段</el-text><el-button type="primary" :disabled="!mappingItem?.mappings.length" @click="confirmMappingSelection">确认选择</el-button></div></template>
</el-dialog>
</div>
</template>
@@ -208,6 +210,7 @@ import { checkPermi } from '@/utils/permission';
import { ingestionStatusLabel } from '@/utils/datagov/ingestionDisplay';
interface SelectableDraftItem extends DraftItem {
compatibilityConfirmed?: boolean;
historyItemId?: string | number;
createTarget: boolean;
availableColumns: ColumnDefinition[];
@@ -645,7 +648,8 @@ async function showMapping(row: unknown) {
if (sequence === draftRequestSequence && mappingItem.value === item) mappingSelectionInitializing = false;
}
function onMappingSelectionChange(rows: FieldMapping[]) { if (mappingSelectionInitializing || !mappingItem.value) return; const selected = new Set(rows.map((mapping) => mapping.sourceField.toLowerCase())); mappingItem.value.mappings = mappingItem.value.availableMappings.filter((mapping) => selected.has(mapping.sourceField.toLowerCase())).map((mapping) => ({ ...mapping, filterValues: [...mapping.filterValues] })); const targetNames = new Set(mappingItem.value.mappings.map((mapping) => mapping.targetField.toLowerCase())); mappingItem.value.columns = mappingItem.value.availableColumns.filter((column) => targetNames.has(column.name.toLowerCase())).map((column) => ({ ...column })); }
function mappingValidation(row: unknown) { const item = row as SelectableDraftItem; if (item.errorSummary) return item.errorSummary; if (!item.mappings.length || item.columns.length !== item.mappings.length) return '请至少选择一个字段'; if (targetType.value === 'DORIS' && ['FLOAT', 'DOUBLE', 'STRING'].includes(item.columns[0]?.type?.toUpperCase())) return 'Doris 目标首列需为整数、日期或定长字段,请调整选择顺序'; return ''; }
function confirmMappingSelection() { if (mappingItem.value) mappingItem.value.compatibilityConfirmed = true; mappingDialog.value = false; }
function mappingValidation(row: unknown) { const item = row as SelectableDraftItem; if (item.errorSummary) return item.errorSummary; if (item.fieldCompatibility?.some(field => field.error) && !item.compatibilityConfirmed) return '部分字段不支持,请打开“选择字段”确认采集范围'; if (!item.mappings.length || item.columns.length !== item.mappings.length) return '请至少选择一个字段'; if (targetType.value === 'DORIS' && ['FLOAT', 'DOUBLE', 'STRING'].includes(item.columns[0]?.type?.toUpperCase())) return 'Doris 目标首列需为整数、日期或定长字段,请调整选择顺序'; return ''; }
const autoSyncNotice = ref('');
const currentCollectionResult = ref<CollectionDetailVO>();
let autoSyncSequence = 0;
@@ -0,0 +1,143 @@
<template>
<div v-hasPermi="[permission + 'view']" class="p-2 app-container">
<div class="search-wrap"><el-card shadow="hover" class="search-panel" :class="{ 'is-collapsed': !showSearch }">
<el-form :inline="true" :model="query" class="query-form" @submit.prevent="search">
<el-form-item label="关键词"><el-input v-model="query.keyword" clearable maxlength="100" placeholder="名称或编码" @keyup.enter="search" /></el-form-item>
<el-form-item label="状态"><el-select v-model="query.enabled" clearable placeholder="全部状态"><el-option label="启用" :value="true" /><el-option label="停用" :value="false" /></el-select></el-form-item>
<el-form-item><el-button type="primary" icon="Search" @click="search">搜索</el-button><el-button icon="Refresh" @click="reset">重置</el-button></el-form-item>
</el-form>
</el-card></div>
<el-card shadow="hover" class="table-panel">
<template #header><div class="toolbar-shell"><div class="table-heading"><h3>{{ title }}</h3><p>共 {{ total }} 条记录</p></div>
<div class="toolbar-actions"><el-button v-hasPermi="[permission + 'edit']" type="primary" plain icon="Plus" @click="openCreate">新增{{ objectName }}</el-button>
<right-toolbar v-model:show-search="showSearch" :search="false" @query-table="load" /></div></div></template>
<el-alert v-if="loadFailed" title="读取失败,请刷新重试" type="error" :closable="false" class="mb-3" />
<el-table v-loading="loading" :data="rows" border class="data-table" :empty-text="loadFailed ? '数据未能读取' : '暂无配置'">
<el-table-column prop="code" label="编码" min-width="140" show-overflow-tooltip />
<el-table-column prop="name" label="名称" min-width="180" show-overflow-tooltip />
<el-table-column v-if="kind !== 'DEPARTMENT'" :label="parentLabel" min-width="180" show-overflow-tooltip><template #default="{ row }">{{ row.parentName || '--' }}</template></el-table-column>
<el-table-column v-if="kind === 'SYSTEM'" label="环境" width="100"><template #default="{ row }">{{ environmentLabel(row.system?.environment) }}</template></el-table-column>
<el-table-column v-if="kind === 'SYSTEM'" label="凭据" width="100"><template #default="{ row }">{{ row.credentialConfigured ? '已配置' : '未配置' }}</template></el-table-column>
<el-table-column v-if="kind === 'TOPIC'" label="统计周期" width="110"><template #default="{ row }">{{ periodLabel(row.topic?.period) }}</template></el-table-column>
<el-table-column label="状态" width="90"><template #default="{ row }"><el-tag :type="row.enabled ? 'success' : 'info'">{{ row.enabled ? '启用' : '停用' }}</el-tag></template></el-table-column>
<el-table-column label="更新时间" width="170"><template #default="{ row }">{{ parseTime(row.updatedAt) || '--' }}</template></el-table-column>
<el-table-column label="操作" width="170" align="center" fixed="right" class-name="dg-row-actions"><template #default="{ row }"><RowActions>
<el-button v-hasPermi="[permission + 'edit']" link type="primary" icon="Edit" @click="openEdit(row as ConfigView)">编辑</el-button>
<el-button link type="primary" icon="View" @click="openAudit(row as ConfigView)">审计</el-button>
</RowActions></template></el-table-column>
</el-table>
<pagination v-show="total > 0" v-model:page="query.pageNum" v-model:limit="query.pageSize" :total="total" @pagination="load" />
</el-card>
<el-dialog v-model="visible" :title="(form.version < 0 ? '新增' : '编辑') + objectName" width="800px" append-to-body destroy-on-close :close-on-click-modal="false" :close-on-press-escape="!saving" :show-close="!saving" @closed="clearCredential">
<el-form ref="formRef" :model="form" :rules="rules" label-width="110px" class="dialog-grid-form" :disabled="saving">
<el-row :gutter="16">
<el-col :span="12"><el-form-item label="编码" prop="code"><el-input v-model="form.code" :disabled="form.version >= 0" maxlength="64" placeholder="字母开头,可含数字、_、-" /></el-form-item></el-col>
<el-col :span="12"><el-form-item label="名称" prop="name"><el-input v-model="form.name" maxlength="160" /></el-form-item></el-col>
<el-col v-if="kind !== 'DEPARTMENT'" :span="24"><el-form-item :label="parentLabel" prop="parentId">
<el-select v-model="form.parentId" filterable remote :remote-method="searchParents" :loading="parentLoading" :disabled="form.version >= 0" class="w-full" placeholder="输入名称或编码搜索">
<el-option v-for="parent in parents" :key="parent.id" :value="parent.id" :label="parent.name + ' (' + parent.code + ')' + (parent.enabled ? '' : ' · 已停用')" />
</el-select><span v-if="parentTotal > parents.length" class="text-sm">匹配 {{ parentTotal }} 条,请输入关键词缩小范围</span>
</el-form-item></el-col>
<template v-if="form.department">
<el-col :span="12"><el-form-item label="简称"><el-input v-model="form.department.shortName" maxlength="80" /></el-form-item></el-col>
<el-col :span="12"><el-form-item label="层级"><el-input v-model="form.department.level" maxlength="80" /></el-form-item></el-col>
<el-col :span="24"><el-form-item label="主管机构"><el-input v-model="form.department.supervisor" maxlength="200" /></el-form-item></el-col>
</template>
<template v-if="form.system">
<el-col :span="24"><el-form-item label="接收端地址"><el-input v-model="form.system.endpoint" maxlength="1000" placeholder="HTTP(S) 接口地址,不含凭据或查询参数" /></el-form-item></el-col>
<el-col :span="12"><el-form-item label="环境"><el-select v-model="form.system.environment" class="w-full"><el-option label="开发" value="DEVELOPMENT" /><el-option label="测试" value="TEST" /><el-option label="生产" value="PRODUCTION" /></el-select></el-form-item></el-col>
<el-col :span="12"><el-form-item label="传输方式"><el-select v-model="form.system.transport" class="w-full"><el-option label="HTTP POST" value="HTTP_POST" /></el-select></el-form-item></el-col>
<el-col :span="12"><el-form-item label="认证方式"><el-select v-model="form.system.authentication" class="w-full"><el-option label="无认证" value="NONE" /><el-option label="受管凭据" value="SECRET_REF" /></el-select></el-form-item></el-col>
<el-col :span="12"><el-form-item label="凭据状态"><el-tag :type="credentialConfigured ? 'success' : 'info'">{{ credentialConfigured ? '已配置' : '未配置' }}</el-tag></el-form-item></el-col>
<el-col v-hasPermi="[permission + 'credential']" :span="24"><el-form-item label="凭据操作"><el-radio-group v-model="credentialAction"><el-radio value="KEEP">保留现有绑定</el-radio><el-radio value="REPLACE">绑定新引用</el-radio><el-radio value="CLEAR">清除绑定</el-radio></el-radio-group></el-form-item>
<el-form-item v-if="credentialAction === 'REPLACE'" label="受管引用"><el-input v-model="credentialInput" type="password" autocomplete="off" maxlength="512" placeholder="填写已配置且带版本的 secretRef,不填写密码或 Token" /></el-form-item>
</el-col>
<el-col :span="12"><el-form-item label="超时(秒)"><el-input-number v-model="form.system.timeoutSeconds" :min="1" :max="120" /></el-form-item></el-col>
<el-col :span="12"><el-form-item label="重试上限"><el-input-number v-model="form.system.maxRetries" :min="0" :max="5" /></el-form-item></el-col>
<el-col :span="12"><el-form-item label="默认版本"><el-input v-model="form.system.defaultVersion" maxlength="64" /></el-form-item></el-col>
<el-col :span="12"><el-form-item label="文件命名规则"><el-input v-model="form.system.fileNameRule" maxlength="200" /></el-form-item></el-col>
<el-col :span="24"><el-form-item label="目标能力"><el-checkbox v-model="form.system.attachments">支持附件</el-checkbox><el-checkbox v-model="form.system.batchSupport">支持批量</el-checkbox><el-checkbox v-model="form.system.receiptQuery">支持回执查询</el-checkbox></el-form-item></el-col>
</template>
<template v-if="form.topic">
<el-col :span="12"><el-form-item label="责任部门"><el-input v-model="form.topic.responsibleDepartment" maxlength="200" /></el-form-item></el-col>
<el-col :span="12"><el-form-item label="统计周期"><el-select v-model="form.topic.period" class="w-full"><el-option v-for="period in periods" :key="period.value" :value="period.value" :label="period.label" /></el-select></el-form-item></el-col>
</template>
<el-col :span="24"><el-form-item label="说明"><el-input v-model="form.description" type="textarea" :rows="3" maxlength="2000" show-word-limit /></el-form-item></el-col>
<el-col :span="24"><el-form-item label="状态"><el-switch v-model="form.enabled" active-text="启用" inactive-text="停用" /></el-form-item></el-col>
</el-row>
</el-form>
<template #footer><div class="dialog-footer"><el-button type="primary" :loading="saving" @click="submit">保存</el-button><el-button :disabled="saving" @click="visible = false">取消</el-button></div></template>
</el-dialog>
<el-drawer v-model="auditVisible" :title="auditTitle" size="720px" append-to-body>
<el-table v-loading="auditLoading" :data="audits" border empty-text="暂无审计记录">
<el-table-column label="操作" min-width="160"><template #default="{ row }">{{ auditLabel(row.action) }}</template></el-table-column>
<el-table-column prop="actorId" label="操作人 ID" min-width="160" />
<el-table-column prop="version" label="版本" width="80" />
<el-table-column label="时间" width="170"><template #default="{ row }">{{ parseTime(row.occurredAt) || '--' }}</template></el-table-column>
</el-table>
<pagination v-show="auditTotal > 0" v-model:page="auditPage" v-model:limit="auditSize" :total="auditTotal" @pagination="loadAudit" />
</el-drawer>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue';
import { ElMessage } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import { parseTime } from '@/utils/aixun';
import { emptyConfig, editConfig, listConfigs, getConfig, saveConfig, getAudit } from '@/api/datagov/regulatory-reporting';
import type { ConfigKind, ConfigView, ConfigQuery, Audit } from '@/api/datagov/regulatory-reporting';
const props = defineProps<{ kind: ConfigKind }>();
const permission = 'aixun:integration:regulatory-reporting:';
const objectName = computed(() => ({ DEPARTMENT: '部门', SYSTEM: '系统', TOPIC: '主题' })[props.kind]);
const title = computed(() => ({ DEPARTMENT: '上报部门', SYSTEM: '上报系统', TOPIC: '报送主题' })[props.kind]);
const parentLabel = computed(() => props.kind === 'SYSTEM' ? '所属部门' : '所属系统');
const periods = [{ value: 'ON_DEMAND', label: '按需' }, { value: 'MONTHLY', label: '月度' }, { value: 'QUARTERLY', label: '季度' }, { value: 'HALF_YEARLY', label: '半年度' }, { value: 'YEARLY', label: '年度' }];
const periodLabel = (value?: string) => periods.find(p => p.value === value)?.label || '--';
const environmentLabel = (value?: string) => ({ DEVELOPMENT: '开发', TEST: '测试', PRODUCTION: '生产' })[value || ''] || '--';
const auditLabel = (value: string) => ({ CREATE: '新建', UPDATE: '修改', CREDENTIAL_BINDING_CHANGED: '变更凭据绑定' })[value] || value;
const query = reactive<ConfigQuery>({ kind: props.kind, keyword: '', pageNum: 1, pageSize: 20 });
const rows = ref<ConfigView[]>([]), total = ref(0), loading = ref(false), loadFailed = ref(false), showSearch = ref(true);
const visible = ref(false), saving = ref(false), formRef = ref<FormInstance>(), form = ref(emptyConfig(props.kind)), currentId = ref('');
const credentialConfigured = ref(false), credentialAction = ref('KEEP'), credentialInput = ref('');
const parents = ref<ConfigView[]>([]), parentTotal = ref(0), parentLoading = ref(false);
const auditVisible = ref(false), auditLoading = ref(false), auditTitle = ref(''), auditId = ref(''), auditPage = ref(1), auditSize = ref(20), auditTotal = ref(0), audits = ref<Audit[]>([]);
const rules: FormRules = { code: [{ required: true, message: '请输入编码', trigger: 'blur' }, { pattern: /^[A-Za-z][A-Za-z0-9_-]{0,63}$/, message: '编码格式无效', trigger: 'blur' }], name: [{ required: true, whitespace: true, message: '请输入名称', trigger: 'blur' }], parentId: [{ required: true, message: '请选择所属对象', trigger: 'change' }] };
let loadSequence = 0, parentSequence = 0, auditSequence = 0;
async function load() {
const sequence = ++loadSequence; loading.value = true; loadFailed.value = false;
try { const { data } = await listConfigs({ ...query, enabled: typeof query.enabled === 'boolean' ? query.enabled : undefined }); if (sequence === loadSequence) { rows.value = data.rows; total.value = data.total; } }
catch { if (sequence === loadSequence) { rows.value = []; total.value = 0; loadFailed.value = true; } }
finally { if (sequence === loadSequence) loading.value = false; }
}
function search() { query.pageNum = 1; void load(); }
function reset() { query.keyword = ''; query.enabled = undefined; search(); }
async function searchParents(keyword: string) {
if (props.kind === 'DEPARTMENT') return;
const sequence = ++parentSequence; parentLoading.value = true;
try { const { data } = await listConfigs({ kind: props.kind === 'SYSTEM' ? 'DEPARTMENT' : 'SYSTEM', keyword, pageNum: 1, pageSize: 50 }); if (sequence === parentSequence) { parents.value = data.rows; parentTotal.value = data.total; } }
finally { if (sequence === parentSequence) parentLoading.value = false; }
}
function clearCredential() { credentialInput.value = ''; credentialAction.value = 'KEEP'; form.value.credentialReference = null; }
function openCreate() { form.value = emptyConfig(props.kind); currentId.value = crypto.randomUUID(); credentialConfigured.value = false; clearCredential(); visible.value = true; void searchParents(''); }
async function openEdit(row: ConfigView) {
const { data } = await getConfig(row.id);
currentId.value = data.id; form.value = editConfig(data); credentialConfigured.value = data.credentialConfigured; clearCredential();
parents.value = data.parentId ? [(await getConfig(data.parentId)).data] : []; parentTotal.value = parents.value.length; visible.value = true;
}
async function submit() {
if (saving.value || !await formRef.value?.validate().catch(() => false)) return;
if (credentialAction.value === 'REPLACE' && !credentialInput.value.trim()) { ElMessage.warning('请输入受管凭据引用'); return; }
saving.value = true;
const command = { ...form.value, credentialReference: credentialAction.value === 'REPLACE' ? credentialInput.value.trim() : credentialAction.value === 'CLEAR' ? '' : null };
try { await saveConfig(currentId.value, command); visible.value = false; clearCredential(); ElMessage.success('保存成功'); await load(); }
finally { saving.value = false; }
}
function openAudit(row: ConfigView) { auditId.value = row.id; auditTitle.value = row.name + ' · 操作审计'; auditPage.value = 1; audits.value = []; auditTotal.value = 0; auditVisible.value = true; void loadAudit(); }
async function loadAudit() {
const sequence = ++auditSequence; auditLoading.value = true;
try { const { data } = await getAudit(auditId.value, auditPage.value, auditSize.value); if (sequence === auditSequence) { audits.value = data.rows; auditTotal.value = data.total; } }
finally { if (sequence === auditSequence) auditLoading.value = false; }
}
onMounted(load);
</script>
@@ -0,0 +1,4 @@
<template><ConfigPage kind="DEPARTMENT" /></template>
<script setup lang="ts">
import ConfigPage from '../ConfigPage.vue';
</script>
@@ -0,0 +1,25 @@
<template>
<div v-hasPermi="['aixun:integration:regulatory-reporting:view']" class="p-2 app-container">
<el-card shadow="hover" class="table-panel">
<template #header><div class="toolbar-shell"><div class="table-heading"><h3>报送总览</h3><p>当前组织的监管报送配置</p></div><el-button icon="Refresh" :loading="loading" @click="load">刷新</el-button></div></template>
<el-alert v-if="failed" type="error" title="统计读取失败,请刷新重试" :closable="false" class="mb-3" />
<div v-loading="loading" class="reporting-overview">
<template v-if="data"><el-statistic title="监管部门" :value="data.departments" /><el-statistic title="上报系统" :value="data.systems" />
<el-statistic title="报送主题" :value="data.topics" /><el-statistic title="启用主题" :value="data.enabledTopics" /></template>
<template v-else><div v-for="label in ['监管部门', '上报系统', '报送主题', '启用主题']" :key="label">{{ label }}<p>--</p></div></template>
</div>
</el-card>
</div>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { getOverview } from '@/api/datagov/regulatory-reporting';
import type { Overview } from '@/api/datagov/regulatory-reporting';
const data = ref<Overview>(), loading = ref(false), failed = ref(false);
async function load() { if (loading.value) return; loading.value = true; failed.value = false; try { data.value = (await getOverview()).data; } catch { data.value = undefined; failed.value = true; } finally { loading.value = false; } }
onMounted(load);
</script>
<style scoped>
.reporting-overview { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 24px; padding: 16px 0; }
@media (max-width: 760px) { .reporting-overview { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
</style>
@@ -0,0 +1,124 @@
<template>
<div v-hasPermi="[prefix + 'view']" class="p-2 app-container">
<div class="search-wrap"><el-card shadow="hover" class="search-panel" :class="{ 'is-collapsed': !showSearch }"><el-form :inline="true" class="query-form">
<el-form-item label="关键词"><el-input v-model="query.keyword" placeholder="标准名称或编码" maxlength="100" clearable @keyup.enter="search" /></el-form-item>
<el-form-item><el-button type="primary" icon="Search" @click="search">搜索</el-button><el-button icon="Refresh" @click="reset">重置</el-button></el-form-item>
</el-form></el-card></div>
<el-card shadow="hover" class="table-panel">
<template #header><div class="toolbar-shell"><div class="table-heading"><h3>报送标准</h3><p>共 {{ total }} 个版本</p></div><div class="toolbar-actions"><el-button v-hasPermi="[prefix + 'standard']" type="primary" plain icon="Plus" @click="create">新增标准</el-button><right-toolbar v-model:show-search="showSearch" :search="false" @query-table="load" /></div></div></template>
<el-alert v-if="failed" type="error" title="标准读取失败,请刷新重试" :closable="false" class="mb-3" />
<el-table v-loading="loading" :data="rows" border class="data-table" :empty-text="failed ? '数据未能读取' : '暂无报送标准'">
<el-table-column prop="definition.code" label="标准编码" min-width="160" show-overflow-tooltip /><el-table-column prop="definition.name" label="标准名称" min-width="200" show-overflow-tooltip />
<el-table-column prop="definition.versionLabel" label="版本" width="110" /><el-table-column label="资源表" width="80"><template #default="{ row }">{{ row.definition.resources.length }}</template></el-table-column>
<el-table-column label="状态" width="100"><template #default="{ row }"><el-tag :type="row.status === 'PUBLISHED' ? 'success' : 'info'">{{ statusLabel(row.status) }}</el-tag></template></el-table-column>
<el-table-column label="模板检查" min-width="130"><template #default="{ row }">{{ consistencyLabel(row as StandardView) }}</template></el-table-column>
<el-table-column label="操作" width="260" fixed="right" align="center" class-name="dg-row-actions"><template #default="{ row }"><RowActions>
<el-button link type="primary" icon="View" @click="open(row as StandardView, false)">详情</el-button>
<el-button v-if="row.status === 'DRAFT'" v-hasPermi="[prefix + 'standard']" link type="primary" icon="Edit" @click="open(row as StandardView, true)">编辑</el-button>
<el-button v-hasPermi="[prefix + 'standard']" link type="primary" icon="CopyDocument" @click="copy(row as StandardView)">新版本</el-button>
</RowActions></template></el-table-column>
</el-table>
<pagination v-show="total > 0" v-model:page="query.pageNum" v-model:limit="query.pageSize" :total="total" @pagination="load" />
</el-card>
<el-drawer v-model="visible" title="报送标准版本" size="90%" append-to-body :close-on-click-modal="false" :close-on-press-escape="!saving" :show-close="!saving">
<el-form :model="definition" label-width="100px" :disabled="!editing || saving">
<el-row :gutter="16">
<el-col :span="12"><el-form-item label="标准编码" required><el-input v-model="definition.code" :disabled="version >= 0" maxlength="128" /></el-form-item></el-col>
<el-col :span="12"><el-form-item label="标准名称" required><el-input v-model="definition.name" maxlength="160" /></el-form-item></el-col>
<el-col :span="12"><el-form-item label="版本号" required><el-input v-model="definition.versionLabel" :disabled="version >= 0" maxlength="64" /></el-form-item></el-col>
<el-col :span="12"><el-form-item label="发布机构"><el-input v-model="definition.publisher" maxlength="160" /></el-form-item></el-col>
<el-col :span="24"><el-form-item label="变更说明"><el-input v-model="definition.description" type="textarea" maxlength="2000" /></el-form-item></el-col>
</el-row>
<div class="mb-3"><el-button icon="Plus" :disabled="definition.resources.length >= 50" @click="addResource">增加资源表</el-button></div>
<el-tabs v-model="activeResource" type="border-card">
<el-tab-pane v-for="(resource, index) in definition.resources" :key="index" :label="resource.name || '资源表 ' + (index + 1)" :name="String(index)">
<el-row :gutter="16"><el-col :span="10"><el-form-item label="资源编码" required><el-input v-model="resource.code" maxlength="128" /></el-form-item></el-col><el-col :span="10"><el-form-item label="资源名称" required><el-input v-model="resource.name" maxlength="160" /></el-form-item></el-col><el-col :span="4"><el-button type="danger" plain :disabled="definition.resources.length <= 1" @click="removeResource(index)">删除资源表</el-button></el-col></el-row>
<div class="toolbar-shell mb-3"><span>目标字段(按下表顺序保存)</span><el-button icon="Plus" :disabled="resource.fields.length >= 500" @click="resource.fields.push(blankField())">增加字段</el-button></div>
<el-table :data="resource.fields" border max-height="420">
<el-table-column label="字段名" min-width="160"><template #default="{ row: field }"><el-input v-model="field.name" maxlength="128" /></template></el-table-column>
<el-table-column label="字段说明" min-width="150"><template #default="{ row: field }"><el-input v-model="field.label" maxlength="160" /></template></el-table-column>
<el-table-column label="类型" width="140"><template #default="{ row: field }"><el-select v-model="field.type"><el-option v-for="type in fieldTypes" :key="type.value" :label="type.label" :value="type.value" /></el-select></template></el-table-column>
<el-table-column label="必填" width="65" align="center"><template #default="{ row: field }"><el-checkbox v-model="field.required" /></template></el-table-column>
<el-table-column label="长度" width="120"><template #default="{ row: field }"><el-input-number v-model="field.maxLength" :min="1" :max="1000000" :controls="false" class="w-full" /></template></el-table-column>
<el-table-column label="精度" width="90"><template #default="{ row: field }"><el-input-number v-model="field.precision" :min="1" :max="38" :controls="false" class="w-full" /></template></el-table-column>
<el-table-column label="小数位" width="90"><template #default="{ row: field }"><el-input-number v-model="field.scale" :min="0" :max="38" :controls="false" class="w-full" /></template></el-table-column>
<el-table-column label="操作" width="155"><template #default="{ $index }"><RowActions><el-button link :disabled="$index === 0" @click="moveField(resource, $index, -1)">上移</el-button><el-button link :disabled="$index === resource.fields.length - 1" @click="moveField(resource, $index, 1)">下移</el-button><el-button type="danger" link :disabled="resource.fields.length <= 1" @click="resource.fields.splice($index, 1)">删除</el-button></RowActions></template></el-table-column>
</el-table>
<el-form-item class="mt-4" label="目标模板"><el-tag :type="resource.templateId ? 'success' : 'info'">{{ resource.templateId ? '已绑定' : '未导入' }}</el-tag><el-button class="ml-3" @click="openImport(index)">{{ resource.templateId ? '替换模板' : '导入 XML 模板' }}</el-button></el-form-item>
</el-tab-pane>
</el-tabs>
</el-form>
<template v-if="saved && !editing">
<h4 class="mt-4 mb-3">目标模板一致性</h4>
<el-table :data="saved.differences" border>
<el-table-column prop="resourceCode" label="资源编码" width="170" />
<el-table-column label="检查结果" min-width="240"><template #default="{ row }"><span v-if="!row.result">尚未导入目标模板</span><template v-else><div>模板缺少:{{ row.result.missingFromTemplate.join('、') || '无' }}</div><div>模板多出:{{ row.result.extraInTemplate.join('、') || '无' }}</div><div>共同字段顺序:{{ row.result.orderMismatch ? '不一致' : '一致' }}</div></template></template></el-table-column>
<el-table-column label="模板内容 SHA256" min-width="230" show-overflow-tooltip><template #default="{ row }">{{ row.templateSha256 || '--' }}</template></el-table-column>
</el-table>
<el-alert v-if="saved.differenceConfirmation" type="warning" :title="'已确认差异:' + saved.differenceConfirmation" :closable="false" class="mt-3" />
<template v-if="saved.status === 'DRAFT'"><el-alert type="info" title="发布后该版本内容冻结,后续调整需新建版本。" :closable="false" class="mt-3" /><el-input v-if="saved.differences.some(hasDifference)" v-model="confirmation" type="textarea" :rows="3" maxlength="1000" show-word-limit placeholder="核对以上差异后填写确认说明;系统不会自动补齐或删除字段" class="mt-3" /></template>
<h4 class="mt-4 mb-3">操作审计</h4>
<el-table v-loading="auditLoading" :data="audits" border empty-text="暂无审计记录">
<el-table-column label="操作" min-width="160"><template #default="{ row }">{{ auditLabel(row.action) }}</template></el-table-column>
<el-table-column prop="actorId" label="操作人 ID" min-width="160" /><el-table-column prop="version" label="版本" width="80" />
<el-table-column label="原因或确认说明" min-width="200" show-overflow-tooltip><template #default="{ row }">{{ row.reason || '--' }}</template></el-table-column>
<el-table-column label="时间" width="170"><template #default="{ row }">{{ parseTime(row.occurredAt) || '--' }}</template></el-table-column>
</el-table>
<pagination v-show="auditTotal > 0" v-model:page="auditPage" v-model:limit="auditSize" :total="auditTotal" @pagination="loadAudit" />
</template>
<template #footer><div class="dialog-footer"><el-button v-if="editing" type="primary" :loading="saving" @click="save">保存并检查</el-button><el-button v-if="saved?.status === 'DRAFT' && !editing" v-hasPermi="[prefix + 'standard']" type="primary" :loading="saving" :disabled="saved.differences.some(d => !d.result) || (saved.differences.some(hasDifference) && !confirmation.trim())" @click="publish">确认发布</el-button><el-button v-if="saved?.status === 'PUBLISHED' && !editing" v-hasPermi="[prefix + 'standard']" type="danger" plain :loading="saving" @click="disable">停用版本</el-button><el-button :disabled="saving" @click="visible = false">关闭</el-button></div></template>
</el-drawer>
<el-dialog v-model="importVisible" title="导入目标 XML 模板" width="660px" append-to-body :close-on-click-modal="false" :show-close="!importing" :close-on-press-escape="!importing">
<el-form label-width="100px" :disabled="importing"><el-form-item label="模板文件"><input ref="fileInput" type="file" accept=".xml,text/xml,application/xml" :disabled="importing" @change="readFile" /></el-form-item><el-form-item label="记录节点名"><el-input v-model="recordElement" maxlength="128" placeholder="填写模板中包裹一条记录的节点名" /></el-form-item></el-form>
<p class="text-sm">支持 UTF-8 XML 和平面字段结构,文件最大 256 KiB。导入会提取字段顺序并保存模板内容哈希。</p>
<template #footer><div class="dialog-footer"><el-button type="primary" :loading="importing" :disabled="!templateXml || !recordElement" @click="submitImport">导入</el-button><el-button :disabled="importing" @click="importVisible = false">取消</el-button></div></template>
</el-dialog>
</div>
</template>
<script setup lang="ts">
import { onMounted, reactive, ref, toRaw } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { blankStandard, blankResource, blankField, hasDifference, listStandards, getStandard, getStandardAudit, saveStandard, publishStandard, disableStandard, importTemplate } from '@/api/datagov/regulatory-reporting/standards';
import type { StandardView, StandardResource } from '@/api/datagov/regulatory-reporting/standards';
import type { Audit } from '@/api/datagov/regulatory-reporting';
import { parseTime } from '@/utils/aixun';
const prefix = 'aixun:integration:regulatory-reporting:';
const query = reactive({ keyword: '', pageNum: 1, pageSize: 20 });
const rows = ref<StandardView[]>([]), total = ref(0), loading = ref(false), failed = ref(false), showSearch = ref(true);
const visible = ref(false), editing = ref(false), saving = ref(false), id = ref(''), version = ref(-1), saved = ref<StandardView>();
const definition = ref(blankStandard()), activeResource = ref('0'), confirmation = ref('');
const audits = ref<Audit[]>([]), auditPage = ref(1), auditSize = ref(20), auditTotal = ref(0), auditLoading = ref(false);
const auditLabel = (value: string) => ({ STANDARD_CREATE: '创建标准版本', STANDARD_UPDATE: '修改草稿', STANDARD_PUBLISH: '发布标准', STANDARD_PUBLISH_CONFIRMED_DIFF: '确认差异并发布', STANDARD_DISABLE: '停用版本' })[value] || value;
const importVisible = ref(false), importing = ref(false), importIndex = ref(0), recordElement = ref(''), templateXml = ref(''), fileInput = ref<HTMLInputElement>();
const fieldTypes = [{ value: 'STRING', label: '字符串' }, { value: 'INTEGER', label: '整数' }, { value: 'DECIMAL', label: '小数' }, { value: 'DATE', label: '日期' }, { value: 'DATETIME', label: '日期时间' }, { value: 'BOOLEAN', label: '布尔' }];
const statusLabel = (status: string) => ({ DRAFT: '草稿', PUBLISHED: '已发布', DISABLED: '停用' })[status] || status;
function consistencyLabel(view: StandardView) { return view.differences.some(d => !d.result) ? '缺少模板' : view.differences.some(hasDifference) ? (view.differenceConfirmation ? '差异已确认' : '存在差异') : '一致'; }
let sequence = 0;
async function load() { const current = ++sequence; loading.value = true; failed.value = false; try { const { data } = await listStandards(query); if (current === sequence) { rows.value = data.rows; total.value = data.total; } } catch { if (current === sequence) { rows.value = []; total.value = 0; failed.value = true; } } finally { if (current === sequence) loading.value = false; } }
function search() { query.pageNum = 1; void load(); }
function reset() { query.keyword = ''; search(); }
function create() { id.value = crypto.randomUUID(); version.value = -1; definition.value = blankStandard(); saved.value = undefined; editing.value = true; activeResource.value = '0'; confirmation.value = ''; visible.value = true; }
async function open(row: StandardView, edit: boolean) { const { data } = await getStandard(row.id); id.value = data.id; version.value = data.version; saved.value = data; definition.value = structuredClone(data.definition); activeResource.value = '0'; confirmation.value = ''; editing.value = edit && data.status === 'DRAFT'; visible.value = true; auditPage.value = 1; await loadAudit(); }
async function copy(row: StandardView) { await open(row, false); id.value = crypto.randomUUID(); version.value = -1; definition.value.versionLabel = ''; saved.value = undefined; editing.value = true; }
function addResource() { definition.value.resources.push(blankResource()); activeResource.value = String(definition.value.resources.length - 1); }
function removeResource(index: number) { definition.value.resources.splice(index, 1); activeResource.value = '0'; }
function moveField(resource: StandardResource, index: number, delta: number) { const target = index + delta; if (target >= 0 && target < resource.fields.length) [resource.fields[index], resource.fields[target]] = [resource.fields[target], resource.fields[index]]; }
async function save() { if (saving.value) return; saving.value = true; try { const { data } = await saveStandard(id.value, version.value, structuredClone(toRaw(definition.value))); saved.value = data; version.value = data.version; definition.value = structuredClone(data.definition); editing.value = false; ElMessage.success('标准已保存,请核对模板差异'); auditPage.value = 1; await Promise.all([load(), loadAudit()]); } finally { saving.value = false; } }
async function publish() { if (saving.value || !saved.value) return; saving.value = true; try { const { data } = await publishStandard(id.value, version.value, confirmation.value); saved.value = data; version.value = data.version; ElMessage.success('标准版本已发布并冻结'); auditPage.value = 1; await Promise.all([load(), loadAudit()]); } finally { saving.value = false; } }
async function disable() {
if (saving.value || !saved.value) return;
const answer = await ElMessageBox.prompt('请输入停用原因,历史版本内容仍保留。', '停用标准版本', { inputValidator: value => !!value?.trim() && value.length <= 1000 || '请输入 1 至 1000 字的原因' }).catch(() => null);
if (!answer) return;
saving.value = true;
try { const { data } = await disableStandard(id.value, version.value, answer.value); saved.value = data; version.value = data.version; ElMessage.success('标准版本已停用'); auditPage.value = 1; await Promise.all([load(), loadAudit()]); } finally { saving.value = false; }
}
let auditSequence = 0;
async function loadAudit() {
const current = ++auditSequence; auditLoading.value = true; audits.value = []; auditTotal.value = 0;
try { const { data } = await getStandardAudit(id.value, auditPage.value, auditSize.value); if (current === auditSequence) { audits.value = data.rows; auditTotal.value = data.total; } } finally { if (current === auditSequence) auditLoading.value = false; }
}
function openImport(index: number) { importIndex.value = index; templateXml.value = ''; recordElement.value = definition.value.resources[index].code; if (fileInput.value) fileInput.value.value = ''; importVisible.value = true; }
async function readFile(event: Event) { const file = (event.target as HTMLInputElement).files?.[0]; templateXml.value = ''; if (!file) return; if (file.size > 262144) { ElMessage.warning('模板文件不能超过 256 KiB'); return; } try { templateXml.value = new TextDecoder('utf-8', { fatal: true }).decode(await file.arrayBuffer()); } catch { ElMessage.error('请使用 UTF-8 编码的 XML 模板'); } }
async function submitImport() { if (importing.value) return; importing.value = true; try { const { data } = await importTemplate(templateXml.value, recordElement.value); definition.value.resources[importIndex.value].templateId = data.id; importVisible.value = false; templateXml.value = ''; ElMessage.success(`已识别 ${data.fields.length} 个模板字段,保存后查看差异`); } finally { importing.value = false; } }
onMounted(load);
</script>
@@ -0,0 +1,4 @@
<template><ConfigPage kind="SYSTEM" /></template>
<script setup lang="ts">
import ConfigPage from '../ConfigPage.vue';
</script>
@@ -0,0 +1,4 @@
<template><ConfigPage kind="TOPIC" /></template>
<script setup lang="ts">
import ConfigPage from '../ConfigPage.vue';
</script>
+90 -1
查看文件
@@ -1,5 +1,5 @@
-- Fresh-install DM schema; target 8.4.4.80 Pack89.
-- Source fingerprint: 7bfa7516946e6b5a507e14f1bb5faff0bea179ed17878151f95b8c102e5ee547
-- Source fingerprint: 8247e55b7ab2e222036d2ba28674ee6956f95526a9ce7f71f18d1981f77802d2
-- @statement sys_social
CREATE TABLE sys_social (
id bigint not null comment '主键',
@@ -20560,3 +20560,92 @@ CREATE TRIGGER dg_ut_bc6344924fde92eb BEFORE UPDATE ON ing_original_file FOR EAC
IF NOT UPDATING('UPDATE_TIME') THEN :NEW.update_time := LOCALTIMESTAMP; END IF;
END;
/
-- @statement dg_reporting_config
CREATE TABLE dg_reporting_config (
config_id VARCHAR(36 CHAR) NOT NULL,
organization_id BIGINT NOT NULL,
config_kind VARCHAR(16 CHAR) NOT NULL,
config_code VARCHAR(64 CHAR) NOT NULL,
config_name VARCHAR(160 CHAR) NOT NULL,
parent_id VARCHAR(36 CHAR) NULL,
root_id VARCHAR(36 CHAR) NOT NULL,
enabled INT NOT NULL DEFAULT 0,
state_json CLOB NOT NULL,
credential_ref VARCHAR(512 CHAR) NULL,
version BIGINT NOT NULL DEFAULT 0,
command_sha256 CHAR(64 CHAR) NOT NULL,
create_dept BIGINT NOT NULL,
create_by BIGINT NOT NULL,
create_time DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
update_by BIGINT NOT NULL,
update_time DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
PRIMARY KEY (organization_id,config_id),
CONSTRAINT ck_reporting_kind CHECK (config_kind IN ('DEPARTMENT','SYSTEM','TOPIC')),
CONSTRAINT ck_reporting_enabled CHECK (enabled IN (0,1)),
CONSTRAINT ck_reporting_version CHECK (version>=0)
);
-- @statement dg_reporting_config
CREATE UNIQUE INDEX uk_reporting_code ON dg_reporting_config(organization_id,config_kind,config_code);
-- @statement dg_reporting_config
CREATE INDEX idx_reporting_parent ON dg_reporting_config(organization_id,parent_id,enabled);
-- @statement dg_reporting_config
CREATE INDEX idx_reporting_root ON dg_reporting_config(organization_id,root_id);
-- @statement dg_reporting_audit
CREATE TABLE dg_reporting_audit (
audit_id VARCHAR(36 CHAR) NOT NULL,
organization_id BIGINT NOT NULL,
object_id VARCHAR(36 CHAR) NOT NULL,
action_name VARCHAR(40 CHAR) NOT NULL,
actor_id BIGINT NOT NULL,
object_version BIGINT NOT NULL,
reason VARCHAR(1000 CHAR) NULL,
create_time DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
PRIMARY KEY (audit_id)
);
-- @statement dg_reporting_audit
CREATE INDEX idx_reporting_audit ON dg_reporting_audit(organization_id,object_id,create_time);
-- @statement dg_reporting_template
CREATE TABLE dg_reporting_template (
template_id VARCHAR(36 CHAR) NOT NULL,
organization_id BIGINT NOT NULL,
file_sha256 CHAR(64 CHAR) NOT NULL,
record_element VARCHAR(128 CHAR) NOT NULL,
fields_json CLOB NOT NULL,
create_by BIGINT NOT NULL,
create_time DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
PRIMARY KEY (organization_id,template_id)
);
-- @statement dg_reporting_template
CREATE UNIQUE INDEX uk_reporting_template ON dg_reporting_template(organization_id,file_sha256,record_element);
-- @statement dg_reporting_standard
CREATE TABLE dg_reporting_standard (
standard_id VARCHAR(36 CHAR) NOT NULL,
organization_id BIGINT NOT NULL,
standard_code VARCHAR(128 CHAR) NOT NULL,
standard_name VARCHAR(160 CHAR) NOT NULL,
version_label VARCHAR(64 CHAR) NOT NULL,
standard_status VARCHAR(16 CHAR) NOT NULL,
definition_json CLOB NOT NULL,
difference_confirmation VARCHAR(1000 CHAR) NULL,
command_sha256 CHAR(64 CHAR) NOT NULL,
version BIGINT NOT NULL DEFAULT 0,
create_by BIGINT NOT NULL,
create_time DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
update_by BIGINT NOT NULL,
update_time DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
PRIMARY KEY (organization_id,standard_id),
CONSTRAINT ck_reporting_standard_status CHECK (standard_status IN ('DRAFT','PUBLISHED','DISABLED')),
CONSTRAINT ck_reporting_standard_version CHECK (version>=0)
);
-- @statement dg_reporting_standard
CREATE UNIQUE INDEX uk_reporting_standard ON dg_reporting_standard(organization_id,standard_code,version_label);
+252
查看文件
@@ -17178,6 +17178,222 @@
null,
null,
"模型与算法知识参考库;不执行训练或推理"
],
[
1761700000000000800,
"监管数据报送",
0,
15,
"/datagov-regulatory-reporting",
"",
"",
"N",
"N",
"M",
"0",
"0",
"",
"documentation",
"",
"",
1761000000000000103,
1761100000000000001,
"2000-01-01 00:00:00",
null,
null,
"监管报送独立业务入口"
],
[
1761700000000000801,
"报送总览",
1761700000000000800,
1,
"/regulatory-reporting-overview",
"datagov/regulatory-reporting/overview/index",
"",
"N",
"N",
"C",
"0",
"0",
"aixun:integration:regulatory-reporting:view",
"dashboard",
"",
"",
1761000000000000103,
1761100000000000001,
"2000-01-01 00:00:00",
null,
null,
"当前组织真实配置统计"
],
[
1761700000000000802,
"上报部门",
1761700000000000800,
2,
"/regulatory-reporting-departments",
"datagov/regulatory-reporting/departments/index",
"",
"N",
"N",
"C",
"0",
"0",
"aixun:integration:regulatory-reporting:view",
"tree-table",
"",
"",
1761000000000000103,
1761100000000000001,
"2000-01-01 00:00:00",
null,
null,
"监管部门管理"
],
[
1761700000000000803,
"上报系统",
1761700000000000800,
3,
"/regulatory-reporting-systems",
"datagov/regulatory-reporting/systems/index",
"",
"N",
"N",
"C",
"0",
"0",
"aixun:integration:regulatory-reporting:view",
"server",
"",
"",
1761000000000000103,
1761100000000000001,
"2000-01-01 00:00:00",
null,
null,
"上报系统管理"
],
[
1761700000000000804,
"报送主题",
1761700000000000800,
4,
"/regulatory-reporting-topics",
"datagov/regulatory-reporting/topics/index",
"",
"N",
"N",
"C",
"0",
"0",
"aixun:integration:regulatory-reporting:view",
"table",
"",
"",
1761000000000000103,
1761100000000000001,
"2000-01-01 00:00:00",
null,
null,
"报送主题管理"
],
[
1761700000000000805,
"报送标准",
1761700000000000800,
5,
"/regulatory-reporting-standards",
"datagov/regulatory-reporting/standards/index",
"",
"N",
"N",
"C",
"0",
"0",
"aixun:integration:regulatory-reporting:view",
"documentation",
"",
"",
1761000000000000103,
1761100000000000001,
"2000-01-01 00:00:00",
null,
null,
"标准版本及目标模板"
],
[
1761700000000000806,
"编辑报送配置",
1761700000000000802,
1,
"",
"",
"",
"N",
"N",
"F",
"0",
"0",
"aixun:integration:regulatory-reporting:edit",
"#",
"",
"",
1761000000000000103,
1761100000000000001,
"2000-01-01 00:00:00",
null,
null,
"创建修改停用部门系统主题"
],
[
1761700000000000807,
"绑定报送凭据",
1761700000000000803,
1,
"",
"",
"",
"N",
"N",
"F",
"0",
"0",
"aixun:integration:regulatory-reporting:credential",
"#",
"",
"",
1761000000000000103,
1761100000000000001,
"2000-01-01 00:00:00",
null,
null,
"只绑定受管引用"
],
[
1761700000000000808,
"管理报送标准",
1761700000000000805,
1,
"",
"",
"",
"N",
"N",
"F",
"0",
"0",
"aixun:integration:regulatory-reporting:standard",
"#",
"",
"",
1761000000000000103,
1761100000000000001,
"2000-01-01 00:00:00",
null,
null,
"创建标准导入模板及确认发布"
]
]
},
@@ -19754,6 +19970,42 @@
[
1761300000000000001,
1761400000000000108
],
[
1761300000000000001,
1761700000000000800
],
[
1761300000000000001,
1761700000000000801
],
[
1761300000000000001,
1761700000000000802
],
[
1761300000000000001,
1761700000000000803
],
[
1761300000000000001,
1761700000000000804
],
[
1761300000000000001,
1761700000000000805
],
[
1761300000000000001,
1761700000000000806
],
[
1761300000000000001,
1761700000000000807
],
[
1761300000000000001,
1761700000000000808
]
]
},
+8
查看文件
@@ -1078,3 +1078,11 @@ migrations:
ownerUnit: system
path: db/migration/system/V20261112.276__combine_log_management_tabs.sql
sha256: 3df45717e655d1ed2e5795630b09feb9a3c805236a329c497f9965643288a8f0
- version: '20261124.277'
ownerUnit: integration
path: db/migration/integration/V20261124.277__create_regulatory_reporting.sql
sha256: 6cd233f9de3e71f0d276423bccd7e9543ba5766d53ba1e23f30822b53b6d8130
- version: '20261124.278'
ownerUnit: system
path: db/migration/system/V20261124.278__register_regulatory_reporting.sql
sha256: f1a7729b7f5a082442c967e125a83c7193b6c921003679222db3d504bfed0f05
@@ -0,0 +1,73 @@
-- Reporting configuration is scoped to the authenticated organization. No target data is seeded.
CREATE TABLE dg_reporting_config (
config_id VARCHAR(36) NOT NULL,
organization_id BIGINT NOT NULL,
config_kind VARCHAR(16) NOT NULL,
config_code VARCHAR(64) NOT NULL,
config_name VARCHAR(160) NOT NULL,
parent_id VARCHAR(36) NULL,
root_id VARCHAR(36) NOT NULL,
enabled INT NOT NULL DEFAULT 0,
state_json LONGTEXT NOT NULL,
credential_ref VARCHAR(512) NULL,
version BIGINT NOT NULL DEFAULT 0,
command_sha256 CHAR(64) NOT NULL,
create_dept BIGINT NOT NULL,
create_by BIGINT NOT NULL,
create_time DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
update_by BIGINT NOT NULL,
update_time DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
PRIMARY KEY (organization_id,config_id),
UNIQUE KEY uk_reporting_code (organization_id,config_kind,config_code),
KEY idx_reporting_parent (organization_id,parent_id,enabled),
KEY idx_reporting_root (organization_id,root_id),
CONSTRAINT ck_reporting_kind CHECK (config_kind IN ('DEPARTMENT','SYSTEM','TOPIC')),
CONSTRAINT ck_reporting_enabled CHECK (enabled IN (0,1)),
CONSTRAINT ck_reporting_version CHECK (version>=0)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
CREATE TABLE dg_reporting_audit (
audit_id VARCHAR(36) NOT NULL,
organization_id BIGINT NOT NULL,
object_id VARCHAR(36) NOT NULL,
action_name VARCHAR(40) NOT NULL,
actor_id BIGINT NOT NULL,
object_version BIGINT NOT NULL,
reason VARCHAR(1000) NULL,
create_time DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
PRIMARY KEY (audit_id),
KEY idx_reporting_audit (organization_id,object_id,create_time)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
CREATE TABLE dg_reporting_template (
template_id VARCHAR(36) NOT NULL,
organization_id BIGINT NOT NULL,
file_sha256 CHAR(64) NOT NULL,
record_element VARCHAR(128) NOT NULL,
fields_json LONGTEXT NOT NULL,
create_by BIGINT NOT NULL,
create_time DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
PRIMARY KEY (organization_id,template_id),
UNIQUE KEY uk_reporting_template (organization_id,file_sha256,record_element)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
CREATE TABLE dg_reporting_standard (
standard_id VARCHAR(36) NOT NULL,
organization_id BIGINT NOT NULL,
standard_code VARCHAR(128) NOT NULL,
standard_name VARCHAR(160) NOT NULL,
version_label VARCHAR(64) NOT NULL,
standard_status VARCHAR(16) NOT NULL,
definition_json LONGTEXT NOT NULL,
difference_confirmation VARCHAR(1000) NULL,
command_sha256 CHAR(64) NOT NULL,
version BIGINT NOT NULL DEFAULT 0,
create_by BIGINT NOT NULL,
create_time DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
update_by BIGINT NOT NULL,
update_time DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
PRIMARY KEY (organization_id,standard_id),
UNIQUE KEY uk_reporting_standard (organization_id,standard_code,version_label),
CONSTRAINT ck_reporting_standard_status CHECK (standard_status IN ('DRAFT','PUBLISHED','DISABLED')),
CONSTRAINT ck_reporting_standard_version CHECK (version>=0)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
@@ -0,0 +1,23 @@
-- Independent navigation; only the existing DataGov superadmin receives initial privileges.
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
START TRANSACTION;
CREATE TEMPORARY TABLE tmp_reporting278_guard(id INT PRIMARY KEY);
INSERT INTO tmp_reporting278_guard VALUES(1);
INSERT INTO tmp_reporting278_guard SELECT 1 WHERE
(SELECT COUNT(*) FROM sys_role WHERE role_id=1761300000000000001 AND role_key='superadmin' AND status='0' AND del_flag='0')<>1
OR EXISTS(SELECT 1 FROM sys_menu WHERE menu_id BETWEEN 1761700000000000800 AND 1761700000000000808)
OR EXISTS(SELECT 1 FROM sys_menu WHERE path='/datagov-regulatory-reporting' OR perms LIKE 'aixun:integration:regulatory-reporting:%');
INSERT INTO sys_menu(menu_id,menu_name,parent_id,order_num,path,component,query_param,is_frame,is_cache,menu_type,visible,status,perms,icon,active_menu,ext,create_dept,create_by,create_time,remark) VALUES
(1761700000000000800,'监管数据报送',0,15,'/datagov-regulatory-reporting','','','N','N','M','0','0','','documentation','','',1761000000000000103,1761100000000000001,NOW(),'监管报送独立业务入口'),
(1761700000000000801,'报送总览',1761700000000000800,1,'/regulatory-reporting-overview','datagov/regulatory-reporting/overview/index','','N','N','C','0','0','aixun:integration:regulatory-reporting:view','dashboard','','',1761000000000000103,1761100000000000001,NOW(),'当前组织真实配置统计'),
(1761700000000000802,'上报部门',1761700000000000800,2,'/regulatory-reporting-departments','datagov/regulatory-reporting/departments/index','','N','N','C','0','0','aixun:integration:regulatory-reporting:view','tree-table','','',1761000000000000103,1761100000000000001,NOW(),'监管部门管理'),
(1761700000000000803,'上报系统',1761700000000000800,3,'/regulatory-reporting-systems','datagov/regulatory-reporting/systems/index','','N','N','C','0','0','aixun:integration:regulatory-reporting:view','server','','',1761000000000000103,1761100000000000001,NOW(),'上报系统管理'),
(1761700000000000804,'报送主题',1761700000000000800,4,'/regulatory-reporting-topics','datagov/regulatory-reporting/topics/index','','N','N','C','0','0','aixun:integration:regulatory-reporting:view','table','','',1761000000000000103,1761100000000000001,NOW(),'报送主题管理'),
(1761700000000000805,'报送标准',1761700000000000800,5,'/regulatory-reporting-standards','datagov/regulatory-reporting/standards/index','','N','N','C','0','0','aixun:integration:regulatory-reporting:view','documentation','','',1761000000000000103,1761100000000000001,NOW(),'标准版本及目标模板'),
(1761700000000000806,'编辑报送配置',1761700000000000802,1,'','','','N','N','F','0','0','aixun:integration:regulatory-reporting:edit','#','','',1761000000000000103,1761100000000000001,NOW(),'创建修改停用部门系统主题'),
(1761700000000000807,'绑定报送凭据',1761700000000000803,1,'','','','N','N','F','0','0','aixun:integration:regulatory-reporting:credential','#','','',1761000000000000103,1761100000000000001,NOW(),'只绑定受管引用'),
(1761700000000000808,'管理报送标准',1761700000000000805,1,'','','','N','N','F','0','0','aixun:integration:regulatory-reporting:standard','#','','',1761000000000000103,1761100000000000001,NOW(),'创建标准导入模板及确认发布');
INSERT INTO sys_role_menu(role_id,menu_id)
SELECT 1761300000000000001,menu_id FROM sys_menu WHERE menu_id BETWEEN 1761700000000000800 AND 1761700000000000808;
COMMIT;
DROP TEMPORARY TABLE tmp_reporting278_guard;
@@ -0,0 +1,100 @@
# 监管数据报送开发交付(2026-11-24)
本轮结果:PASS_WITH_LIMITATION。已实现并部署基础配置及标准版本管理;整个监管报送模块尚未完成,不能执行真实报送。用户授权来源:本会话提供产品实施方案后要求“你直接开始开发”“继续”,随后明确要求“部署一下本地的 docker 上”。本次仅更新本地 DataGov Integration、前端及其专属达梦 schema 的必要增量,没有发布生产环境。
## 已实现
- 独立一级导航“监管数据报送”,下设报送总览、上报部门、上报系统、报送主题、报送标准。未实现的任务、执行和记录页面未挂空菜单。
- 部门、系统、主题分页搜索、创建、编辑、启停和审计;编码、对象类型和所属关系创建后固定;没有物理删除接口。上级停用与子对象启用在同一部门根对象事务锁下协调。
- 配置仅查询当前登录组织。组织和操作人来自 RCP6 登录身份,客户端不能指定;集团跨组织授权汇总及主题级授权尚未实现,不能把当前组织隔离说成已完成全部多组织需求。
- 系统配置环境、HTTP POST、地址、认证方式、超时、重试上限、版本、命名规则和目标能力声明。这些是配置,尚无真实连接测试或传输执行。地址禁止嵌入用户信息、查询参数和片段。
- 凭据只保存带版本的现有 `SecretRef` 引用,响应仅返回是否配置;修改绑定有独立权限和审计,操作日志不保存请求/响应正文。当前仅校验引用语法,未读取秘密、验证引用可用性或证明环境对应关系。
- 标准编码与版本唯一;支持多资源表、目标字段名称/说明/类型、必填、长度/精度/小数位和顺序。支持草稿编辑、复制新版本、发布冻结和停用;发布后不可覆盖内容。
- XML 模板导入提取实际字段与顺序、计算 UTF-8 解码后模板文本 SHA256,持久保存不可变模板结构引用;不保存样例记录值。此哈希是模板文本哈希,不声称是原文件字节哈希。仅支持 UTF-8 平面字段模板,最大文件 256 KiB;嵌套、命名空间或其他格式模板需要适配。DTD/外部实体被拒绝。
- 标准页面展示模板缺少、多出和共同字段顺序差异;缺少模板禁止发布;存在差异须有标准管理权限并明确填写确认说明。确认不修改字段,不代表目标接口会接受该标准。
- 写入使用稳定 UUID、版本检查及命令 SHA256;同一原请求重放不重复写入/审计。标准发布、停用和凭据绑定都有事务内审计;发布差异确认和停用原因可读回。
## 复用与尚缺能力
复用现有 Integration 服务、RCP6 登录/菜单权限/审计、JdbcTemplate 事务、JsonMapper、SecretRef、RCP6 查询/表格/分页/Dialog/Drawer。未新增微服务、依赖框架或通用质量引擎。
已核查 DataProduct `PublishedDatasetCatalog`、`DataExchangeDatasetReferenceDirectory`、`PublishedApiExecutionOwner` 和受控 `BiQuerySource`。已有数据集目录及结构/来源权限校验可复用,但目录不是完整数据读取契约。API 调试路径限制每页 100 行、前 1000 行;BI 表读取另有 BI 权限和截断语义。后续报送读取需独立绑定发布版本、沿用源权限和脱敏策略、检查完整性,不能扩大现有接口上限后视为解决,也不能把截断结果生成正式批次。
未实现:主题—多系统/标准版本关联、字典及版本引用、字典和字段映射、规范文件资源存储、生效/失效日期、测试态标准、任务和数据集绑定、专项过滤、记录级校验、业务审核、批次快照、GUID映射、文件生成/附件ZIP、B接口传输、回执解析、重试对账、目标端核验、业务运行总览。这些是后续工程工作,并非已经实现但未验证。
国资委试点另缺:V1.2 完整字段/字典规范、企业侧当前 B 接口导出模板、APRCAWARD 原试点映射/报文/脚本、测试端参数契约和 DS 核验方式。本次没有伪造15张表字段、试点成功记录或正式业务数据。
## 文件与迁移
- 后端:`aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/regulatoryreporting/`,对应测试同名目录。
- 前端:`aixun-ui/src/api/datagov/regulatory-reporting/`、`aixun-ui/src/views/datagov/regulatory-reporting/`;导航仅在 `src/layout/navigation/groups.ts` 增加对应根目录归组。
- 277:四张配置/审计/模板/标准表。278:1个目录、5个页面、3个按钮权限,只授给既有 DataGov superadmin,不为普通角色自动扩权。
- `db/migration/catalog.yml` 注册校验和;`db/dameng/schema.sql`、`db/dameng/seed.json` 通过既有脚本重新生成,并核查4张表、9个菜单/按钮记录及9个 superadmin 关联。
- 达梦全新部署产物已更新;现有实例通过 `script/database/reporting-dameng-increment.py` 和 `ReportingMenuMigration.java` 精确应用本次增量,没有重放全量 seed。DDL 复用现有逐语句日志;菜单和权限在同一事务中新增,并核对内容及迁移摘要。只读 verify 已确认4表、6索引、9菜单、9关联和10条DDL成功日志。
## 验证
| 范围 | 结果 | 证据/限制 |
| --- | --- | --- |
| 后端定向编译和单测 | PASS | 27项通过;随后新增发布/停用正向用例2项通过,合计29项不同用例 |
| 前端定向lint | PASS | 新API、新页面、导航及生成声明检查通过 |
| 导航单测 | PASS | 5项,包括独立分组和无授权子页时隐藏 |
| 类型检查 | PASS_WITH_LIMITATION | 本次目录与导航0项错误;全局vue-tsc仍有111项其他文件错误,不能报告全局通过 |
| 达梦生成及离线核对 | PASS | 639张总表、1940条schema语句;校验全部catalog哈希和本次菜单归属;不是数据库执行验证 |
| 后端打包/前端生产构建 | PASS | Integration可执行JAR包含新控制器;前端1598个文件包含新导航、页面及最终文案;无额外打包副本 |
| 实际达梦SQL/事务/并发验证 | PASS_WITH_LIMITATION | 增量DDL、菜单事务、读回及5个报送查询接口通过;业务写入、发布、审计、并发行为仍NOT_RUN,不能以空列表查询替代 |
| 本地部署/迁移 | PASS_WITH_LIMITATION | 两个容器制品读回PASS、迁移PASS;Integration启动期两次JVM原生崩溃后自动恢复,详情见下文 |
| Browser/RBAC/人工功能验收 | NOT_RUN | 页面源码与构建不等于交互验收 |
| 真实报送/目标端入库 | NOT_RUN | 执行链未实现,未调用监管接口 |
主要命令:
```sh
./script/quality/check.sh --backend aixun-modules/aixun-integration 'TemplateConsistencyTest,Reporting*Test'
./script/quality/check.sh --backend aixun-modules/aixun-integration 'ReportingStandardServiceTest#confirmedDifferenceCanPublishWithAuditedReason+disablingRetainsDefinitionAndRequiresReason'
./script/quality/check.sh --frontend src/api/datagov/regulatory-reporting src/views/datagov/regulatory-reporting src/layout/navigation/groups.ts src/layout/navigation/groups.test.ts
# 固定工具链已由script/toolchain/bootstrap-node.sh加载
pnpm --dir aixun-ui exec vitest run src/layout/navigation/groups.test.ts
pnpm --dir aixun-ui exec vue-tsc --noEmit --pretty false
./script/quality/check.sh --frontend-build
./mvnw -B -pl aixun-modules/aixun-integration -am package -DskipTests
python3 script/database/build-dameng-baseline.py
python3 script/database/build-dameng-seed.py
```
打包时跳过重复测试,采用前面已执行的定向测试结果;没有执行全业务回归。前端因最后一处文案修正重新构建,以最终构建为准。首轮凭据无协议头输入触发异常,已在报送入口修正并通过定向复测。
最终制品身份:
- `aixun-modules/aixun-integration/target/aixun-integration.jar`,SHA256:`3e551fe459dc9f2e3db0cad16809d3c5b945610721aef3df279db7f266ad9791`。
- `aixun-ui/dist/`,1598个文件,目录摘要:`3b2a9d37b82f036f07609394bfe8fd902cc2dbddb51e00cf112b72456a73be78`。算法:按相对路径排序,把每个文件的“相对路径 + NUL + 文件SHA256十六进制 + 换行”以UTF-8串联,再取SHA256。
- 制品内容和运行容器读回核查通过;本地部署不等于人工功能验收。
## 本地 Docker 发布
- 访问:`http://localhost:28000`。超级管理员重新登录后可看到“监管数据报送”及5个子页;普通角色没有自动获得新增权限。
- release:`regulatory-reporting-20261124`。通过两个现有 Dockerfile 构建,只应用 Integration 和 frontend 的局部 plan/apply。网络、IP、挂载、端口、秘密及非镜像配置保持原值。
- Integration 镜像:`sha256:5ed74397796aedf65b1530767a7b13928b5a427eb858b4dff10a733533885289`;容器:`78181755a73ae75e8bb6aa3e5de511575dc4d0282e3ee4361b4ab4b6b320dbc1`。
- 前端镜像:`sha256:223093aa5ba49f3adf19f5635c9208e6eea449e6d98a28a15653f2d7965ff22e`;容器:`53b9a68245f716e37058e2ab8a0c9c37b9488c790cad0bb970217f376fdb13cc`。
- 计划及自动结果:`script/datagov/deployment/releases/regulatory-reporting-20261124-{integration,frontend}{,-attempt,-result}.json`。两项 `artifactReadback=PASS`;工具结果中的 `applicationReadiness=NOT_RUN` 是工具本身边界,后续人工发起的接口检查记录在本段。
- 启动异常:Integration 初始启动两次 SIGSEGV,问题帧为 `libjvm.so` 的 `OopOopIterateDispatch<YoungGenScanClosure>`,随后自动恢复。新旧镜像基础层、Java版本(21.0.12.1)及SerialGC配置一致,未修改JVM参数;不能据此断言崩溃根因已解决。重启计数固定为2后完成下述读回,运行稳定性保留限制。
- 运行验证:带现有受管鉴权的 `/actuator/health` 返回HTTP200/UP;Nacos中Integration健康且启用实例1个;未登录报送查询拒绝(业务码401);登录、菜单读取、退出均业务码200;总览、部门、系统、主题及标准列表均业务码200,新列表为空;原有数据源查询业务码200。首次在服务启动期间的查询为404,恢复后以上查询通过。
- 未执行浏览器交互、普通角色RBAC矩阵、业务新增/编辑/发布和真实报送,不把只读API检查记为完整功能验收。
- 最终复核:两个服务 `--check-config` 均PASS;Integration恢复后连续运行171秒、重启计数仍为2,总览再次返回200;前端连续运行209秒、重启0次、入口HTTP200。该短观察窗口不代表长期稳定性已验证。
部署命令(连接秘密仅经私有环境辅助脚本传递):
```sh
python3 script/database/with-dameng-env.py --config runtime/dev-private/dameng-test.json -- python3 script/database/reporting-dameng-increment.py preflight
python3 script/database/with-dameng-env.py --config runtime/dev-private/dameng-test.json -- python3 script/database/reporting-dameng-increment.py apply
python3 script/database/with-dameng-env.py --config runtime/dev-private/dameng-test.json -- python3 script/database/reporting-dameng-increment.py verify
# Integration 的下列两条命令同样经 with-dameng-env.py 包装
./script/datagov/deploy.sh --plan integration regulatory-reporting-20261124 aixun-datagov/integration:regulatory-reporting-20261124 --artifact aixun-modules/aixun-integration/target/aixun-integration.jar
./script/datagov/deploy.sh --apply integration regulatory-reporting-20261124 --authorized-by '用户在当前会话要求部署本轮监管数据报送到本地Docker'
./script/datagov/deploy.sh --plan frontend regulatory-reporting-20261124 aixun-datagov/frontend:regulatory-reporting-20261124 --artifact aixun-ui/dist
./script/datagov/deploy.sh --apply frontend regulatory-reporting-20261124 --authorized-by '用户在当前会话要求部署本轮监管数据报送到本地Docker'
```
## 恢复
已保留部署前镜像:Integration `sha256:c94bec7bea27914e85aab5e9b87d4c781f3e8fb92a8610ca2234e1bdec986a4a`;前端 `sha256:7ea0a8e61a38edfae7cc918aa13f2ace07e592215de77f2ae3ad4beba4278aa9`。需要恢复时通过现有 deploy.sh 为上述确切镜像重新plan/apply,保持拓扑与秘密;默认保留新增表、数据、迁移和审计记录,必要时仅禁用本次精确菜单ID 1761700000000000800—1761700000000000808,不DROP表、不重放全量seed。保护备份未访问、未改写。
@@ -0,0 +1,61 @@
# 采集字段类型兼容修复(2026-11-24)
用户要求修复数据采集映射页的LONGTEXT错误,并明确范围为当前支持的所有数据库。结果:PASS_WITH_LIMITATION。覆盖MySQL、SQL Server、Oracle、达梦、金仓的常见标量及扩展类型;不承诺任意厂商自定义对象都能自动转换,也不把类型兼容等同于无限字段容量。
## 行为与文件
- `aixun-api/aixun-api-integration/.../datasource/BatchTextTypes.java`:统一扩展类型的目标载体和源SQL转换;`DataSourceObjects.java`作为所有建表、映射及执行校验入口复用。
- 长文本(含LONGTEXT、MEDIUMTEXT、CLOB/NCLOB、SQL Server MAX/TEXT)映射STRING,按实际内容采集,不再因声明最大容量拒绝整张表。
- MySQL二进制、空间类型使用HEX;SQL Server IMAGE/大VARBINARY使用十六进制转换,空间类型使用含SRID的Serialize;Oracle/达梦BLOB及金仓BYTEA等通过JDBC bytes和SeaTunnel RAWTOHEX编码。无SUBSTR/LEFT截断。
- JSON/XML、枚举/集合、时间间隔、时区/超微秒时间、超出公共DECIMAL精度的数值等采用显式文本表示;Oracle数值格式固定小数点,避免依赖会话NLS小数分隔符。金仓数组及网络等扩展类型使用数据库文本表示。目标不会继承源枚举约束、对象类型运算、空间索引或数值计算语义。
- `aixun-modules/aixun-integration/.../batchingestion/M3CollectionJobFactory.java`:实际查询转换与schema一致,二进制大对象用独立SQL编码步骤;Doris JDBC显式启用`enable_insert_strict=true`,不接受过滤坏行后假成功。批次失败可能已有先前批量写入,沿用既有UNKNOWN/对账逻辑,不自动重跑。
- `aixun-api/aixun-api-dataops/.../UnifiedIngestionApi.java`新增逐字段兼容说明(保留旧构造方法);`aixun-modules/aixun-dataops/.../UnifiedIngestionService.java`保留完整结构指纹,并返回可用字段和不能处理的字段原因。
- `aixun-ui/src/views/datagov/dataops/unified-ingestion/index.vue`及对应API types:显示真实源类型、保存方式和逐字段原因。遇到不能处理的字段须打开选择框明确确认剩余范围,不能静默跳过;全部字段不可用时不能提交。
- 组织权限、凭据、源/目标版本核对、采集节点和数据库开放范围保持。没有数据库迁移。
## 验证
- 90项不同后端定向用例最终通过,覆盖5库类型矩阵、实际任务SQL/schema、目标容量兼容、历史映射、结构指纹和不支持字段隔离。测试报告在两个模块现有`target/surefire-reports`。
- 前端相关Vue/types定向lint及生成声明检查通过,生产构建通过。全局vue-tsc退出2、111项既有其他目录错误;本次unified-ingestion页面/API范围0错误,不能报告全局通过。
- `script/quality/BatchCarrierProbe.java`通过现有达梦专属连接执行只读常量查询:高精度数值、纳秒格式时间、日期、10万字符CLOB、包含00/80/FF字节的BLOB共5项通过。未读写业务表。
- 在归属明确的本地`aixun-datagov-m2-seatunnel`中调用现有2.3.13 SQL引擎:RAWTOHEX对NULL、空字节数组、边界字节及10万字节样本4项通过,编码可逆。临时Java文件已删除,没有改镜像、配置或重启节点。
- Integration/DataOps合并Maven打包通过,前端生产构建通过;本次未新增依赖、未clean或重装。
- 本地两处已授权MySQL源各选一张已有表,对Hive和Doris生成只读草稿,共4次接口业务码200;分别完整返回15及7个字段、对应映射和逐字段说明,无表级错误或不支持字段。没有提交采集、创建目标表或写入业务数据。本地两个可用MySQL源均未查到截图的`tpms_achievement_award_maintain`,不能推导截图远端表已采集成功。
- 复核补充金仓无长度声明/超大VARCHAR、CHARACTER VARYING等字符字段的完整文本载体;不是把未知厂商对象无条件转字符串。
- 未进行所有五库×全部类型×Hive/Doris的真实端到端写入;尤其自定义对象、BFILE、SQL_VARIANT等无确定序列化规则的类型仍逐字段提示,不伪造支持。二进制大对象仅开放原值采集和空值过滤,文本转换/内容过滤须源视图处理。
- Doris容量、关键列限制及连接/内存上限仍有效;扩展字段改用STRING不能作为Doris首个关键列。超大实际值可能失败,不承诺4GB LONGTEXT必然能写入目标。
主要命令:
```sh
./script/quality/check.sh --backend aixun-modules/aixun-integration,aixun-modules/aixun-dataops 'MysqlTargetTypeMatrixTest,*BatchTypesTest,M3SeaTunnelCollectionContractTest,M3BatchTemporalPrecisionTest,M3BatchTargetVerifierTest,BatchTargetTypePolicyTest,BatchTargetWizardTest,UnifiedIngestionContractTest'
./script/quality/check.sh --backend aixun-modules/aixun-integration,aixun-modules/aixun-dataops 'MysqlTargetTypeMatrixTest,BatchExtendedTypesTest,BatchTargetTypePolicyTest,BatchTargetWizardTest,UnifiedIngestionContractTest,UnifiedIngestionTypeCompatibilityTest,UnifiedIngestionRecoveryTest'
./script/quality/check.sh --backend aixun-modules/aixun-dataops BatchTargetTypePolicyTest
./script/quality/check.sh --backend aixun-modules/aixun-integration,aixun-modules/aixun-dataops 'BatchExtendedTypesTest,KingbaseBatchTypesTest,BatchTargetTypePolicyTest'
./script/quality/check.sh --frontend src/views/datagov/dataops/unified-ingestion/index.vue src/api/datagov/unified-ingestion/types.ts
./mvnw -B -pl aixun-modules/aixun-integration,aixun-modules/aixun-dataops -am package -DskipTests
./script/quality/check.sh --frontend-build
python3 script/database/with-dameng-env.py --config runtime/dev-private/dameng-test.json -- java --class-path script/datagov/m2/seatunnel/local/artifacts/DmJdbcDriver18-8.1.3.62.jar script/quality/BatchCarrierProbe.java dameng
```
首轮旧测试仍断言扩展类型必须拒绝,另有一项测试辅助方法不能处理不带长度的VARCHAR;已随新行为修正并定向复测,最终上述90项全部通过。
## 发布与恢复
本地局部release:frontend为`ingestion-types-20261124`,Integration和DataOps最终为`ingestion-types-20261124-r2`。r2补充金仓无界字符字段后,19项相关用例再次通过(包含在90项不同用例内,不重复累计),后端合并打包通过。沿用本会话本地部署请求和本次修复授权;截图远端`data.jxdig.com:8443`未发布。计划/执行结果保存在`script/datagov/deployment/releases/ingestion-types-20261124-*`,不重复保存镜像包或构建日志。
最终本地制品:
| 服务 | 镜像SHA256 | JAR SHA256或前端目录摘要 |
| --- | --- | --- |
| Integration | `83b9a7de4fb08887ef9fb7ecdfa9d650df6b8f7a54f5b401f9f3729f65d64542` | `e51a0c7aa9a5248041c0aa5f62a0c1b803f5acc52f6d1429b58b32d8132ad836` |
| DataOps | `e32d537daefee362b9569b9bee5344c18d8f0fe0a1619c4f887f1c54c802ca6d` | `1188aecabf2ad2d71792357a401723981067ef24e7331f57b311787fee23556d` |
| frontend | `8ea621f3309f0bf0a8b943a42edb9ec2d7d9d457ae41f131ed38ee7c94d4d4b3` | `89aefa98e37e6af180be15825b7c77cd526bcefb915ba000bd5f7253d47388eb` |
三个服务的部署制品读回和`deploy.sh --check-config`均PASS,最终容器running、重启次数0。Integration/DataOps鉴权健康端点HTTP 200且UP;最终版本采集数据源入口和监管报送overview接口业务码200。访问入口:`http://localhost:28000/unified-ingestion`。没有迁移、整栈重启或远端发布。部署状态为PASS_WITH_LIMITATION:浏览器人工流程、五库全部类型真实采集写入均NOT_RUN。
部署使用`python3 script/database/with-dameng-env.py --config runtime/dev-private/dameng-test.json -- ./script/datagov/deploy.sh --apply <service> ingestion-types-20261124-r2 --authorized-by <本会话授权来源>`(两个后端分别顺序执行),frontend沿用首轮已通过的制品。r2执行结果另记录首轮后端镜像作为直接恢复引用;不打印私密配置,也不清除仍被恢复记录引用的镜像。
发布前恢复制品:Integration `sha256:5ed74397796aedf65b1530767a7b13928b5a427eb858b4dff10a733533885289`,DataOps `sha256:45c1d8bebe6671a350ea93040c6e2fc0b87891fcf6186e495aea01ddd02c9891`,frontend `sha256:223093aa5ba49f3adf19f5635c9208e6eea449e6d98a28a15653f2d7965ff22e`。如需恢复,通过deploy.sh对确切旧镜像plan/apply;保留业务数据、记录和原配置,不回滚数据库或自动重放采集任务。恢复后新类型草稿需重新读取结构。
参考:[MySQL显式转换](https://dev.mysql.com/doc/refman/8.4/en/cast-functions.html)、[SeaTunnel 2.3.13 RAWTOHEX](https://seatunnel.apache.org/docs/2.3.13/transforms/sql-functions/)、[Doris STRING容量](https://doris.apache.org/docs/3.x/sql-manual/basic-element/sql-data-types/data-type-overview/)、[Doris严格插入](https://doris.apache.org/docs/3.x/data-operate/import/import-way/insert-into-manual/)。
@@ -0,0 +1,92 @@
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.sql.*;
import java.util.*;
/** Exact 278 increment. Existing seed rows are never updated or deleted. */
class ReportingMenuMigration {
static final String RANGE = "menu_id BETWEEN 1761700000000000800 AND 1761700000000000808";
static final String KEY = "migration:20261124.278:reporting-menu";
static int tables(Connection c, String schema, boolean verifyIndexes) throws SQLException {
Map<String,Set<String>> expected=Map.of(
"DG_REPORTING_CONFIG",Set.of("UK_REPORTING_CODE","IDX_REPORTING_PARENT","IDX_REPORTING_ROOT"),
"DG_REPORTING_AUDIT",Set.of("IDX_REPORTING_AUDIT"),
"DG_REPORTING_TEMPLATE",Set.of("UK_REPORTING_TEMPLATE"),
"DG_REPORTING_STANDARD",Set.of("UK_REPORTING_STANDARD"));
int found=0;
for (var entry:expected.entrySet()) {
try (ResultSet r=c.getMetaData().getTables(null,schema,entry.getKey(),new String[]{"TABLE"})) { if(r.next()) found++; }
if (verifyIndexes) {
Set<String> indexes=new HashSet<>();
try (ResultSet r=c.getMetaData().getIndexInfo(null,schema,entry.getKey(),false,false)) {
while(r.next()) if(r.getString("INDEX_NAME")!=null) indexes.add(r.getString("INDEX_NAME").toUpperCase(Locale.ROOT));
}
require(indexes.containsAll(entry.getValue()),"Reporting index missing");
}
}
return found;
}
static int count(Connection c, String sql) throws SQLException {
try (Statement s=c.createStatement()) {
s.setQueryTimeout(15);
try (ResultSet r=s.executeQuery(sql)) { r.next(); return r.getInt(1); }
}
}
static void require(boolean ok, String message) {
if (!ok) throw new IllegalStateException(message);
}
static void verify(Connection c, List<String[]> rows) throws SQLException {
require(count(c,"SELECT COUNT(*) FROM sys_menu WHERE "+RANGE)==9,"Menu count differs");
require(count(c,"SELECT COUNT(*) FROM sys_role_menu WHERE role_id=1761300000000000001 AND "+RANGE)==9,"Grant count differs");
for (String[] row:rows) require(count(c,row[1])==1,"Installed menu content differs");
}
public static void main(String[] args) throws Exception {
require(args.length==1 && Set.of("--preflight","--apply","--verify").contains(args[0]),"Explicit mode required");
var in=new BufferedReader(new InputStreamReader(System.in,StandardCharsets.UTF_8));
String hash=in.readLine();
require(hash!=null && hash.matches("[a-f0-9]{64}"),"Invalid digest");
List<String[]> rows=new ArrayList<>();
for (String line; (line=in.readLine())!=null;) {
String[] p=line.split("\t",2);
rows.add(new String[]{new String(Base64.getDecoder().decode(p[0]),StandardCharsets.UTF_8),new String(Base64.getDecoder().decode(p[1]),StandardCharsets.UTF_8)});
}
require(rows.size()==18,"Exactly nine menus and nine grants required");
String schema=System.getenv("DATAGOV_DM_SCHEMA");
require(schema!=null && schema.matches("AIXUN_DATAGOV_[A-Z0-9_]+"),"Dedicated schema required");
Properties p=new Properties();
p.setProperty("user",System.getenv("DATAGOV_DM_USERNAME"));
p.setProperty("password",System.getenv("DATAGOV_DM_PASSWORD"));
p.setProperty("connectTimeout","6000"); p.setProperty("socketTimeout","30000");
Class.forName("dm.jdbc.driver.DmDriver");
try (Connection c=DriverManager.getConnection("jdbc:dm://"+System.getenv("DATAGOV_DM_HOST")+":"+System.getenv("DATAGOV_DM_PORT"),p)) {
c.setSchema(schema); require(schema.equals(c.getSchema()),"Schema mismatch");
c.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); c.setAutoCommit(false);
require(count(c,"SELECT COUNT(*) FROM sys_role WHERE role_id=1761300000000000001 AND role_key='superadmin' AND status='0' AND del_flag='0'")==1,"Expected active superadmin missing");
boolean installed=false;
try (PreparedStatement s=c.prepareStatement("SELECT sha256,state FROM dg_dm_install_step WHERE step_key=?")) {
s.setString(1,KEY);
try (ResultSet r=s.executeQuery()) {
if (r.next()) { require(hash.equals(r.getString(1)) && "SUCCESS".equals(r.getString(2)),"Reconcile journal before proceeding"); installed=true; }
}
}
if (installed) { require(tables(c,schema,true)==4,"Reporting table missing"); verify(c,rows); c.rollback(); System.out.println("TABLES_VERIFIED=4 INDEXES_VERIFIED=6 MENU_VERIFIED=9 GRANTS_VERIFIED=9"); return; }
require(!"--verify".equals(args[0]),"Migration not installed");
require(count(c,"SELECT COUNT(*) FROM sys_menu WHERE "+RANGE+" OR path='/datagov-regulatory-reporting' OR perms LIKE 'aixun:integration:regulatory-reporting:%'")==0,"Menu collision; reconcile first");
require(count(c,"SELECT COUNT(*) FROM sys_role_menu WHERE "+RANGE)==0,"Existing grant collision");
int tables=tables(c,schema,"--apply".equals(args[0]));
System.out.println("PREFLIGHT=PASS REPORTING_TABLES="+tables);
if ("--preflight".equals(args[0])) { c.rollback(); return; }
require(tables==4,"Install four reporting tables first");
try {
for (String[] row:rows) try (Statement s=c.createStatement()) { s.setQueryTimeout(15); require(s.executeUpdate(row[0])==1,"Unexpected inserted row count"); }
verify(c,rows);
try (PreparedStatement s=c.prepareStatement("INSERT INTO dg_dm_install_step(step_key,sha256,state) VALUES(?,?,'SUCCESS')")) {
s.setString(1,KEY); s.setString(2,hash); s.executeUpdate();
}
c.commit(); System.out.println("MENU_APPLIED=9 GRANTS_APPLIED=9 TRANSACTION=COMMITTED");
} catch (Exception e) { c.rollback(); throw e; }
} catch (SQLException e) {
System.err.println("DATABASE_FAILED SQLSTATE="+e.getSQLState()+" CODE="+e.getErrorCode()+"; reconcile journal and contents before retry"); System.exit(2);
}
}
}
@@ -0,0 +1,87 @@
#!/usr/bin/env python3
"""Apply or verify only regulatory reporting 277/278 using the existing DM journal.
Invoke through with-dameng-env.py; no credentials or SQL are emitted.
"""
import argparse
import base64
import hashlib
import json
from pathlib import Path
import re
import subprocess
ROOT = Path(__file__).resolve().parents[2]
TABLES = {'dg_reporting_config', 'dg_reporting_audit', 'dg_reporting_template', 'dg_reporting_standard'}
def literal(value):
if value is None:
return 'NULL'
if isinstance(value, (int, float)):
return str(value)
if value == '2000-01-01 00:00:00':
return 'LOCALTIMESTAMP'
return "'" + str(value).replace("'", "''") + "'"
def encoded(value):
return base64.b64encode(value.encode()).decode()
def main():
p = argparse.ArgumentParser(description=__doc__)
p.add_argument('mode', choices=['preflight', 'apply', 'verify'])
args = p.parse_args()
# Bind this incremental runner to the reviewed migration sources.
for path, expected in [
('integration/V20261124.277__create_regulatory_reporting.sql', '6cd233f9de3e71f0d276423bccd7e9543ba5766d53ba1e23f30822b53b6d8130'),
('system/V20261124.278__register_regulatory_reporting.sql', 'f1a7729b7f5a082442c967e125a83c7193b6c921003679222db3d504bfed0f05'),
]:
if hashlib.sha256((ROOT/'db/migration'/path).read_bytes()).hexdigest() != expected:
raise ValueError('Reviewed migration checksum changed')
ddl = []
for part in (ROOT/'db/dameng/schema.sql').read_text().split('-- @statement ')[1:]:
label, sql = part.split('\n', 1)
if label not in TABLES:
continue
sql = sql.strip().removesuffix(';')
name = re.match(r'CREATE\s+(?:UNIQUE\s+)?(?:TABLE|INDEX)\s+(\w+)', sql, re.I).group(1)
ddl.append(label+':'+name+'\t'+hashlib.sha256(sql.encode()).hexdigest()+'\t'+encoded(sql))
if len(ddl) != 10:
raise ValueError('Expected exactly ten DDL statements')
seed = json.loads((ROOT/'db/dameng/seed.json').read_text())
rows = []
for table in ('sys_menu', 'sys_role_menu'):
columns = seed[table]['columns']
selected = [r for r in seed[table]['rows'] if 1761700000000000800 <= int(r[columns.index('menu_id')]) <= 1761700000000000808]
if len(selected) != 9:
raise ValueError('Expected nine rows in '+table)
for row in selected:
if table == 'sys_role_menu' and int(row[columns.index('role_id')]) != 1761300000000000001:
raise ValueError('Unexpected role')
insert = 'INSERT INTO '+table+'('+','.join(columns)+') VALUES('+','.join(map(literal,row))+')'
predicates = []
for col, val in zip(columns, row):
if col in ('create_time', 'update_time'):
continue
predicates.append(col+' IS NULL' if val is None else "COALESCE("+col+",'~')=COALESCE("+literal(val)+",'~')" if isinstance(val,str) else col+'='+literal(val))
check = 'SELECT COUNT(*) FROM '+table+' WHERE '+' AND '.join(predicates)
rows.append(encoded(insert)+'\t'+encoded(check))
body = '\n'.join(rows)+'\n'
body = hashlib.sha256(body.encode()).hexdigest()+'\n'+body
java = ['java', '--class-path', str(ROOT/'script/datagov/m2/seatunnel/local/artifacts/DmJdbcDriver18-8.1.3.62.jar')]
def menus(mode):
subprocess.run(java+[str(ROOT/'script/database/ReportingMenuMigration.java'), '--'+mode], input=body, text=True, check=True)
if args.mode == 'preflight':
menus('preflight')
print('SCOPED_DDL=10 MENU_ROWS=9 ROLE_GRANTS=9 RUNTIME_MUTATION=NONE')
return
if args.mode == 'apply':
menus('preflight')
subprocess.run(java+[str(ROOT/'script/database/DamengSchema.java')]+(['--verify'] if args.mode=='verify' else []), input='\n'.join(ddl)+'\n', text=True, check=True)
menus(args.mode)
if __name__ == '__main__':
main()
@@ -0,0 +1,6 @@
{
"sourceContainerId": "af0c483cbbf96e90a5bfb363c6f033659c113cac87725f050f2fabf679ccae15",
"imageId": "sha256:f53a5bfc204057ecbcea8ca4ce5d0ed2cbef1f74aa15e1f15f8508b43712a705",
"authorizedBy": "\u7528\u6237\u5728\u672c\u4f1a\u8bdd\u8981\u6c42\u90e8\u7f72\u672c\u5730Docker\uff0c\u968f\u540e\u8981\u6c42\u4fee\u590d\u91c7\u96c6\u5b57\u6bb5\u7c7b\u578b\u5e76\u786e\u8ba4\u8986\u76d6\u73b0\u6709\u6240\u6709\u6570\u636e\u5e93\uff1b\u540c\u6b65\u672c\u6b21\u672c\u5730\u4fee\u590d",
"startedAt": 1795505221.888093
}
@@ -0,0 +1,9 @@
{
"service": "dataops",
"containerId": "d4b14d9b7309fc9d349c53a39aa628f8bd2542ea37db680843622856e8b21736",
"imageId": "sha256:f53a5bfc204057ecbcea8ca4ce5d0ed2cbef1f74aa15e1f15f8508b43712a705",
"status": "DEPLOYED_FUNCTIONAL_UAT_NOT_RUN",
"artifactReadback": "PASS",
"applicationReadiness": "NOT_RUN",
"recoveryImageId": "sha256:45c1d8bebe6671a350ea93040c6e2fc0b87891fcf6186e495aea01ddd02c9891"
}
@@ -0,0 +1,14 @@
{
"version": 1,
"service": "dataops",
"release": "ingestion-types-20261124",
"imageTag": "aixun-datagov/dataops:ingestion-types-20261124",
"imageId": "sha256:f53a5bfc204057ecbcea8ca4ce5d0ed2cbef1f74aa15e1f15f8508b43712a705",
"artifactSha256": "48b80bf201192cbcc4fe1dfc28da599fa5afdec321ee406c002685a350014bba",
"sourceContainerId": "af0c483cbbf96e90a5bfb363c6f033659c113cac87725f050f2fabf679ccae15",
"sourceImageId": "sha256:45c1d8bebe6671a350ea93040c6e2fc0b87891fcf6186e495aea01ddd02c9891",
"sourceImageTag": "sha256:45c1d8bebe6671a350ea93040c6e2fc0b87891fcf6186e495aea01ddd02c9891",
"sourceStateSha256": "1a90120e998ee3abfff34dd3432ed16f03359a0e704d085d643ed31265ade8e1",
"modelSha256": "784c7da07e356035522d7b0257259fed476504f0d65527e0a07a728856d89737",
"identitySha256": "68b340373dcc194a7483f67243b47b9d9612f151d7fce5c41d3c0af220018be6"
}
@@ -0,0 +1,6 @@
{
"sourceContainerId": "53b9a68245f716e37058e2ab8a0c9c37b9488c790cad0bb970217f376fdb13cc",
"imageId": "sha256:8ea621f3309f0bf0a8b943a42edb9ec2d7d9d457ae41f131ed38ee7c94d4d4b3",
"authorizedBy": "\u7528\u6237\u5728\u672c\u4f1a\u8bdd\u8981\u6c42\u90e8\u7f72\u672c\u5730Docker\uff0c\u968f\u540e\u8981\u6c42\u4fee\u590d\u91c7\u96c6\u5b57\u6bb5\u7c7b\u578b\u5e76\u786e\u8ba4\u8986\u76d6\u73b0\u6709\u6240\u6709\u6570\u636e\u5e93\uff1b\u540c\u6b65\u672c\u6b21\u672c\u5730\u4fee\u590d",
"startedAt": 1795505246.16651
}
@@ -0,0 +1,9 @@
{
"service": "frontend",
"containerId": "0ba636c872f797c84672cc09fc54c1216a358fb2fd933b6a33c0bfaed3ab289a",
"imageId": "sha256:8ea621f3309f0bf0a8b943a42edb9ec2d7d9d457ae41f131ed38ee7c94d4d4b3",
"status": "DEPLOYED_FUNCTIONAL_UAT_NOT_RUN",
"artifactReadback": "PASS",
"applicationReadiness": "NOT_RUN",
"recoveryImageId": "sha256:223093aa5ba49f3adf19f5635c9208e6eea449e6d98a28a15653f2d7965ff22e"
}
@@ -0,0 +1,15 @@
{
"version": 1,
"service": "frontend",
"release": "ingestion-types-20261124",
"imageTag": "aixun-datagov/frontend:ingestion-types-20261124",
"imageId": "sha256:8ea621f3309f0bf0a8b943a42edb9ec2d7d9d457ae41f131ed38ee7c94d4d4b3",
"artifactSha256": "89aefa98e37e6af180be15825b7c77cd526bcefb915ba000bd5f7253d47388eb",
"sourceContainerId": "53b9a68245f716e37058e2ab8a0c9c37b9488c790cad0bb970217f376fdb13cc",
"sourceImageId": "sha256:223093aa5ba49f3adf19f5635c9208e6eea449e6d98a28a15653f2d7965ff22e",
"sourceImageTag": "sha256:223093aa5ba49f3adf19f5635c9208e6eea449e6d98a28a15653f2d7965ff22e",
"sourceStateSha256": "225f70299b9829a0de2639fc06d5443ec7cc2dcce8fc682f41ca9d5858423788",
"modelSha256": "250bdc6d09bfdc5feaf35b797b8fc28a1ef4964d3a6768230aa50d082f152289",
"identitySha256": "d0c9630a8fcfc59276ca59df8adcf0043ee76a2c5f5ca0eb6745651a651c1f9f",
"artifactPath": "/opt/aixun-datagov/frontend-current"
}
@@ -0,0 +1,6 @@
{
"sourceContainerId": "78181755a73ae75e8bb6aa3e5de511575dc4d0282e3ee4361b4ab4b6b320dbc1",
"imageId": "sha256:0e493cf35418c6d187d209609abbc674856483864615be0241f6025f3002602f",
"authorizedBy": "\u7528\u6237\u5728\u672c\u4f1a\u8bdd\u8981\u6c42\u90e8\u7f72\u672c\u5730Docker\uff0c\u968f\u540e\u8981\u6c42\u4fee\u590d\u91c7\u96c6\u5b57\u6bb5\u7c7b\u578b\u5e76\u786e\u8ba4\u8986\u76d6\u73b0\u6709\u6240\u6709\u6570\u636e\u5e93\uff1b\u540c\u6b65\u672c\u6b21\u672c\u5730\u4fee\u590d",
"startedAt": 1795505188.9545128
}
@@ -0,0 +1,9 @@
{
"service": "integration",
"containerId": "1e42737ddee8a3a0751c480ef2c1b2e94d4a279b117d28138882d9c8339a795f",
"imageId": "sha256:0e493cf35418c6d187d209609abbc674856483864615be0241f6025f3002602f",
"status": "DEPLOYED_FUNCTIONAL_UAT_NOT_RUN",
"artifactReadback": "PASS",
"applicationReadiness": "NOT_RUN",
"recoveryImageId": "sha256:5ed74397796aedf65b1530767a7b13928b5a427eb858b4dff10a733533885289"
}
@@ -0,0 +1,14 @@
{
"version": 1,
"service": "integration",
"release": "ingestion-types-20261124",
"imageTag": "aixun-datagov/integration:ingestion-types-20261124",
"imageId": "sha256:0e493cf35418c6d187d209609abbc674856483864615be0241f6025f3002602f",
"artifactSha256": "5d98c8a56d8ca3b1183a2e87bd620dfd8777bc3a50efe97977fbb3037dd12946",
"sourceContainerId": "78181755a73ae75e8bb6aa3e5de511575dc4d0282e3ee4361b4ab4b6b320dbc1",
"sourceImageId": "sha256:5ed74397796aedf65b1530767a7b13928b5a427eb858b4dff10a733533885289",
"sourceImageTag": "sha256:5ed74397796aedf65b1530767a7b13928b5a427eb858b4dff10a733533885289",
"sourceStateSha256": "217471fb25ab84d531ba129926751ca2409dd5c6dd2a8a2a2804a5c855f008b4",
"modelSha256": "8d45506d9596a5dd68ccddbf261890677717e65a85892778565bc6fa108ff52c",
"identitySha256": "b8dba93c3fb1418c792f60579268fdcc808452f3907a9b393164a83d819eb2d7"
}
@@ -0,0 +1,6 @@
{
"sourceContainerId": "d4b14d9b7309fc9d349c53a39aa628f8bd2542ea37db680843622856e8b21736",
"imageId": "sha256:e32d537daefee362b9569b9bee5344c18d8f0fe0a1619c4f887f1c54c802ca6d",
"authorizedBy": "\u6cbf\u7528\u672c\u4f1a\u8bdd\u672c\u5730Docker\u90e8\u7f72\u53ca\u91c7\u96c6\u5168\u5e93\u7c7b\u578b\u4fee\u590d\u6388\u6743\uff0c\u8865\u5145\u91d1\u4ed3\u65e0\u754c\u5b57\u7b26\u7c7b\u578b\u5e76\u540c\u6b65\u6700\u7ec8\u5236\u54c1",
"startedAt": 1795505803.926808
}
@@ -0,0 +1,9 @@
{
"service": "dataops",
"containerId": "b904f30a86a9cadaaf7b1dcd660fa61311b07d3c724bfd3d6b6ad4416dbbe935",
"imageId": "sha256:e32d537daefee362b9569b9bee5344c18d8f0fe0a1619c4f887f1c54c802ca6d",
"status": "DEPLOYED_FUNCTIONAL_UAT_NOT_RUN",
"artifactReadback": "PASS",
"applicationReadiness": "NOT_RUN",
"recoveryImageId": "sha256:f53a5bfc204057ecbcea8ca4ce5d0ed2cbef1f74aa15e1f15f8508b43712a705"
}
@@ -0,0 +1,14 @@
{
"version": 1,
"service": "dataops",
"release": "ingestion-types-20261124-r2",
"imageTag": "aixun-datagov/dataops:ingestion-types-20261124-r2",
"imageId": "sha256:e32d537daefee362b9569b9bee5344c18d8f0fe0a1619c4f887f1c54c802ca6d",
"artifactSha256": "1188aecabf2ad2d71792357a401723981067ef24e7331f57b311787fee23556d",
"sourceContainerId": "d4b14d9b7309fc9d349c53a39aa628f8bd2542ea37db680843622856e8b21736",
"sourceImageId": "sha256:f53a5bfc204057ecbcea8ca4ce5d0ed2cbef1f74aa15e1f15f8508b43712a705",
"sourceImageTag": "sha256:f53a5bfc204057ecbcea8ca4ce5d0ed2cbef1f74aa15e1f15f8508b43712a705",
"sourceStateSha256": "e3992a412c4e1fb488ab3f90ab764ee8c0b26cf27cbd8b547c80819115f5b0cd",
"modelSha256": "d3e76c9982c196af34ce0063a9aedc91c772db25d0181a30b1b20f9bb141e876",
"identitySha256": "68b340373dcc194a7483f67243b47b9d9612f151d7fce5c41d3c0af220018be6"
}
@@ -0,0 +1,6 @@
{
"sourceContainerId": "1e42737ddee8a3a0751c480ef2c1b2e94d4a279b117d28138882d9c8339a795f",
"imageId": "sha256:83b9a7de4fb08887ef9fb7ecdfa9d650df6b8f7a54f5b401f9f3729f65d64542",
"authorizedBy": "\u6cbf\u7528\u672c\u4f1a\u8bdd\u672c\u5730Docker\u90e8\u7f72\u53ca\u91c7\u96c6\u5168\u5e93\u7c7b\u578b\u4fee\u590d\u6388\u6743\uff0c\u8865\u5145\u91d1\u4ed3\u65e0\u754c\u5b57\u7b26\u7c7b\u578b\u5e76\u540c\u6b65\u6700\u7ec8\u5236\u54c1",
"startedAt": 1795505658.81675
}
@@ -0,0 +1,9 @@
{
"service": "integration",
"containerId": "e59adec2fc84fd21e4de4261219acc4b175454e033c3ba2f0c55fb9b80f8fbf5",
"imageId": "sha256:83b9a7de4fb08887ef9fb7ecdfa9d650df6b8f7a54f5b401f9f3729f65d64542",
"status": "DEPLOYED_FUNCTIONAL_UAT_NOT_RUN",
"artifactReadback": "PASS",
"applicationReadiness": "NOT_RUN",
"recoveryImageId": "sha256:0e493cf35418c6d187d209609abbc674856483864615be0241f6025f3002602f"
}
@@ -0,0 +1,14 @@
{
"version": 1,
"service": "integration",
"release": "ingestion-types-20261124-r2",
"imageTag": "aixun-datagov/integration:ingestion-types-20261124-r2",
"imageId": "sha256:83b9a7de4fb08887ef9fb7ecdfa9d650df6b8f7a54f5b401f9f3729f65d64542",
"artifactSha256": "e51a0c7aa9a5248041c0aa5f62a0c1b803f5acc52f6d1429b58b32d8132ad836",
"sourceContainerId": "1e42737ddee8a3a0751c480ef2c1b2e94d4a279b117d28138882d9c8339a795f",
"sourceImageId": "sha256:0e493cf35418c6d187d209609abbc674856483864615be0241f6025f3002602f",
"sourceImageTag": "sha256:0e493cf35418c6d187d209609abbc674856483864615be0241f6025f3002602f",
"sourceStateSha256": "24e9e6ef0796a9b2470f0d667bbb6ab6cf9e9d672e005bc5bc3db380bdc18a4d",
"modelSha256": "9e08804effec388c0cc550966fe0302615d0c4ae61b635eff8a70131f6e910ce",
"identitySha256": "b8dba93c3fb1418c792f60579268fdcc808452f3907a9b393164a83d819eb2d7"
}
@@ -0,0 +1,6 @@
{
"sourceContainerId": "d505520cc8bed1a5133c5cd15871e2aec0fb2d68de4c679383e0f97238f1aa5a",
"imageId": "sha256:223093aa5ba49f3adf19f5635c9208e6eea449e6d98a28a15653f2d7965ff22e",
"authorizedBy": "\u7528\u6237\u5728\u5f53\u524d\u4f1a\u8bdd\u8981\u6c42\uff1a\u90e8\u7f72\u4e00\u4e0b\u672c\u5730\u7684 docker \u4e0a\uff1b\u90e8\u7f72\u672c\u8f6e\u76d1\u7ba1\u6570\u636e\u62a5\u9001 Integration \u4e0e\u524d\u7aef\u53ca\u5fc5\u8981\u589e\u91cf\u8fc1\u79fb",
"startedAt": 1795500660.799277
}
@@ -0,0 +1,9 @@
{
"service": "frontend",
"containerId": "53b9a68245f716e37058e2ab8a0c9c37b9488c790cad0bb970217f376fdb13cc",
"imageId": "sha256:223093aa5ba49f3adf19f5635c9208e6eea449e6d98a28a15653f2d7965ff22e",
"status": "DEPLOYED_FUNCTIONAL_UAT_NOT_RUN",
"artifactReadback": "PASS",
"applicationReadiness": "NOT_RUN",
"recoveryImageId": "sha256:7ea0a8e61a38edfae7cc918aa13f2ace07e592215de77f2ae3ad4beba4278aa9"
}
@@ -0,0 +1,15 @@
{
"version": 1,
"service": "frontend",
"release": "regulatory-reporting-20261124",
"imageTag": "aixun-datagov/frontend:regulatory-reporting-20261124",
"imageId": "sha256:223093aa5ba49f3adf19f5635c9208e6eea449e6d98a28a15653f2d7965ff22e",
"artifactSha256": "3b2a9d37b82f036f07609394bfe8fd902cc2dbddb51e00cf112b72456a73be78",
"sourceContainerId": "d505520cc8bed1a5133c5cd15871e2aec0fb2d68de4c679383e0f97238f1aa5a",
"sourceImageId": "sha256:7ea0a8e61a38edfae7cc918aa13f2ace07e592215de77f2ae3ad4beba4278aa9",
"sourceImageTag": "sha256:7ea0a8e61a38edfae7cc918aa13f2ace07e592215de77f2ae3ad4beba4278aa9",
"sourceStateSha256": "7488f963b03c6806db55f6a78a28ec5b59c0b79807555edac6cfd20dfabee322",
"modelSha256": "6bc65014a70390839034839ba9150359603fc81f060e195dbb6fdc91871b5a5e",
"identitySha256": "d0c9630a8fcfc59276ca59df8adcf0043ee76a2c5f5ca0eb6745651a651c1f9f",
"artifactPath": "/opt/aixun-datagov/frontend-current"
}
@@ -0,0 +1,6 @@
{
"sourceContainerId": "9110fbdf14f519b42e2cc5c36c8b41ffc3e4d52b2fc508b6770db229bc483fb2",
"imageId": "sha256:5ed74397796aedf65b1530767a7b13928b5a427eb858b4dff10a733533885289",
"authorizedBy": "\u7528\u6237\u5728\u5f53\u524d\u4f1a\u8bdd\u8981\u6c42\uff1a\u90e8\u7f72\u4e00\u4e0b\u672c\u5730\u7684 docker \u4e0a\uff1b\u90e8\u7f72\u672c\u8f6e\u76d1\u7ba1\u6570\u636e\u62a5\u9001 Integration \u4e0e\u524d\u7aef\u53ca\u5fc5\u8981\u589e\u91cf\u8fc1\u79fb",
"startedAt": 1795500631.199382
}
@@ -0,0 +1,9 @@
{
"service": "integration",
"containerId": "78181755a73ae75e8bb6aa3e5de511575dc4d0282e3ee4361b4ab4b6b320dbc1",
"imageId": "sha256:5ed74397796aedf65b1530767a7b13928b5a427eb858b4dff10a733533885289",
"status": "DEPLOYED_FUNCTIONAL_UAT_NOT_RUN",
"artifactReadback": "PASS",
"applicationReadiness": "NOT_RUN",
"recoveryImageId": "sha256:c94bec7bea27914e85aab5e9b87d4c781f3e8fb92a8610ca2234e1bdec986a4a"
}
@@ -0,0 +1,14 @@
{
"version": 1,
"service": "integration",
"release": "regulatory-reporting-20261124",
"imageTag": "aixun-datagov/integration:regulatory-reporting-20261124",
"imageId": "sha256:5ed74397796aedf65b1530767a7b13928b5a427eb858b4dff10a733533885289",
"artifactSha256": "3e551fe459dc9f2e3db0cad16809d3c5b945610721aef3df279db7f266ad9791",
"sourceContainerId": "9110fbdf14f519b42e2cc5c36c8b41ffc3e4d52b2fc508b6770db229bc483fb2",
"sourceImageId": "sha256:c94bec7bea27914e85aab5e9b87d4c781f3e8fb92a8610ca2234e1bdec986a4a",
"sourceImageTag": "sha256:c94bec7bea27914e85aab5e9b87d4c781f3e8fb92a8610ca2234e1bdec986a4a",
"sourceStateSha256": "b2f196837eefee5c6623955cfead9d4f8c28799522925a8e2b3e170177ee1d1e",
"modelSha256": "0a0ae64e6fdf6de08b535a8d56f820e58b0f3f308c1a4e8dbec20bdba8675756",
"identitySha256": "b8dba93c3fb1418c792f60579268fdcc808452f3907a9b393164a83d819eb2d7"
}
+62
查看文件
@@ -0,0 +1,62 @@
import java.lang.reflect.Array;
import java.sql.*;
import java.util.*;
/** Read-only synthetic conversion probes. Never reads a business table or prints connection details. */
class BatchCarrierProbe {
static void require(boolean value) { if (!value) throw new IllegalStateException("Carrier value mismatch"); }
public static void main(String[] args) throws Exception {
if (args.length!=1) throw new IllegalArgumentException("Select seatunnel or dameng");
if (args[0].equals("seatunnel")) seatunnel();
else if(args[0].equals("dameng")) dameng();
else throw new IllegalArgumentException("Unknown probe");
}
static void seatunnel() throws Exception {
Class<?> dataType=Class.forName("org.apache.seatunnel.api.table.type.SeaTunnelDataType");
Class<?> rowType=Class.forName("org.apache.seatunnel.api.table.type.SeaTunnelRowType");
Class<?> rowClass=Class.forName("org.apache.seatunnel.api.table.type.SeaTunnelRow");
Object types=Array.newInstance(dataType,1);
Array.set(types,0,Class.forName("org.apache.seatunnel.api.table.type.PrimitiveByteArrayType").getField("INSTANCE").get(null));
Object schema=rowType.getConstructor(String[].class,types.getClass()).newInstance(new String[]{"payload"},types);
Class<?> engineClass=Class.forName("org.apache.seatunnel.transform.sql.zeta.ZetaSQLEngine");
Object engine=engineClass.getConstructor().newInstance();
engineClass.getMethod("init",String.class,String.class,rowType,String.class).invoke(engine,"batch_source","batch_source",schema,
"SELECT RAWTOHEX(`payload`) AS `payload` FROM batch_source");
Object output=engineClass.getMethod("typeMapping",List.class).invoke(engine,new ArrayList<String>());
byte[] large=new byte[100_000]; for(int i=0;i<large.length;i++)large[i]=(byte)i;
for(byte[] input:Arrays.asList(null,new byte[0],new byte[]{0,1,127,-128,-1},large)) {
Object row=rowClass.getConstructor(Object[].class).newInstance((Object)new Object[]{input});
var result=(List<?>)engineClass.getMethod("transformBySQL",rowClass,rowType).invoke(engine,row,output);
require(result.size()==1);
Object actual=rowClass.getMethod("getField",int.class).invoke(result.getFirst(),0);
require(input==null ? actual==null : actual instanceof String && Arrays.equals(input,HexFormat.of().parseHex((String)actual)));
}
System.out.println("SEATUNNEL_BINARY_SQL=PASS cases=4 maxBytes=100000 null_empty_and_all_byte_values_preserved=true");
}
static void dameng() throws Exception {
Properties p=new Properties();p.setProperty("user",System.getenv("DATAGOV_DM_USERNAME"));p.setProperty("password",System.getenv("DATAGOV_DM_PASSWORD"));
p.setProperty("connectTimeout","6000");p.setProperty("socketTimeout","20000");
Class.forName("dm.jdbc.driver.DmDriver");
try(Connection c=DriverManager.getConnection("jdbc:dm://"+System.getenv("DATAGOV_DM_HOST")+":"+System.getenv("DATAGOV_DM_PORT"),p)) {
c.setReadOnly(true);
String[][] cases={
{"number","SELECT TO_CHAR(12345678901234567890.123456789,'TM9','NLS_NUMERIC_CHARACTERS=''.,''') FROM DUAL","12345678901234567890.123456789"},
{"timestamp","SELECT TO_CHAR(TIMESTAMP '2026-11-24 12:34:56.123456','YYYY-MM-DD\"T\"HH24:MI:SS.FF9') FROM DUAL","2026-11-24T12:34:56.123456000"},
{"date","SELECT TO_CHAR(CAST('2026-11-24' AS DATE),'YYYY-MM-DD HH24:MI:SS') FROM DUAL","2026-11-24 00:00:00"}
};
boolean passed=true;
for(String[] item:cases) {
try(Statement s=c.createStatement()) { s.setQueryTimeout(10);try(ResultSet r=s.executeQuery(item[1])) {r.next();require(item[2].equals(r.getString(1)));System.out.println("DAMENG_"+item[0]+"=PASS");} }
catch(SQLException e) {passed=false;System.out.println("DAMENG_"+item[0]+"=FAIL code="+e.getErrorCode());}
}
String large="长文本🙂".repeat(20000);
try(PreparedStatement s=c.prepareStatement("SELECT CAST(? AS CLOB) FROM DUAL")) {
s.setString(1,large);try(ResultSet r=s.executeQuery()) {r.next();require(large.equals(r.getString(1)));System.out.println("DAMENG_CLOB=PASS chars="+large.length());}
}
try(Statement s=c.createStatement();ResultSet r=s.executeQuery("SELECT CAST(HEXTORAW('00017F80FF') AS BLOB) FROM DUAL")) {
r.next();require(Arrays.equals(r.getBytes(1),HexFormat.of().parseHex("00017f80ff")));System.out.println("DAMENG_BLOB=PASS");
}
require(passed);
} catch(SQLException e) {System.err.println("DATABASE_PROBE_FAILED code="+e.getErrorCode());System.exit(2);}
}
}