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

这个提交包含在:
apple
2026-11-24 16:05:24 +08:00
父节点 fb47c07f7c
当前提交 c5760c74eb
共修改 74 个文件,包含 2631 行新增和 41 行删除
@@ -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")));
}
}