修改问题
这个提交包含在:
@@ -11,6 +11,12 @@
|
||||
<artifactId>aixun-integration</artifactId>
|
||||
<description>DataGov external integration boundary and internal adapters</description>
|
||||
<dependencies>
|
||||
<dependency><groupId>cn.aixunkeji</groupId><artifactId>aixun-api-resource</artifactId></dependency>
|
||||
<dependency><groupId>org.apache.pdfbox</groupId><artifactId>pdfbox</artifactId><version>3.0.8</version></dependency>
|
||||
<dependency>
|
||||
<groupId>cn.aixunkeji</groupId>
|
||||
<artifactId>aixun-common-excel</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>jakarta.mail</groupId>
|
||||
<artifactId>jakarta.mail-api</artifactId>
|
||||
|
||||
+4
-1
@@ -10,10 +10,13 @@ import static cn.aixunkeji.datagov.integration.aiassistant.AiWorkbenchDomain.Act
|
||||
|
||||
@Repository @RequiredArgsConstructor
|
||||
class WorkbenchMemoryRepository {
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect = cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG;
|
||||
|
||||
private final JdbcTemplate jdbc;
|
||||
record Settings(boolean enabled,long version) { }
|
||||
Settings settings(Actor actor,boolean lock) {
|
||||
if(lock)jdbc.update("INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(dg_ai_workbench_memory_settings) */ INTO dg_ai_workbench_memory_settings(actor_id,department_id) VALUES(?,?)",actor.userId(),actor.departmentId());
|
||||
if(lock)jdbc.update(databaseDialect.sql("INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(dg_ai_workbench_memory_settings) */ INTO dg_ai_workbench_memory_settings(actor_id,department_id) VALUES(?,?)", "INSERT IGNORE INTO dg_ai_workbench_memory_settings(actor_id,department_id) VALUES(?,?)"),actor.userId(),actor.departmentId());
|
||||
return jdbc.query("SELECT enabled,version FROM dg_ai_workbench_memory_settings WHERE actor_id=? AND department_id=?"+(lock?" FOR UPDATE":""),
|
||||
(r,n)->new Settings(r.getBoolean(1),r.getLong(2)),actor.userId(),actor.departmentId()).stream().findFirst().orElse(new Settings(false,0));
|
||||
}
|
||||
|
||||
+4
-1
@@ -17,6 +17,9 @@ import static cn.aixunkeji.datagov.integration.aischedule.ScheduleApi.*;
|
||||
@Repository
|
||||
@RequiredArgsConstructor
|
||||
class ScheduleRepository {
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect = cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG;
|
||||
|
||||
private final JdbcTemplate jdbc;
|
||||
private final JsonMapper json;
|
||||
private static final String PLAN_COLUMNS="plan_json,status,next_run_at,reserved_tokens,run_count,pause_reason,version,update_time";
|
||||
@@ -39,7 +42,7 @@ class ScheduleRepository {
|
||||
return rows.getFirst()[1]==null?null:json.readValue(rows.getFirst()[1],Plan.class);
|
||||
}
|
||||
Plan receipt(ScheduleActor.Actor a,String key,String hash,String id,Supplier<Plan> action) {
|
||||
jdbc.update("INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(dg_assistant_schedule_request) */ INTO dg_assistant_schedule_request(actor_id,department_id,request_key,request_hash,schedule_id,create_dept,create_by,update_by,version,del_flag) VALUES(?,?,?,?,?,?,?,?,0,'0')",a.id(),a.department(),key,hash,id,a.department(),a.id(),a.id());
|
||||
jdbc.update(databaseDialect.sql("INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(dg_assistant_schedule_request) */ INTO dg_assistant_schedule_request(actor_id,department_id,request_key,request_hash,schedule_id,create_dept,create_by,update_by,version,del_flag) VALUES(?,?,?,?,?,?,?,?,0,'0')", "INSERT IGNORE INTO dg_assistant_schedule_request(actor_id,department_id,request_key,request_hash,schedule_id,create_dept,create_by,update_by,version,del_flag) VALUES(?,?,?,?,?,?,?,?,0,'0')"),a.id(),a.department(),key,hash,id,a.department(),a.id(),a.id());
|
||||
var rows=jdbc.query("SELECT request_hash,response_json FROM dg_assistant_schedule_request WHERE actor_id=? AND department_id=? AND request_key=? FOR UPDATE",(r,i)->new String[]{r.getString(1),r.getString(2)},a.id(),a.department(),key);
|
||||
if(rows.size()!=1||!hash.equals(rows.getFirst()[0])) throw ScheduleException.conflict("幂等键已用于其他请求");
|
||||
if(rows.getFirst()[1]!=null) return json.readValue(rows.getFirst()[1],Plan.class);
|
||||
|
||||
+13
-4
@@ -30,6 +30,10 @@ final class DataSourceBiQueryJdbc {
|
||||
}
|
||||
static AnalyticsQuery.Result read(Connection connection,DataSourceView source,NativeMetadataBiDirectory.Target target,
|
||||
List<String> allowed,AnalyticsQuery.Plan plan,NativeQueryPolicyApi.Decision policy,AnalyticsExecution execution) throws SQLException {
|
||||
return read(connection,source,target,allowed,plan,policy,execution,false);
|
||||
}
|
||||
static AnalyticsQuery.Result read(Connection connection,DataSourceView source,NativeMetadataBiDirectory.Target target,
|
||||
List<String> allowed,AnalyticsQuery.Plan plan,NativeQueryPolicyApi.Decision policy,AnalyticsExecution execution,boolean complete) throws SQLException {
|
||||
String schema=Set.of("MYSQL","MARIADB","DORIS").contains(source.type())?null:target.schema();
|
||||
List<Field> before=fields(connection,source,target,schema);
|
||||
List<String> permitted=permitted(target,before,allowed,plan);
|
||||
@@ -38,16 +42,18 @@ final class DataSourceBiQueryJdbc {
|
||||
if(policy.columns()==null||!allowed.containsAll(policy.columns()))throw new IllegalArgumentException();
|
||||
var projected=permitted.stream().filter(policy.columns()::contains).toList();
|
||||
// Authorize every user-supplied projection and analysis before adding owner-only row conditions.
|
||||
AnalyticsSqlCompiler.compileForSource(plan,projected,source.type(),target.database(),schema,target.table());
|
||||
compile(plan,projected,source.type(),target.database(),schema,target.table(),complete);
|
||||
protectedPlan=DataSourceBiQueryPolicy.guarded(plan,policy);
|
||||
var needed=new LinkedHashSet<>(projected);policy.filters().forEach(f->needed.add(f.field()));
|
||||
permitted=permitted(target,before,List.copyOf(needed),protectedPlan);
|
||||
}
|
||||
var sql=AnalyticsSqlCompiler.compileForSource(protectedPlan,permitted,source.type(),target.database(),schema,target.table());
|
||||
AnalyticsQuery.Result result=rows(connection,sql,policy==null?List.of():policy.masks(),execution);
|
||||
var sql=compile(protectedPlan,permitted,source.type(),target.database(),schema,target.table(),complete);
|
||||
AnalyticsQuery.Result result=rows(connection,sql,policy==null?List.of():policy.masks(),execution,System::nanoTime,complete);
|
||||
if(complete&&result.truncated())throw new SQLException("COMPLETE_READ_LIMIT_EXCEEDED");
|
||||
if (!before.equals(fields(connection,source,target,schema))) throw new SQLException("NATIVE_BI_STRUCTURE_CHANGED");
|
||||
return result;
|
||||
}
|
||||
private static AnalyticsSqlCompiler.Compiled compile(AnalyticsQuery.Plan p,List<String> allowed,String source,String database,String schema,String table,boolean complete){return complete?AnalyticsSqlCompiler.compileForSnapshot(p,allowed,source,database,schema,table):AnalyticsSqlCompiler.compileForSource(p,allowed,source,database,schema,table);}
|
||||
|
||||
static List<String> permitted(NativeMetadataBiDirectory.Target target,List<Field> actual,List<String> allowed,
|
||||
AnalyticsQuery.Plan plan) {
|
||||
@@ -166,6 +172,9 @@ final class DataSourceBiQueryJdbc {
|
||||
return rows(connection,sql,masks,execution,System::nanoTime);
|
||||
}
|
||||
static AnalyticsQuery.Result rows(Connection connection,AnalyticsSqlCompiler.Compiled sql,List<NativeQueryPolicyApi.Mask> masks,AnalyticsExecution execution,java.util.function.LongSupplier nanoClock)throws SQLException{
|
||||
return rows(connection,sql,masks,execution,nanoClock,false);
|
||||
}
|
||||
static AnalyticsQuery.Result rows(Connection connection,AnalyticsSqlCompiler.Compiled sql,List<NativeQueryPolicyApi.Mask> masks,AnalyticsExecution execution,java.util.function.LongSupplier nanoClock,boolean complete)throws SQLException{
|
||||
Map<String,NativeQueryPolicyApi.Mask> outputMasks=new HashMap<>();masks.forEach(mask->{DataSourceBiQueryPolicy.validate(mask);if(outputMasks.put(mask.field(),mask)!=null)throw new IllegalArgumentException();});
|
||||
try(PreparedStatement statement=connection.prepareStatement(sql.sql());var cancellation=NativeQueryCancellation.watch(execution,statement)){
|
||||
int seconds=SqlExecutionBudget.seconds(sql.maxExecutionSeconds());
|
||||
@@ -187,7 +196,7 @@ final class DataSourceBiQueryJdbc {
|
||||
deadline.check();
|
||||
String value=result.getString(i+1);
|
||||
if(value!=null){if(value.length()>1_000_000)throw new SQLException();bytes+=value.getBytes(StandardCharsets.UTF_8).length;}
|
||||
if(bytes>2_000_000){statement.cancel();throw new SQLException();}
|
||||
if(bytes>(complete?8_000_000:2_000_000)){statement.cancel();throw new SQLException(complete?"COMPLETE_READ_LIMIT_EXCEEDED":"QUERY_SIZE_EXCEEDED");}
|
||||
row.put(sql.columns().get(i),value);
|
||||
}
|
||||
rows.add(Collections.unmodifiableMap(row));
|
||||
|
||||
+41
-5
@@ -35,6 +35,22 @@ public class DataSourceBiQueryService implements DataSourceBiQueryApi {
|
||||
this.registry=registry;this.credentials=credentials;this.connections=connections;this.access=access;
|
||||
}
|
||||
@Override public AnalyticsQuery.Result query(Query query){
|
||||
return execute(query,false);
|
||||
}
|
||||
@Override public AnalyticsQuery.Result complete(Query query){
|
||||
if(query==null||!"EXPORT".equals(query.action())||query.plan()==null||query.plan().limit()!=100000)return failure("COMPLETE_READ_INVALID");
|
||||
return execute(query,true);
|
||||
}
|
||||
private AnalyticsQuery.Result execute(Query query,boolean complete){
|
||||
return execute(query,complete,false);
|
||||
}
|
||||
@Override public String authorizeComplete(Query query){
|
||||
if(query==null||!"EXPORT".equals(query.action())||query.plan()==null||query.plan().limit()!=100000)throw new IllegalArgumentException();
|
||||
var result=execute(query,true,true);
|
||||
if(result==null||!"SUCCEEDED".equals(result.state())||result.authorizationSha256()==null)throw DataSourceOperationException.forbidden();
|
||||
return result.authorizationSha256();
|
||||
}
|
||||
private AnalyticsQuery.Result execute(Query query,boolean complete,boolean authorizationOnly){
|
||||
Future<AnalyticsQuery.Result> work=null;
|
||||
try{
|
||||
if(query==null||query.tableId()==null||!query.tableId().matches("[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}")
|
||||
@@ -49,22 +65,35 @@ public class DataSourceBiQueryService implements DataSourceBiQueryApi {
|
||||
var scope=new DataSourceAccessScope(query.actorId(),query.departmentId());
|
||||
DataSourceView before=source(scope,target);
|
||||
String queryHash=hash(JsonMapper.builder().build().writeValueAsString(query.plan()));
|
||||
var decision=policies.prepare(new NativeQueryPolicyApi.Request(query.actorId(),query.departmentId(),query.tableId(),
|
||||
target.sourceVersion(),target.revision(),before.type(),"EXPORT".equals(query.action())?"EXPORT":"SELECT",query.allowedColumns(),queryHash,purpose));
|
||||
var policyRequest=new NativeQueryPolicyApi.Request(query.actorId(),query.departmentId(),query.tableId(),
|
||||
target.sourceVersion(),target.revision(),before.type(),"EXPORT".equals(query.action())?"EXPORT":"SELECT",query.allowedColumns(),queryHash,purpose,complete);
|
||||
var decision=authorizationOnly?policies.authorize(policyRequest):policies.prepare(policyRequest);
|
||||
if(decision==null||decision.queryId()==null||decision.fingerprint()==null||!decision.fingerprint().matches("[0-9a-f]{64}"))throw new IllegalArgumentException();
|
||||
work=workers.submit(()->connections.read(before,scope,c->DataSourceBiQueryJdbc.read(c,before,target,query.allowedColumns(),query.plan(),decision,query.execution())));
|
||||
var result=work.get(10,TimeUnit.SECONDS);
|
||||
AnalyticsQuery.Result result;
|
||||
if(authorizationOnly){
|
||||
cn.aixunkeji.datagov.integration.tablefile.AnalyticsSqlCompiler.compileForSnapshot(query.plan(),decision.columns(),before.type(),target.database(),target.schema(),target.table());
|
||||
var needed=new LinkedHashSet<>(decision.columns());decision.filters().forEach(f->needed.add(f.field()));
|
||||
cn.aixunkeji.datagov.integration.tablefile.AnalyticsSqlCompiler.compileForSnapshot(DataSourceBiQueryPolicy.guarded(query.plan(),decision),List.copyOf(needed),before.type(),target.database(),target.schema(),target.table());
|
||||
result=new AnalyticsQuery.Result("SUCCEEDED",query.plan().columns(),List.of(),false,LocalDateTime.now(),null);
|
||||
}else{
|
||||
work=workers.submit(()->connections.read(before,scope,c->DataSourceBiQueryJdbc.read(c,before,target,query.allowedColumns(),query.plan(),decision,query.execution(),complete)));
|
||||
result=work.get(10,TimeUnit.SECONDS);
|
||||
}
|
||||
authorize(query,purpose);
|
||||
if("EXPORT".equals(query.action()))access.requireExport(query.actorId(),query.departmentId());
|
||||
DataSourceView after=source(scope,target);
|
||||
if(!Objects.equals(before.secretRef(),after.secretRef())||!Objects.equals(before.lastTestId(),after.lastTestId())
|
||||
||!target.equals(directory.resolve(reference)))return failure("SOURCE_CHANGED");
|
||||
if(result==null||!"SUCCEEDED".equals(result.state()))return result==null?failure("QUERY_NOT_AUTHORIZED_OR_UNAVAILABLE"):result;
|
||||
if(authorizationOnly){
|
||||
if(!decision.fingerprint().equals(policies.authorize(policyRequest).fingerprint()))return failure("POLICY_CHANGED_OR_REVOKED");
|
||||
return DataSourceQueryProof.attach(result,completeProof(query,decision));
|
||||
}
|
||||
var receipt=policies.complete(new NativeQueryPolicyApi.Completion(query.actorId(),query.departmentId(),decision.queryId(),
|
||||
decision.fingerprint(),queryHash,result.rows().size(),outputSources(query.plan(),result.columns()),result.observedAt()));
|
||||
if(receipt==null||!receipt.accepted())return failure("POLICY_CHANGED_OR_REVOKED");
|
||||
NativeQueryCancellation.requireRunning(query.execution(),query.actorId(),query.departmentId());
|
||||
return DataSourceQueryProof.attach(result,decision.fingerprint());
|
||||
return DataSourceQueryProof.attach(result,complete?completeProof(query,decision):decision.fingerprint());
|
||||
}catch(InterruptedException exception){Thread.currentThread().interrupt();return failure("QUERY_INTERRUPTED");}
|
||||
catch(TimeoutException exception){return failure("QUERY_TIMEOUT");}
|
||||
catch(RejectedExecutionException exception){return failure("QUERY_BUSY");}
|
||||
@@ -78,8 +107,15 @@ public class DataSourceBiQueryService implements DataSourceBiQueryApi {
|
||||
var frames=Arrays.stream(error.getStackTrace()).filter(f->f.getClassName().startsWith("cn.aixunkeji.datagov.")).limit(5).map(StackTraceElement::toString).toList();
|
||||
LOG.warn("Native query rejected: type={}, frames={}",error.getClass().getSimpleName(),frames);
|
||||
}
|
||||
/** A reporting reader must independently obtain exactly the same effective data scope.
|
||||
* The real actor remains in the policy ticket/receipt; matching scope is not an authorization grant.
|
||||
*/
|
||||
static String completeProof(Query query,NativeQueryPolicyApi.Decision decision){
|
||||
return hash(JsonMapper.builder().build().writeValueAsString(List.of("reporting-complete-scope-v1",query.departmentId(),query.tableId(),query.allowedColumns(),query.plan(),decision.resourceRef(),decision.columns(),decision.filters(),decision.masks(),decision.policies())));
|
||||
}
|
||||
static String executionFailure(ExecutionException exception){
|
||||
Throwable cause=exception.getCause();
|
||||
if(cause instanceof java.sql.SQLException&&"COMPLETE_READ_LIMIT_EXCEEDED".equals(cause.getMessage()))return "COMPLETE_READ_LIMIT_EXCEEDED";
|
||||
return cause instanceof cn.aixunkeji.datagov.integration.tablefile.SqlExecutionTimeoutException?"QUERY_EXECUTION_TIMEOUT":cause instanceof java.sql.SQLException&&"QUERY_EXECUTION_WATCH_BUSY".equals(cause.getMessage())?"QUERY_BUSY":"QUERY_NOT_AUTHORIZED_OR_UNAVAILABLE";
|
||||
}
|
||||
private void authorize(Query query,String purpose){
|
||||
|
||||
+8
-2
@@ -31,6 +31,9 @@ import java.util.Optional;
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class DataSourceRegistry {
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect = cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG;
|
||||
|
||||
|
||||
private static final String SELECT_SOURCE = """
|
||||
SELECT data_source_id, data_source_name, source_type, host_name, port_no,
|
||||
@@ -340,7 +343,7 @@ public class DataSourceRegistry {
|
||||
private void upsertBinding(long dataSourceId, String reference, DataSourceAccessScope scope) {
|
||||
cn.aixunkeji.datagov.integration.secret.SecretRef secretRef =
|
||||
new cn.aixunkeji.datagov.integration.secret.SecretRef(reference);
|
||||
jdbcTemplate.update("""
|
||||
jdbcTemplate.update(databaseDialect.sql("""
|
||||
MERGE INTO dg_secret_binding t
|
||||
USING (SELECT ? AS binding_id, 'data-source' AS owner_object_type, ? AS owner_object_id, ? AS secret_ref, ? AS secret_ref_fingerprint, ? AS secret_version, 'ACTIVE' AS binding_status, ? AS create_dept, ? AS create_by, NOW() AS create_time, ? AS update_by, NOW() AS update_time, '0' AS del_flag, 0 AS version FROM DUAL) s
|
||||
ON ((t.binding_id=s.binding_id) OR (t.owner_object_type=s.owner_object_type AND t.owner_object_id=s.owner_object_id AND t.del_flag=s.del_flag))
|
||||
@@ -349,7 +352,10 @@ public class DataSourceRegistry {
|
||||
t.binding_status='ACTIVE', t.update_by=s.update_by, t.update_time=NOW(), t.version=t.version+1
|
||||
WHEN NOT MATCHED THEN INSERT (binding_id,owner_object_type,owner_object_id,secret_ref,secret_ref_fingerprint,secret_version,binding_status,create_dept,create_by,create_time,update_by,update_time,del_flag,version)
|
||||
VALUES (s.binding_id,s.owner_object_type,s.owner_object_id,s.secret_ref,s.secret_ref_fingerprint,s.secret_version,s.binding_status,s.create_dept,s.create_by,s.create_time,s.update_by,s.update_time,s.del_flag,s.version)
|
||||
""", IdGeneratorUtil.nextLongId(), dataSourceId, secretRef.value(), secretRef.fingerprint(),
|
||||
""", """
|
||||
INSERT INTO dg_secret_binding(binding_id,owner_object_type,owner_object_id,secret_ref,secret_ref_fingerprint,secret_version,binding_status,create_dept,create_by,create_time,update_by,update_time,del_flag,version) SELECT s.binding_id,s.owner_object_type,s.owner_object_id,s.secret_ref,s.secret_ref_fingerprint,s.secret_version,s.binding_status,s.create_dept,s.create_by,s.create_time,s.update_by,s.update_time,s.del_flag,s.version FROM (SELECT ? AS binding_id, 'data-source' AS owner_object_type, ? AS owner_object_id, ? AS secret_ref, ? AS secret_ref_fingerprint, ? AS secret_version, 'ACTIVE' AS binding_status, ? AS create_dept, ? AS create_by, NOW() AS create_time, ? AS update_by, NOW() AS update_time, '0' AS del_flag, 0 AS version FROM DUAL) s WHERE TRUE ON DUPLICATE KEY UPDATE secret_ref=s.secret_ref,
|
||||
secret_ref_fingerprint=s.secret_ref_fingerprint, secret_version=s.secret_version,
|
||||
binding_status='ACTIVE', update_by=s.update_by, update_time=NOW(), version=dg_secret_binding.version+1"""), IdGeneratorUtil.nextLongId(), dataSourceId, secretRef.value(), secretRef.fingerprint(),
|
||||
secretRef.version(), scope.orgScopeId(), scope.actorId(), scope.actorId());
|
||||
}
|
||||
|
||||
|
||||
+10
-2
@@ -14,6 +14,9 @@ import java.util.List;
|
||||
@Repository
|
||||
@RequiredArgsConstructor
|
||||
public class GoldenStageRepository {
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect = cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG;
|
||||
|
||||
|
||||
private static final List<String> STAGES = List.of("SEATUNNEL", "HIVE", "DORIS", "OPENMETADATA", "FINALIZE");
|
||||
|
||||
@@ -25,12 +28,17 @@ public class GoldenStageRepository {
|
||||
STAGES.forEach(stage -> {
|
||||
boolean reused = "RETRY".equals(command.runType()) && command.parentRunId() != null &&
|
||||
parentStageSucceeded(command.parentRunId(), stage);
|
||||
jdbcTemplate.update("""
|
||||
jdbcTemplate.update(databaseDialect.sql("""
|
||||
INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(dg_golden_stage) */ INTO dg_golden_stage(
|
||||
stage_id, run_id, batch_no, stage_name, stage_status, attempt_no, fail_once,
|
||||
request_id, payload_sha256, completed_at, create_time, update_time, del_flag, version
|
||||
) VALUES (?, ?, ?, ?, ?, 0, ?, ?, ?, ?, NOW(), NOW(), '0', 0)
|
||||
""", IdGeneratorUtil.nextLongId(), command.runId(), command.batchNo(), stage,
|
||||
""", """
|
||||
INSERT IGNORE INTO dg_golden_stage(
|
||||
stage_id, run_id, batch_no, stage_name, stage_status, attempt_no, fail_once,
|
||||
request_id, payload_sha256, completed_at, create_time, update_time, del_flag, version
|
||||
) VALUES (?, ?, ?, ?, ?, 0, ?, ?, ?, ?, NOW(), NOW(), '0', 0)
|
||||
"""), IdGeneratorUtil.nextLongId(), command.runId(), command.batchNo(), stage,
|
||||
reused ? "SUCCEEDED" : "PENDING",
|
||||
command.failHiveOnce() && "HIVE".equals(stage) ? "1" : "0", command.requestId(),
|
||||
command.payloadSha256(), reused ? new java.sql.Timestamp(System.currentTimeMillis()) : null);
|
||||
|
||||
+23
-6
@@ -14,6 +14,9 @@ import java.util.List;
|
||||
|
||||
@Repository
|
||||
class AlertDeliveryStore {
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect = cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG;
|
||||
|
||||
private final JdbcTemplate jdbc;
|
||||
AlertDeliveryStore(JdbcTemplate jdbc) { this.jdbc = jdbc; }
|
||||
record Stored(String hash, Receipt receipt) { }
|
||||
@@ -26,23 +29,32 @@ class AlertDeliveryStore {
|
||||
public boolean reserve(Command command, String hash, AlertDeliveryProperties.Channel channel, String targetLabel) {
|
||||
// This committed reservation precedes network I/O. A lost process is UNKNOWN, never a new send.
|
||||
try {
|
||||
return jdbc.update("""
|
||||
return jdbc.update(databaseDialect.sql("""
|
||||
INSERT INTO dg_alert_external_delivery
|
||||
(org_id,actor_id,request_key,event_id,event_version,command_sha256,channel_id,channel_label,
|
||||
target_key,target_label,delivery_state,safe_code,started_at,create_dept,create_by,update_by)
|
||||
VALUES (?,?,?,?,?,?,?,?,?,?,'UNKNOWN','AWAITING_RECEIPT',CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS TIMESTAMP(3)),?,?,?)
|
||||
""", command.scope().orgId(), command.scope().actorId(), command.requestKey(), command.eventId(),
|
||||
""", """
|
||||
INSERT INTO dg_alert_external_delivery
|
||||
(org_id,actor_id,request_key,event_id,event_version,command_sha256,channel_id,channel_label,
|
||||
target_key,target_label,delivery_state,safe_code,started_at,create_dept,create_by,update_by)
|
||||
VALUES (?,?,?,?,?,?,?,?,?,?,'UNKNOWN','AWAITING_RECEIPT',UTC_TIMESTAMP(3),?,?,?)
|
||||
"""), command.scope().orgId(), command.scope().actorId(), command.requestKey(), command.eventId(),
|
||||
command.eventVersion(), hash, channel.getId(), channel.getLabel(), command.targetKey(), targetLabel,
|
||||
command.scope().orgId(), command.scope().actorId(), command.scope().actorId()) == 1;
|
||||
} catch (DuplicateKeyException existing) { return false; }
|
||||
}
|
||||
@Transactional(propagation = Propagation.REQUIRES_NEW)
|
||||
public void finish(Command command, AlertDeliveryTransport.Result result) {
|
||||
jdbc.update("""
|
||||
jdbc.update(databaseDialect.sql("""
|
||||
UPDATE dg_alert_external_delivery SET delivery_state=?,safe_code=?,completed_at=CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS TIMESTAMP(3)),
|
||||
update_time=CURRENT_TIMESTAMP(3),version=version+1
|
||||
WHERE org_id=? AND actor_id=? AND request_key=? AND command_sha256=? AND safe_code='AWAITING_RECEIPT' AND del_flag='0'
|
||||
""", result.state(), result.code(), command.scope().orgId(), command.scope().actorId(),
|
||||
""", """
|
||||
UPDATE dg_alert_external_delivery SET delivery_state=?,safe_code=?,completed_at=UTC_TIMESTAMP(3),
|
||||
update_time=CURRENT_TIMESTAMP(3),version=version+1
|
||||
WHERE org_id=? AND actor_id=? AND request_key=? AND command_sha256=? AND safe_code='AWAITING_RECEIPT' AND del_flag='0'
|
||||
"""), result.state(), result.code(), command.scope().orgId(), command.scope().actorId(),
|
||||
command.requestKey(), AlertDeliveryService.hash(command));
|
||||
}
|
||||
List<Receipt> history(Scope scope, long eventId) {
|
||||
@@ -52,12 +64,17 @@ class AlertDeliveryStore {
|
||||
@Transactional(propagation = Propagation.REQUIRES_NEW)
|
||||
public void cancelUnsubmitted(Scope scope, long eventId, String key) {
|
||||
try {
|
||||
jdbc.update("""
|
||||
jdbc.update(databaseDialect.sql("""
|
||||
INSERT INTO dg_alert_external_delivery
|
||||
(org_id,actor_id,request_key,event_id,event_version,command_sha256,channel_id,channel_label,
|
||||
target_key,target_label,delivery_state,safe_code,started_at,completed_at,create_dept,create_by,update_by)
|
||||
VALUES (?,?,?,?,0,?,'-','未开始','-','未开始','CANCELLED','REQUEST_CANCELLED',CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS TIMESTAMP(3)),CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS TIMESTAMP(3)),?,?,?)
|
||||
""", scope.orgId(), scope.actorId(), key, eventId, "0".repeat(64), scope.orgId(), scope.actorId(), scope.actorId());
|
||||
""", """
|
||||
INSERT INTO dg_alert_external_delivery
|
||||
(org_id,actor_id,request_key,event_id,event_version,command_sha256,channel_id,channel_label,
|
||||
target_key,target_label,delivery_state,safe_code,started_at,completed_at,create_dept,create_by,update_by)
|
||||
VALUES (?,?,?,?,0,?,'-','未开始','-','未开始','CANCELLED','REQUEST_CANCELLED',UTC_TIMESTAMP(3),UTC_TIMESTAMP(3),?,?,?)
|
||||
"""), scope.orgId(), scope.actorId(), key, eventId, "0".repeat(64), scope.orgId(), scope.actorId(), scope.actorId());
|
||||
} catch (DuplicateKeyException alreadySubmitted) { /* A claimed send cannot be cancelled or retried. */ }
|
||||
}
|
||||
private static Receipt receipt(ResultSet rs) throws SQLException {
|
||||
|
||||
+4
-2
@@ -5,7 +5,9 @@ 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 Department(String shortName, String level, String supervisor, String role) {
|
||||
public Department(String shortName, String level, String supervisor) { this(shortName, level, supervisor, "UNCLASSIFIED"); }
|
||||
}
|
||||
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) { }
|
||||
@@ -19,6 +21,6 @@ public final class ReportingApi {
|
||||
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 Overview(long departments, long systems, long topics, long enabledTopics, long regulators, long internalDepartments, long unclassifiedDepartments) { }
|
||||
public record Audit(String id, String action, String actorId, long version, String reason, String occurredAt) { }
|
||||
}
|
||||
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
package cn.aixunkeji.datagov.integration.regulatoryreporting;
|
||||
|
||||
import java.util.*;
|
||||
import cn.aixunkeji.resource.api.assetupgrade.ReportingAttachmentPolicy;
|
||||
import static cn.aixunkeji.datagov.integration.regulatoryreporting.ReportingExecutionApi.*;
|
||||
|
||||
/** Derives associations from immutable mapped rows; no client-supplied business keys or arbitrary file IDs. */
|
||||
final class ReportingAttachments {
|
||||
private ReportingAttachments() { }
|
||||
static boolean configured(Frozen fixed){return fixed.selections().stream().anyMatch(s->!s.attachmentFields().isEmpty());}
|
||||
static LinkedHashMap<String,List<AttachmentUse>> expected(Frozen fixed,Snapshot snapshot){
|
||||
var result=new LinkedHashMap<String,List<AttachmentUse>>();var folded=new HashSet<String>();
|
||||
for(var selection:fixed.selections()){
|
||||
if(selection.attachmentFields().isEmpty())continue;
|
||||
var data=snapshot.resources().stream().filter(r->r.resource().equals(selection.resourceCode())).toList();
|
||||
if(data.size()!=1)throw ReportingException.conflict("附件资源不属于当前快照");
|
||||
int row=0;
|
||||
for(var record:data.getFirst().rows()){
|
||||
row++;
|
||||
for(String field:selection.attachmentFields()){
|
||||
if(!record.containsKey(field))throw ReportingException.conflict("附件字段不属于当前快照");
|
||||
String reference=record.get(field);if(reference==null||reference.isBlank())continue;
|
||||
String name=name(reference);
|
||||
if(!result.containsKey(name)){
|
||||
if(!folded.add(name.toLowerCase(Locale.ROOT)))throw ReportingException.invalid("附件名称存在大小写冲突");
|
||||
if(result.size()>=ReportingAttachmentPolicy.MAX_FILES)throw ReportingException.invalid("每批次最多50份不同附件");
|
||||
result.put(name,new ArrayList<>());
|
||||
}
|
||||
if(result.get(name).size()>=2000)throw ReportingException.invalid("单个附件最多关联2000条字段记录,请拆分期间");
|
||||
result.get(name).add(new AttachmentUse(selection.resourceCode(),row,field));
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
static String name(String reference){
|
||||
String name=reference.startsWith("unStruct/")?reference.substring(9):reference;
|
||||
try{ReportingAttachmentPolicy.originalName(name);return name;}
|
||||
catch(IllegalArgumentException e){throw ReportingException.invalid("附件引用须为32位大写MD5_原文件名,可带unStruct/前缀;请核对附件类型和文件名");}
|
||||
}
|
||||
static void validateUpload(String name,String original,byte[] bytes){
|
||||
try{if(!ReportingAttachmentPolicy.originalName(name).equals(original))throw new IllegalArgumentException();ReportingAttachmentPolicy.verify(name,bytes);}
|
||||
catch(IllegalArgumentException e){throw ReportingException.invalid("附件名称、内容MD5或大小与快照引用不一致;单批次附件总量最多8 MiB");}
|
||||
}
|
||||
static List<Attachment> describe(Frozen fixed,Snapshot snapshot,List<Artifact> artifacts,boolean requireComplete){
|
||||
var expected=expected(fixed,snapshot);var stored=new HashMap<String,Artifact>();long total=0;
|
||||
for(var file:artifacts)if("ATTACHMENT".equals(file.kind())){
|
||||
if(!expected.containsKey(file.name())||stored.put(file.name(),file)!=null)throw ReportingException.conflict("附件关联重复或不属于当前快照");
|
||||
total+=file.length();
|
||||
}
|
||||
if(total>ReportingAttachmentPolicy.MAX_BYTES)throw ReportingException.invalid("批次附件总量超过8 MiB");
|
||||
var result=new ArrayList<Attachment>();
|
||||
expected.forEach((name,uses)->{
|
||||
var file=stored.get(name);String state=file==null?"MISSING":file.state();
|
||||
if(requireComplete&&!"BOUND".equals(state))throw ReportingException.conflict("附件未完整保存,不能审核或生成文件:"+name);
|
||||
result.add(new Attachment(name,name.substring(0,32),file==null?null:file.id(),state,file==null?0:file.length(),List.copyOf(uses)));
|
||||
});
|
||||
return List.copyOf(result);
|
||||
}
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
package cn.aixunkeji.datagov.integration.regulatoryreporting;
|
||||
|
||||
import java.io.*;
|
||||
import java.util.*;
|
||||
import java.util.zip.ZipInputStream;
|
||||
import javax.xml.XMLConstants;
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
import org.apache.pdfbox.Loader;
|
||||
import org.apache.pdfbox.text.PDFTextStripper;
|
||||
|
||||
/** Supplementary text only: never silently infer field constraints from prose. */
|
||||
final class ReportingDocumentNotes {
|
||||
record Note(String file,String location,String text,boolean confirmationRequired) { }
|
||||
static List<Note> extract(String name,byte[] bytes) throws IOException {
|
||||
List<Note> notes=new ArrayList<>();
|
||||
if(name.toLowerCase(Locale.ROOT).endsWith(".pdf")){
|
||||
try(var pdf=Loader.loadPDF(bytes)){
|
||||
if(pdf.isEncrypted()||pdf.getNumberOfPages()>200)throw ReportingException.invalid("PDF已加密或超过200页");
|
||||
var reader=new PDFTextStripper();int total=0;
|
||||
for(int page=1;page<=pdf.getNumberOfPages();page++){
|
||||
reader.setStartPage(page);reader.setEndPage(page);String text=reader.getText(pdf).strip();
|
||||
total+=text.length();if(total>200000)throw ReportingException.invalid("规范文本超过20万字符,请拆分文件");
|
||||
notes.add(new Note(name,"第"+page+"页",text.isBlank()?"未提取到文本;扫描页需人工识别和核对":text,true));
|
||||
}
|
||||
}
|
||||
}else{
|
||||
byte[] document=null;int count=0,total=0;Set<String> entries=new HashSet<>();
|
||||
try(var zip=new ZipInputStream(new ByteArrayInputStream(bytes))){
|
||||
for(var entry=zip.getNextEntry();entry!=null;entry=zip.getNextEntry()){
|
||||
if(++count>500||!entries.add(entry.getName())||entry.getName().contains("..")||entry.getName().startsWith("/"))throw ReportingException.invalid("DOCX压缩结构无效");
|
||||
var content=zip.readNBytes(2_000_001);total+=content.length;
|
||||
if(content.length>2_000_000||total>10_000_000)throw ReportingException.invalid("DOCX解压内容过大");
|
||||
if(entry.getName().equals("word/document.xml"))document=content;
|
||||
}
|
||||
}
|
||||
if(document==null)throw ReportingException.invalid("不是有效的DOCX文档");
|
||||
try{
|
||||
var f=DocumentBuilderFactory.newInstance();f.setNamespaceAware(true);f.setXIncludeAware(false);f.setExpandEntityReferences(false);
|
||||
f.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING,true);f.setFeature("http://apache.org/xml/features/disallow-doctype-decl",true);
|
||||
f.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD,"");f.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA,"");
|
||||
var doc=f.newDocumentBuilder().parse(new ByteArrayInputStream(document));
|
||||
var paragraphs=doc.getElementsByTagNameNS("http://schemas.openxmlformats.org/wordprocessingml/2006/main","p");int totalText=0;
|
||||
for(int i=0;i<paragraphs.getLength();i++){
|
||||
var text=new StringBuilder();var nodes=((org.w3c.dom.Element)paragraphs.item(i)).getElementsByTagNameNS("http://schemas.openxmlformats.org/wordprocessingml/2006/main","t");
|
||||
for(int j=0;j<nodes.getLength();j++)text.append(nodes.item(j).getTextContent());
|
||||
if(text.isEmpty())continue;totalText+=text.length();if(totalText>200000||notes.size()>=2000)throw ReportingException.invalid("DOCX文本过多,请拆分文件");
|
||||
notes.add(new Note(name,"段落"+(i+1),text.toString(),true));
|
||||
}
|
||||
}catch(ReportingException e){throw e;}catch(Exception e){throw ReportingException.invalid("DOCX正文XML无效");}
|
||||
}
|
||||
if(notes.isEmpty())notes.add(new Note(name,"正文","未提取到可识别文本,请人工核对",true));
|
||||
return List.copyOf(notes);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -5,7 +5,7 @@ import org.springframework.dao.DuplicateKeyException;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@RestControllerAdvice(assignableTypes = { ReportingController.class, ReportingStandardController.class })
|
||||
@RestControllerAdvice(assignableTypes = { ReportingController.class, ReportingStandardController.class, ReportingImportController.class, ReportingPlanController.class, ReportingExecutionController.class })
|
||||
class ReportingExceptionHandler {
|
||||
@ExceptionHandler(ReportingException.class)
|
||||
ResponseEntity<R<Void>> handle(ReportingException error) {
|
||||
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package cn.aixunkeji.datagov.integration.regulatoryreporting;
|
||||
|
||||
import java.util.*;
|
||||
import cn.aixunkeji.datagov.dataproduct.api.reporting.ReportingDatasetDirectory;
|
||||
|
||||
public final class ReportingExecutionApi {
|
||||
private ReportingExecutionApi() { }
|
||||
public record Selection(String resourceCode,String periodField,List<String> keyFields,List<ReportingDatasetDirectory.Filter> filters,List<String> attachmentFields) {
|
||||
public Selection { attachmentFields=attachmentFields==null?List.of():List.copyOf(attachmentFields); }
|
||||
public Selection(String resourceCode,String periodField,List<String> keyFields,List<ReportingDatasetDirectory.Filter> filters){this(resourceCode,periodField,keyFields,filters,List.of());}
|
||||
}
|
||||
public record TaskDefinition(String name,String planId,long planVersion,String periodType,List<Selection> selections) { }
|
||||
public record TaskSave(long version,TaskDefinition definition) { }
|
||||
public record Task(String id,long version,boolean enabled,TaskDefinition definition,String updatedAt) { }
|
||||
public record CreateBatch(String taskId,long taskVersion,String startDate,String endDate) { }
|
||||
public record Action(long version,String reason) { }
|
||||
public record Frozen(ReportingPlanApi.View plan,ReportingStandardApi.Definition standard,List<ReportingStandardApi.Template> templates,List<Selection> selections) { }
|
||||
public record Issue(String resource,int row,String key,String field,String rule,String severity,String message) { }
|
||||
public record Batch(String id,String taskId,long taskVersion,long version,String state,String startDate,String endDate,
|
||||
int rowCount,int blockingCount,int warningCount,List<Issue> issues,String snapshotId,String packageId,String message,String updatedAt) { }
|
||||
public record SourceProof(String resource,ReportingDatasetDirectory.Read query,String authorizationSha256,String observedAt) { }
|
||||
public record ResourceRows(String resource,List<Map<String,String>> rows,List<Map<String,String>> sourceKeys) {
|
||||
public ResourceRows(String resource,List<Map<String,String>> rows){this(resource,rows,List.of());}
|
||||
}
|
||||
public record QualityEvidence(long ruleId,long snapshotId,String configSha256,String operationKey,String state,Long validationId,String evidenceRef) { }
|
||||
public record Snapshot(String batchId,String startDate,String endDate,String definitionSha256,List<ResourceRows> resources,List<QualityEvidence> sourceQualityEvidence) {
|
||||
public Snapshot(String batchId,String startDate,String endDate,String definitionSha256,List<ResourceRows> resources){this(batchId,startDate,endDate,definitionSha256,resources,List.of());}
|
||||
}
|
||||
public record Artifact(String id,String batchId,String kind,String name,String sha256,long length,String state,String createdAt) { }
|
||||
public record AttachmentUse(String resource,int row,String field) { }
|
||||
public record Attachment(String name,String md5,String artifactId,String state,long length,List<AttachmentUse> uses) { }
|
||||
public record Precheck(boolean fileReady,boolean submissionReady,List<String> blockers) { }
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package cn.aixunkeji.datagov.integration.regulatoryreporting;
|
||||
|
||||
import cn.aixunkeji.common.core.domain.R;
|
||||
import cn.dev33.satoken.annotation.SaCheckPermission;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.http.*;
|
||||
import java.util.List;
|
||||
import static cn.aixunkeji.datagov.integration.regulatoryreporting.ReportingExecutionApi.*;
|
||||
|
||||
@RestController @RequiredArgsConstructor
|
||||
@RequestMapping("/api/integration/v1/regulatory-reporting/execution")
|
||||
@SaCheckPermission(ReportingActor.PREFIX+"view")
|
||||
class ReportingExecutionController {
|
||||
private final ReportingExecutionService service;
|
||||
@GetMapping("/quality-rules/{ruleId}/reference") @SaCheckPermission(ReportingActor.PREFIX+"standard")
|
||||
public R<String> qualityReference(@PathVariable long ruleId){return R.ok(service.qualityReference(ruleId));}
|
||||
@GetMapping("/tasks") public R<ReportingApi.Page<Task>> tasks(@RequestParam(defaultValue="1") int pageNum,@RequestParam(defaultValue="20") int pageSize){return R.ok(service.tasks(pageNum,pageSize));}
|
||||
@PutMapping("/tasks/{id}") @SaCheckPermission(ReportingActor.PREFIX+"edit") public R<Task> save(@PathVariable String id,@RequestBody TaskSave request){return R.ok(service.saveTask(id,request));}
|
||||
@PostMapping("/tasks/{id}/{operation:enable|disable}") @SaCheckPermission(ReportingActor.PREFIX+"edit") public R<Task> enable(@PathVariable String id,@PathVariable String operation,@RequestBody Action action){return R.ok(service.enable(id,action,"enable".equals(operation)));}
|
||||
@GetMapping("/batches") public R<ReportingApi.Page<Batch>> batches(@RequestParam String taskId,@RequestParam(defaultValue="1") int pageNum,@RequestParam(defaultValue="20") int pageSize){return R.ok(service.batches(taskId,pageNum,pageSize));}
|
||||
@GetMapping("/batches/{id}") public R<Batch> get(@PathVariable String id){return R.ok(service.get(id));}
|
||||
@PutMapping("/batches/{id}") @SaCheckPermission(ReportingActor.PREFIX+"edit") public R<Batch> create(@PathVariable String id,@RequestBody CreateBatch request){return R.ok(service.create(id,request));}
|
||||
@PostMapping("/batches/{id}/{operation:prepare|approve|reject|generate|cancel}") @SaCheckPermission(ReportingActor.PREFIX+"edit")
|
||||
public R<Batch> action(@PathVariable String id,@PathVariable String operation,@RequestBody Action action){return R.ok(switch(operation){case "prepare"->service.prepare(id,action);case "approve"->service.review(id,action,true);case "reject"->service.review(id,action,false);case "generate"->service.generate(id,action);case "cancel"->service.cancel(id,action);default->throw ReportingException.invalid("操作无效");});}
|
||||
@PostMapping("/batches/{id}/reconcile") @SaCheckPermission(ReportingActor.PREFIX+"edit") public R<Batch> reconcile(@PathVariable String id){return R.ok(service.reconcile(id));}
|
||||
@GetMapping("/batches/{id}/precheck") public R<Precheck> precheck(@PathVariable String id){return R.ok(service.precheck(id));}
|
||||
@GetMapping("/batches/{id}/files") public R<List<Artifact>> files(@PathVariable String id){return R.ok(service.artifacts(id));}
|
||||
@GetMapping("/batches/{id}/attachments") public R<List<Attachment>> attachments(@PathVariable String id){return R.ok(service.attachments(id));}
|
||||
@PostMapping(value="/batches/{id}/attachments",consumes=MediaType.MULTIPART_FORM_DATA_VALUE)
|
||||
@SaCheckPermission(ReportingActor.PREFIX+"edit")
|
||||
public R<Batch> attach(@PathVariable String id,@RequestParam long version,@RequestParam String name,@RequestPart("file") org.springframework.web.multipart.MultipartFile file) throws java.io.IOException {
|
||||
if(file.isEmpty()||file.getSize()>cn.aixunkeji.resource.api.assetupgrade.ReportingAttachmentPolicy.MAX_BYTES)throw ReportingException.invalid("附件为空或超过8 MiB");
|
||||
return R.ok(service.attach(id,version,name,file.getOriginalFilename(),file.getBytes()));
|
||||
}
|
||||
@GetMapping("/batches/{id}/files/{fileId}") public ResponseEntity<byte[]> download(@PathVariable String id,@PathVariable String fileId){return ResponseEntity.ok().header(HttpHeaders.CACHE_CONTROL,"no-store").header(HttpHeaders.CONTENT_DISPOSITION,"attachment; filename=reporting-"+ReportingPolicy.id(fileId)+".bin").contentType(MediaType.APPLICATION_OCTET_STREAM).body(service.download(id,fileId));}
|
||||
@GetMapping("/batches/{id}/audit") public R<ReportingApi.Page<ReportingApi.Audit>> audit(@PathVariable String id,@RequestParam(defaultValue="1") int pageNum,@RequestParam(defaultValue="20") int pageSize){return R.ok(service.history(id,pageNum,pageSize));}
|
||||
}
|
||||
+236
@@ -0,0 +1,236 @@
|
||||
package cn.aixunkeji.datagov.integration.regulatoryreporting;
|
||||
|
||||
import java.util.*;
|
||||
import java.time.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.apache.dubbo.config.annotation.DubboReference;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
import cn.aixunkeji.datagov.dataproduct.api.reporting.ReportingDatasetDirectory;
|
||||
import static cn.aixunkeji.datagov.integration.regulatoryreporting.ReportingExecutionApi.*;
|
||||
import static cn.aixunkeji.datagov.integration.regulatoryreporting.ReportingException.*;
|
||||
|
||||
@Service @RequiredArgsConstructor
|
||||
class ReportingExecutionService {
|
||||
private final JdbcTemplate jdbc;
|
||||
private final JsonMapper json;
|
||||
private final ReportingActor actors;
|
||||
private final ReportingPlanService plans;
|
||||
private final ReportingStandardService standards;
|
||||
private final ReportingRepository audit;
|
||||
private final ReportingFiles files;
|
||||
private final ReportingQuality quality;
|
||||
private final org.springframework.transaction.support.TransactionTemplate transactions;
|
||||
@DubboReference(version=ReportingDatasetDirectory.VERSION,group=ReportingDatasetDirectory.GROUP,check=false,retries=0,timeout=30000)
|
||||
private ReportingDatasetDirectory datasets;
|
||||
|
||||
String qualityReference(long ruleId){return quality.resolveReference(actors.current("standard"),ruleId);}
|
||||
|
||||
ReportingApi.Page<Task> tasks(int page,int size){var a=actors.current("view");ReportingService.paging(page,size);
|
||||
var ids=jdbc.query("SELECT task_id FROM dg_reporting_task WHERE organization_id=? ORDER BY update_time DESC,task_id LIMIT ? OFFSET ?",(r,n)->r.getString(1),a.organization(),size,(page-1)*size);
|
||||
return new ReportingApi.Page<>(ids.stream().map(id->task(a,id,false)).toList(),jdbc.queryForObject("SELECT COUNT(*) FROM dg_reporting_task WHERE organization_id=?",Long.class,a.organization()));}
|
||||
Task task(ReportingActor.Scope a,String id,boolean lock){ReportingPolicy.id(id);return jdbc.query("SELECT * FROM dg_reporting_task WHERE organization_id=? AND task_id=?"+(lock?" FOR UPDATE":""),(r,n)->new Task(id,r.getLong("version"),r.getInt("enabled")==1,json.readValue(r.getString("definition_json"),TaskDefinition.class),r.getTimestamp("update_time").toLocalDateTime().toString()),a.organization(),id).stream().findFirst().orElseThrow(ReportingException::forbidden);}
|
||||
@Transactional public Task saveTask(String id,TaskSave request){
|
||||
var a=actors.current("edit");ReportingPolicy.id(id);if(request==null||request.version() < -1||request.version()==Long.MAX_VALUE)throw invalid("任务版本无效");
|
||||
var d=normalizeTask(request.definition());String hash=ReportingService.hash(json.writeValueAsString(new TaskSave(request.version(),d)));
|
||||
var count=jdbc.queryForObject("SELECT COUNT(*) FROM dg_reporting_task WHERE organization_id=? AND task_id=?",Integer.class,a.organization(),id);
|
||||
if(count>0){var before=task(a,id,true);if(hash.equals(jdbc.queryForObject("SELECT command_sha256 FROM dg_reporting_task WHERE organization_id=? AND task_id=?",String.class,a.organization(),id)))return before;
|
||||
if(before.version()!=request.version())throw conflict("任务已变化,请刷新");
|
||||
}else if(request.version()!=-1)throw forbidden();
|
||||
var plan=plans.read(a,d.planId(),false);if(plan==null)throw forbidden();
|
||||
if(!"FROZEN".equals(plan.state())||plan.version()!=d.planVersion()||!plans.check(plan.definition()).configurationValid())throw conflict("请选择当前可用的冻结方案版本");
|
||||
validateSelections(d,plan);
|
||||
if(count==0)jdbc.update("INSERT INTO dg_reporting_task(organization_id,task_id,task_name,plan_id,plan_version,definition_json,command_sha256,create_by,update_by) VALUES(?,?,?,?,?,?,?,?,?)",a.organization(),id,d.name(),d.planId(),d.planVersion(),json.writeValueAsString(d),hash,a.user(),a.user());
|
||||
else if(jdbc.update("UPDATE dg_reporting_task SET task_name=?,plan_id=?,plan_version=?,definition_json=?,command_sha256=?,version=version+1,update_by=?,update_time=CURRENT_TIMESTAMP WHERE organization_id=? AND task_id=? AND version=?",d.name(),d.planId(),d.planVersion(),json.writeValueAsString(d),hash,a.user(),a.organization(),id,request.version())!=1)throw conflict("任务版本已变化");
|
||||
audit.audit(a,id,count==0?"TASK_CREATE":"TASK_UPDATE",request.version()+1);return task(a,id,false);
|
||||
}
|
||||
@Transactional public Task enable(String id,Action action,boolean enabled){
|
||||
var a=actors.current("edit");validate(action);var before=task(a,id,true);String hash=command("TASK_ENABLED_"+enabled,action);
|
||||
if(hash.equals(jdbc.queryForObject("SELECT command_sha256 FROM dg_reporting_task WHERE organization_id=? AND task_id=?",String.class,a.organization(),id)))return before;
|
||||
if(before.version()!=action.version())throw conflict("任务版本已变化");
|
||||
jdbc.update("UPDATE dg_reporting_task SET enabled=?,version=version+1,command_sha256=?,update_by=?,update_time=CURRENT_TIMESTAMP WHERE organization_id=? AND task_id=?",enabled?1:0,hash,a.user(),a.organization(),id);
|
||||
audit.audit(a,id,enabled?"TASK_ENABLE":"TASK_DISABLE",action.version()+1,action.reason());return task(a,id,false);
|
||||
}
|
||||
ReportingApi.Page<Batch> batches(String taskId,int page,int size){var a=actors.current("view");ReportingService.paging(page,size);task(a,taskId,false);
|
||||
var ids=jdbc.query("SELECT batch_id FROM dg_reporting_batch WHERE organization_id=? AND task_id=? ORDER BY create_time DESC,batch_id LIMIT ? OFFSET ?",(r,n)->r.getString(1),a.organization(),taskId,size,(page-1)*size);
|
||||
return new ReportingApi.Page<>(ids.stream().map(id->batch(a,id)).toList(),jdbc.queryForObject("SELECT COUNT(*) FROM dg_reporting_batch WHERE organization_id=? AND task_id=?",Long.class,a.organization(),taskId));}
|
||||
Batch get(String id){return batch(actors.current("view"),id);}
|
||||
Batch batch(ReportingActor.Scope a,String id){ReportingPolicy.id(id);return jdbc.query("SELECT * FROM dg_reporting_batch WHERE organization_id=? AND batch_id=?",(r,n)->new Batch(id,r.getString("task_id"),r.getLong("task_version"),r.getLong("version"),r.getString("batch_state"),r.getString("start_date"),r.getString("end_date"),r.getInt("row_count"),r.getInt("blocking_count"),r.getInt("warning_count"),Arrays.asList(json.readValue(r.getString("issue_json"),Issue[].class)),r.getString("snapshot_id"),r.getString("package_id"),r.getString("message"),r.getTimestamp("update_time").toLocalDateTime().toString()),a.organization(),id).stream().findFirst().orElseThrow(ReportingException::forbidden);}
|
||||
Frozen frozen(ReportingActor.Scope a,String id){batch(a,id);return json.readValue(jdbc.queryForObject("SELECT frozen_json FROM dg_reporting_batch WHERE organization_id=? AND batch_id=?",String.class,a.organization(),id),Frozen.class);}
|
||||
@Transactional public Batch create(String id,CreateBatch request){
|
||||
var a=actors.current("edit");ReportingPolicy.id(id);if(request==null)throw invalid("请选择任务和期间");
|
||||
String hash=ReportingService.hash(json.writeValueAsString(request));
|
||||
var old=jdbc.query("SELECT create_sha256 FROM dg_reporting_batch WHERE organization_id=? AND batch_id=?",(r,n)->r.getString(1),a.organization(),id);
|
||||
if(!old.isEmpty()){if(!hash.equals(old.getFirst()))throw conflict("批次标识已用于其他请求");return batch(a,id);}
|
||||
var task=task(a,request.taskId(),true);if(!task.enabled()||task.version()!=request.taskVersion())throw conflict("任务已停用或版本变化");
|
||||
period(task.definition().periodType(),request.startDate(),request.endDate());
|
||||
var plan=plans.read(a,task.definition().planId(),false);
|
||||
if(plan==null||!"FROZEN".equals(plan.state())||plan.version()!=task.definition().planVersion()||!plans.check(plan.definition()).configurationValid())throw conflict("方案或其基础引用已变化,请修订任务");
|
||||
var standard=standards.read(a,plan.definition().standardId(),false);
|
||||
if(standard==null||!"PUBLISHED".equals(standard.status())||standard.version()!=plan.definition().standardVersion())throw conflict("标准固定版本不可用");
|
||||
var templates=standard.definition().resources().stream().filter(r->r.templateId()!=null&&!r.templateId().isBlank()).map(r->standards.template(a,r.templateId())).toList();
|
||||
var captured=new Frozen(plan,standard.definition(),templates,task.definition().selections());String value=json.writeValueAsString(captured);
|
||||
jdbc.update("INSERT INTO dg_reporting_batch(organization_id,batch_id,task_id,task_version,batch_state,start_date,end_date,frozen_json,frozen_sha256,issue_json,create_sha256,command_sha256,create_by,update_by) VALUES(?,?,?,?,'DRAFT',?,?,?,?, '[]',?,?,?,?)",a.organization(),id,task.id(),task.version(),request.startDate(),request.endDate(),value,ReportingService.hash(value),hash,hash,a.user(),a.user());
|
||||
audit.audit(a,id,"BATCH_CREATE",0);return batch(a,id);
|
||||
}
|
||||
Batch prepare(String id,Action action){
|
||||
var a=actors.current("edit");var before=batch(a,id);if(!claim(a,before,action,"PREPARE",Set.of("DRAFT"),"READING"))return batch(a,id);
|
||||
try{
|
||||
var fixed=frozen(a,id);requireActive(a,before,fixed);
|
||||
List<ResourceRows> rows=new ArrayList<>();List<Issue> issues=new ArrayList<>();List<SourceProof> proofs=new ArrayList<>();int count=0,totalBytes=0;
|
||||
ReportingRows.rules(fixed.standard(),issues);
|
||||
var qualityEvidence=quality.execute(a,id,before.startDate(),fixed.standard(),issues);
|
||||
for(var resource:fixed.standard().resources()){
|
||||
var binding=fixed.plan().definition().bindings().stream().filter(b->b.resourceCode().equals(resource.code())).findFirst().orElseThrow();
|
||||
var selection=fixed.selections().stream().filter(s->s.resourceCode().equals(resource.code())).findFirst().orElseThrow();
|
||||
var dataset=datasets.resolve(binding.datasetId());requireVersion(binding,dataset);
|
||||
var columns=new LinkedHashSet<String>();binding.mappings().forEach(m->columns.addAll(ReportingMapping.sources(m)));columns.addAll(selection.keyFields());
|
||||
var filters=new ArrayList<>(selection.filters());
|
||||
if(!selection.periodField().isBlank()){filters.add(new ReportingDatasetDirectory.Filter(selection.periodField(),"GTE",List.of(before.startDate())));filters.add(new ReportingDatasetDirectory.Filter(selection.periodField(),"LT",List.of(before.endDate())));}
|
||||
var query=new ReportingDatasetDirectory.Read(dataset,List.copyOf(columns),List.copyOf(filters));var data=datasets.read(query);
|
||||
if(data==null||!data.complete()||!dataset.equals(data.dataset())||!query.columns().equals(data.columns())||data.authorizationSha256()==null||data.rows().size()>100000)throw conflict("数据未完整读取,不能生成快照");
|
||||
totalBytes+=json.writeValueAsBytes(data.rows()).length;if(totalBytes>8_000_000)throw invalid("批次数据总量超过8 MB,请缩小期间或过滤范围");
|
||||
var result=ReportingRows.map(resource,binding,selection,data.rows());rows.add(result.data());issues.addAll(result.issues());if(issues.size()>2000)throw invalid("校验问题超过2000项");count+=data.rows().size();
|
||||
proofs.add(new SourceProof(resource.code(),query,data.authorizationSha256(),data.observedAt()));
|
||||
}
|
||||
for(var proof:proofs)datasets.authorize(proof.query(),proof.authorizationSha256());requireActive(a,before,fixed);
|
||||
int blocking=(int)issues.stream().filter(i->"BLOCKING".equals(i.severity())).count(),warnings=issues.size()-blocking;
|
||||
jdbc.update("UPDATE dg_reporting_batch SET issue_json=?,row_count=?,blocking_count=?,warning_count=? WHERE organization_id=? AND batch_id=? AND batch_state='READING'",json.writeValueAsString(issues),count,blocking,warnings,a.organization(),id);
|
||||
var snapshot=new Snapshot(id,before.startDate(),before.endDate(),definitionHash(a,id),List.copyOf(rows),qualityEvidence);
|
||||
ReportingAttachments.expected(fixed,snapshot);
|
||||
String artifact=files.write(a,id,"SNAPSHOT","snapshot.json","application/json",json.writeValueAsBytes(snapshot),List.copyOf(proofs));
|
||||
finish(a,id,"READING",blocking>0?"VALIDATION_FAILED":"REVIEW_PENDING",artifact,null,blocking>0?"存在阻断问题,请整改后创建新批次":"候选数据已完整保存,等待审核;不表示已报送");
|
||||
}catch(RuntimeException e){failure(a,id,"READING",e instanceof ReportingException?e.getMessage():"数据读取、校验或文件保存未完成;请核对数据访问权限、范围和文件操作");}
|
||||
return batch(a,id);
|
||||
}
|
||||
@Transactional public Batch review(String id,Action action,boolean approve){
|
||||
var a=actors.current("edit");var b=batch(a,id);String hash=command(approve?"APPROVE":"REJECT",action);
|
||||
if(same(a,id,hash))return b;validate(action);
|
||||
if(!"REVIEW_PENDING".equals(b.state())||b.version()!=action.version()||b.blockingCount()>0||b.snapshotId()==null)throw conflict("批次未通过校验或状态已变化");
|
||||
if(approve)quality.validateCurrent(a,frozen(a,id).standard());
|
||||
// Physical bytes are immutable before review; freezing fixes the approved reference, not a fresh source read.
|
||||
if(!"BOUND".equals(files.required(a,b.snapshotId()).state()))throw conflict("候选快照尚未完成绑定");
|
||||
var fixed=frozen(a,id);
|
||||
if(approve&&ReportingAttachments.configured(fixed))attachmentBytes(a,b,fixed,readSnapshot(a,b));
|
||||
if(jdbc.update("UPDATE dg_reporting_batch SET batch_state=?,version=version+1,command_sha256=?,message=?,update_by=?,update_time=CURRENT_TIMESTAMP WHERE organization_id=? AND batch_id=? AND version=?",approve?"FROZEN":"REJECTED",hash,approve?"已审核并冻结快照":"审核驳回;整改后创建新批次",a.user(),a.organization(),id,b.version())!=1)throw conflict("批次已变化");
|
||||
audit.audit(a,id,approve?"BATCH_APPROVE_AND_FREEZE":"BATCH_REJECT",b.version()+1,action.reason());return batch(a,id);
|
||||
}
|
||||
Batch generate(String id,Action action){
|
||||
var a=actors.current("edit");var before=batch(a,id);if(!claim(a,before,action,"GENERATE",Set.of("FROZEN"),"GENERATING"))return batch(a,id);
|
||||
try{
|
||||
var snapshot=json.readValue(files.read(a,before.snapshotId()),Snapshot.class);var fixed=frozen(a,id);verifySnapshot(a,before,snapshot);
|
||||
byte[] bytes=ReportingPackage.generate(fixed,snapshot,attachmentBytes(a,before,fixed,snapshot));
|
||||
String artifact=files.write(a,id,"PACKAGE","reporting_"+id+".zip","application/zip",bytes,files.required(a,before.snapshotId()).proofs());
|
||||
finish(a,id,"GENERATING","FILE_READY",null,artifact,"文件已生成;尚未提交监管系统");
|
||||
}catch(RuntimeException e){failure(a,id,"GENERATING",e instanceof ReportingException?e.getMessage():"文件生成或保存未完成,请核对原文件操作");}
|
||||
return batch(a,id);
|
||||
}
|
||||
Batch reconcile(String id){
|
||||
var a=actors.current("edit");var b=batch(a,id);
|
||||
if(Set.of("ATTACHING","ATTACHMENT_UNKNOWN").contains(b.state()))return reconcileAttachments(a,b);
|
||||
if(!Set.of("READING","GENERATING","UNKNOWN").contains(b.state()))throw conflict("此状态不需要核对");
|
||||
if(!"UNKNOWN".equals(b.state())&&LocalDateTime.parse(b.updatedAt()).isAfter(LocalDateTime.now().minusMinutes(5)))throw conflict("操作仍在执行,请稍后刷新;超过5分钟后可以核对");
|
||||
boolean generating=b.snapshotId()!=null;
|
||||
String artifact=files.reconcile(a,id,generating?"PACKAGE":"SNAPSHOT");
|
||||
if(!generating){var snapshot=json.readValue(files.read(a,artifact),Snapshot.class);verifySnapshot(a,b,snapshot);}
|
||||
finish(a,id,b.state(),generating?"FILE_READY":b.blockingCount()>0?"VALIDATION_FAILED":"REVIEW_PENDING",generating?null:artifact,generating?artifact:null,"已核对同一私有文件操作,未重复读取源数据");return batch(a,id);
|
||||
}
|
||||
@Transactional public Batch cancel(String id,Action action){var a=actors.current("edit");var b=batch(a,id);claim(a,b,action,"CANCEL",Set.of("DRAFT","VALIDATION_FAILED","REJECTED","FAILED","FROZEN","REVIEW_PENDING","FILE_READY"),"CANCELED");return batch(a,id);}
|
||||
List<Artifact> artifacts(String id){var a=actors.current("view");var b=batch(a,id);if(b.snapshotId()!=null)files.authorizeMetadata(a,b.snapshotId());return files.list(a,id);}
|
||||
List<Attachment> attachments(String id){var a=actors.current("view");var b=batch(a,id);if(b.snapshotId()==null)return List.of();return ReportingAttachments.describe(frozen(a,id),readSnapshot(a,b),files.list(a,id),false);}
|
||||
Batch attach(String id,long version,String name,String original,byte[] bytes){
|
||||
var a=actors.current("edit");var b=batch(a,id);
|
||||
ReportingAttachments.validateUpload(name,original,bytes);
|
||||
var action=new Action(version,"附件:"+name+":"+ReportingFiles.sha(bytes));
|
||||
if(same(a,id,command("ATTACH",action)))return b;
|
||||
if(!"REVIEW_PENDING".equals(b.state())||b.version()!=version)throw conflict("仅待审核批次可上传附件,请刷新状态");
|
||||
var fixed=frozen(a,id);var snapshot=readSnapshot(a,b);var manifest=ReportingAttachments.describe(fixed,snapshot,files.list(a,id),false);
|
||||
var expected=manifest.stream().filter(f->f.name().equals(name)).findFirst().orElseThrow(()->invalid("附件不属于当前快照中的业务记录"));
|
||||
if(expected.artifactId()!=null)throw conflict("该附件已登记,待核对时请核对原文件操作");
|
||||
if(manifest.stream().mapToLong(Attachment::length).sum()+bytes.length>cn.aixunkeji.resource.api.assetupgrade.ReportingAttachmentPolicy.MAX_BYTES)throw invalid("批次附件总量超过8 MiB");
|
||||
if(!claim(a,b,action,"ATTACH",Set.of("REVIEW_PENDING"),"ATTACHING"))return batch(a,id);
|
||||
try{
|
||||
files.write(a,id,"ATTACHMENT:"+(version+1),name,cn.aixunkeji.resource.api.assetupgrade.ReportingAttachmentPolicy.mime(original),bytes,files.required(a,b.snapshotId()).proofs());
|
||||
finish(a,id,"ATTACHING","REVIEW_PENDING",null,null,"附件已关联快照记录;全部附件齐备后可以审核");
|
||||
}catch(RuntimeException e){finish(a,id,"ATTACHING","ATTACHMENT_UNKNOWN",null,null,"附件写入未确认;请核对原操作,不能重复上传或审核");}
|
||||
return batch(a,id);
|
||||
}
|
||||
private Batch reconcileAttachments(ReportingActor.Scope a,Batch b){
|
||||
if("ATTACHING".equals(b.state())&&LocalDateTime.parse(b.updatedAt()).isAfter(LocalDateTime.now().minusMinutes(5)))throw conflict("附件正在保存,请稍后刷新;超过5分钟后可以核对");
|
||||
// The claimed version identifies exactly this upload, including a BOUND write whose batch update was lost.
|
||||
// Absence of its persisted operation is not proof of completion; never unlock another upload on that basis.
|
||||
String kind="ATTACHMENT:"+("ATTACHING".equals(b.state())?b.version():b.version()-1);
|
||||
files.reconcile(a,b.id(),kind);
|
||||
var fixed=frozen(a,b.id());var snapshot=readSnapshot(a,b);
|
||||
var manifest=ReportingAttachments.describe(fixed,snapshot,files.list(a,b.id()),false);
|
||||
for(var attachment:manifest)if(attachment.artifactId()!=null)verifyAttachment(a,attachment);
|
||||
finish(a,b.id(),b.state(),"REVIEW_PENDING",null,null,"已核对原附件操作;请检查附件清单,缺失文件仍须补齐后审核");return batch(a,b.id());
|
||||
}
|
||||
private Snapshot readSnapshot(ReportingActor.Scope a,Batch b){
|
||||
if(b.snapshotId()==null)throw conflict("批次尚无候选快照");
|
||||
var snapshot=json.readValue(files.read(a,b.snapshotId()),Snapshot.class);verifySnapshot(a,b,snapshot);return snapshot;
|
||||
}
|
||||
private Map<String,byte[]> attachmentBytes(ReportingActor.Scope a,Batch b,Frozen fixed,Snapshot snapshot){
|
||||
var result=new LinkedHashMap<String,byte[]>();
|
||||
for(var attachment:ReportingAttachments.describe(fixed,snapshot,files.list(a,b.id()),true))result.put(attachment.name(),verifyAttachment(a,attachment));
|
||||
return result;
|
||||
}
|
||||
private byte[] verifyAttachment(ReportingActor.Scope a,Attachment attachment){
|
||||
byte[] bytes=files.read(a,attachment.artifactId());
|
||||
ReportingAttachments.validateUpload(attachment.name(),cn.aixunkeji.resource.api.assetupgrade.ReportingAttachmentPolicy.originalName(attachment.name()),bytes);return bytes;
|
||||
}
|
||||
byte[] download(String batchId,String artifactId){var a=actors.current("view");batch(a,batchId);var f=files.required(a,artifactId);if(!batchId.equals(f.batchId()))throw forbidden();return files.read(a,artifactId);}
|
||||
ReportingApi.Page<ReportingApi.Audit> history(String id,int page,int size){var a=actors.current("view");batch(a,id);ReportingService.paging(page,size);return audit.objectHistory(a,id,page,size);}
|
||||
Precheck precheck(String id){var b=get(id);List<String> blockers=new ArrayList<>();if(!"FILE_READY".equals(b.state())||b.packageId()==null)blockers.add("未生成已审核批次的正式文件");blockers.add("缺少对应B接口版本的地址、认证、签名和回执契约,外部提交尚不可用");return new Precheck("FILE_READY".equals(b.state()),false,List.copyOf(blockers));}
|
||||
private void requireActive(ReportingActor.Scope a,Batch b,Frozen frozen){var task=task(a,b.taskId(),false);var plan=plans.read(a,frozen.plan().id(),false);if(!task.enabled()||plan==null||!"FROZEN".equals(plan.state())||plan.version()!=frozen.plan().version()||!plans.check(plan.definition()).configurationValid())throw conflict("任务、方案或引用已停用或变化");}
|
||||
private String definitionHash(ReportingActor.Scope a,String id){return jdbc.queryForObject("SELECT frozen_sha256 FROM dg_reporting_batch WHERE organization_id=? AND batch_id=?",String.class,a.organization(),id);}
|
||||
private void verifySnapshot(ReportingActor.Scope a,Batch b,Snapshot s){if(!b.id().equals(s.batchId())||!b.startDate().equals(s.startDate())||!b.endDate().equals(s.endDate())||!definitionHash(a,b.id()).equals(s.definitionSha256()))throw conflict("快照不属于当前固定批次");}
|
||||
private boolean claim(ReportingActor.Scope a,Batch b,Action action,String operation,Set<String> allowed,String state){
|
||||
return Boolean.TRUE.equals(transactions.execute(status->claimInTransaction(a,b,action,operation,allowed,state)));
|
||||
}
|
||||
private boolean claimInTransaction(ReportingActor.Scope a,Batch b,Action action,String operation,Set<String> allowed,String state){
|
||||
validate(action);String hash=command(operation,action);if(same(a,b.id(),hash))return false;
|
||||
if(!allowed.contains(b.state())||b.version()!=action.version())throw conflict("批次状态或版本已变化,请刷新");
|
||||
if(jdbc.update("UPDATE dg_reporting_batch SET batch_state=?,version=version+1,command_sha256=?,update_by=?,update_time=CURRENT_TIMESTAMP WHERE organization_id=? AND batch_id=? AND version=?",state,hash,a.user(),a.organization(),b.id(),b.version())!=1)throw conflict("批次操作已被其他请求接管");
|
||||
audit.audit(a,b.id(),"BATCH_"+operation,b.version()+1,action.reason());return true;
|
||||
}
|
||||
private boolean same(ReportingActor.Scope a,String id,String hash){return hash.equals(jdbc.queryForObject("SELECT command_sha256 FROM dg_reporting_batch WHERE organization_id=? AND batch_id=?",String.class,a.organization(),id));}
|
||||
private String command(String operation,Action action){validate(action);return ReportingService.hash(json.writeValueAsString(List.of(operation,action.version(),action.reason())));}
|
||||
private static void validate(Action a){if(a==null||a.version()<0||a.version()==Long.MAX_VALUE)throw invalid("操作版本无效");if(a.reason()==null||a.reason().length()>1000)throw invalid("操作意见必须为1至1000字");ReportingPolicy.text(a.reason(),1000,true,"操作原因/审核意见");}
|
||||
private void finish(ReportingActor.Scope a,String id,String old,String state,String snapshot,String file,String message){
|
||||
transactions.executeWithoutResult(status->finishInTransaction(a,id,old,state,snapshot,file,message));
|
||||
}
|
||||
private void finishInTransaction(ReportingActor.Scope a,String id,String old,String state,String snapshot,String file,String message){
|
||||
if(jdbc.update("UPDATE dg_reporting_batch SET batch_state=?,snapshot_id=COALESCE(?,snapshot_id),package_id=COALESCE(?,package_id),message=?,version=version+1,update_by=?,update_time=CURRENT_TIMESTAMP WHERE organization_id=? AND batch_id=? AND batch_state=?",state,snapshot,file,message,a.user(),a.organization(),id,old)!=1)throw conflict("批次已变化,请刷新核对");
|
||||
audit.audit(a,id,"BATCH_"+state,batch(a,id).version(),message);
|
||||
}
|
||||
private void failure(ReportingActor.Scope a,String id,String old,String message){boolean uncertain=files.list(a,id).stream().anyMatch(f->("READING".equals(old)?"SNAPSHOT":"PACKAGE").equals(f.kind()));finish(a,id,old,uncertain?"UNKNOWN":"FAILED",null,null,message);}
|
||||
private void validateSelections(TaskDefinition d,ReportingPlanApi.View plan){
|
||||
var expected=plan.definition().bindings().stream().map(ReportingPlanApi.Binding::resourceCode).collect(java.util.stream.Collectors.toSet());
|
||||
if(!expected.equals(d.selections().stream().map(Selection::resourceCode).collect(java.util.stream.Collectors.toSet())))throw invalid("任务必须为每张方案资源指定主键及期间过滤");
|
||||
for(var s:d.selections()){
|
||||
var b=plan.definition().bindings().stream().filter(v->v.resourceCode().equals(s.resourceCode())).findFirst().orElseThrow();var dataset=datasets.resolve(b.datasetId());requireVersion(b,dataset);
|
||||
var fields=dataset.fields().stream().map(ReportingDatasetDirectory.Field::name).toList();
|
||||
if(!fields.containsAll(s.keyFields())||!s.periodField().isBlank()&&!fields.contains(s.periodField())||s.filters().stream().anyMatch(f->!fields.contains(f.field())))throw invalid("任务主键或过滤字段不属于数据集");
|
||||
var targets=b.mappings().stream().map(ReportingPlanApi.Mapping::target).toList();
|
||||
if(!targets.containsAll(s.attachmentFields()))throw invalid("附件引用字段必须是方案中已映射的目标字段");
|
||||
}
|
||||
}
|
||||
static TaskDefinition normalizeTask(TaskDefinition d){
|
||||
if(d==null||d.planVersion()<0||d.selections()==null||d.selections().isEmpty()||d.selections().size()>50||!Set.of("MONTH","QUARTER","YEAR","CUSTOM").contains(Objects.toString(d.periodType(),"")))throw invalid("任务定义无效");ReportingPolicy.id(d.planId());Set<String> codes=new HashSet<>();
|
||||
for(var s:d.selections()){
|
||||
if(s==null||s.resourceCode()==null||!codes.add(s.resourceCode())||s.periodField()==null||s.keyFields()==null||s.keyFields().isEmpty()||s.keyFields().size()>10||new HashSet<>(s.keyFields()).size()!=s.keyFields().size()||s.filters()==null||s.filters().size()>18)throw invalid("资源、业务主键或过滤设置无效");
|
||||
if(s.attachmentFields().size()>20||new HashSet<>(s.attachmentFields()).size()!=s.attachmentFields().size()||s.attachmentFields().stream().anyMatch(f->f==null||f.isBlank()||f.length()>128))throw invalid("附件引用字段无效");
|
||||
for(var f:s.filters())if(f==null||f.field()==null||!Set.of("EQ","NE","GT","GTE","LT","LTE","IN","NOT_IN","IS_NULL","IS_NOT_NULL").contains(Objects.toString(f.operator(),""))||f.values()==null||f.values().size()>100||f.values().stream().anyMatch(v->v==null||v.length()>1000))throw invalid("过滤条件无效");
|
||||
}
|
||||
return new TaskDefinition(ReportingPolicy.text(d.name(),160,true,"任务名称"),d.planId(),d.planVersion(),d.periodType(),List.copyOf(d.selections()));
|
||||
}
|
||||
static void period(String type,String start,String end){try{
|
||||
LocalDate a=LocalDate.parse(start),b=LocalDate.parse(end);if(!a.isBefore(b)||a.getYear()<1900||b.getYear()>2200||java.time.temporal.ChronoUnit.DAYS.between(a,b)>366)throw new IllegalArgumentException();
|
||||
boolean valid=switch(type){case "MONTH"->a.getDayOfMonth()==1&&b.equals(a.plusMonths(1));case "QUARTER"->a.getDayOfMonth()==1&&(a.getMonthValue()-1)%3==0&&b.equals(a.plusMonths(3));case "YEAR"->a.getDayOfYear()==1&&b.equals(a.plusYears(1));case "CUSTOM"->true;default->false;};if(!valid)throw new IllegalArgumentException();
|
||||
}catch(Exception e){throw invalid("期间须匹配任务周期,采用起日包含、止日不包含,最多366天");}}
|
||||
private static void requireVersion(ReportingPlanApi.Binding b,ReportingDatasetDirectory.Dataset d){if(d.version()!=b.datasetVersion()||!d.releaseId().equals(b.releaseId())||!d.schemaVersionId().equals(b.schemaVersionId())||!d.schemaSha256().equals(b.schemaSha256()))throw conflict("数据集发布或结构版本已变化");}
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package cn.aixunkeji.datagov.integration.regulatoryreporting;
|
||||
|
||||
import cn.aixunkeji.resource.api.assetupgrade.PrivateBusinessFileOwner.*;
|
||||
import org.apache.dubbo.config.annotation.DubboService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
@DubboService(group="aixun-datagov-private-file-integration",version="1.0.0",retries=0)
|
||||
@RequiredArgsConstructor
|
||||
public class ReportingFileAuthorization implements AuthorizationOwner {
|
||||
private final ReportingFiles files;
|
||||
@Override public AuthorizationDecision authorize(AuthorizationQuery query){
|
||||
try{return files.authorize(query);}catch(RuntimeException e){return new AuthorizationDecision(query,State.DENIED,null,0,null,null,null,false,"REPORTING_FILE_FORBIDDEN");}
|
||||
}
|
||||
}
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
package cn.aixunkeji.datagov.integration.regulatoryreporting;
|
||||
|
||||
import java.util.*;
|
||||
import java.time.Instant;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import org.apache.dubbo.config.annotation.DubboReference;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
import cn.aixunkeji.resource.api.assetupgrade.PrivateBusinessFileOwner;
|
||||
import cn.aixunkeji.resource.api.assetupgrade.PrivateBusinessFileOwner.*;
|
||||
import cn.aixunkeji.datagov.dataproduct.api.reporting.ReportingDatasetDirectory;
|
||||
import static cn.aixunkeji.datagov.integration.regulatoryreporting.ReportingExecutionApi.*;
|
||||
import static cn.aixunkeji.resource.api.assetupgrade.PrivateBusinessFileOwner.MAX_CHUNK_BYTES;
|
||||
|
||||
@Service @RequiredArgsConstructor
|
||||
class ReportingFiles {
|
||||
private final JdbcTemplate jdbc;
|
||||
private final JsonMapper json;
|
||||
private final ReportingActor actors;
|
||||
@DubboReference(version=PrivateBusinessFileOwner.VERSION,group=PrivateBusinessFileOwner.GROUP,check=false,retries=0,timeout=15000)
|
||||
private PrivateBusinessFileOwner files;
|
||||
@DubboReference(version=ReportingDatasetDirectory.VERSION,group=ReportingDatasetDirectory.GROUP,check=false,retries=0,timeout=10000)
|
||||
private ReportingDatasetDirectory datasets;
|
||||
record Stored(String id,String batchId,String kind,Target target,Binding binding,List<SourceProof> proofs,String operation,String state,long creator,String createdAt) { }
|
||||
String write(ReportingActor.Scope a,String batch,String kind,String name,String mime,byte[] bytes,List<SourceProof> proofs){
|
||||
if(bytes.length==0||bytes.length>10*1024*1024)throw ReportingException.invalid("批次文件为空或超过10 MiB;请缩小任务期间或过滤范围");
|
||||
String id=UUID.randomUUID().toString(),operation=ReportingService.hash("reporting:"+a.organization()+":"+id);
|
||||
var target=new Target("integration","REGULATORY_REPORTING_ARTIFACT",id,1,"PACKAGE".equals(kind)?FileUse.DELIVERY_PACKAGE:FileUse.EVIDENCE,
|
||||
"REGULATORY_REPORTING",batch,name,sha(bytes),bytes.length,mime,null,null);
|
||||
jdbc.update("INSERT INTO dg_reporting_artifact(organization_id,artifact_id,batch_id,artifact_kind,target_json,proof_json,operation_key,artifact_state,create_by) VALUES(?,?,?,?,?,?,?,'PENDING',?)",
|
||||
a.organization(),id,batch,kind,json.writeValueAsString(target),json.writeValueAsString(proofs),operation,a.user());
|
||||
var context=context(a,id);var query=new WriteQuery(context,operation);
|
||||
var status=files.stage(new StageRequest(context,target,operation,target.bytesSha256()));
|
||||
verifyBinding(target,status.binding());
|
||||
jdbc.update("UPDATE dg_reporting_artifact SET binding_json=? WHERE organization_id=? AND artifact_id=? AND artifact_state='PENDING'",json.writeValueAsString(status.binding()),a.organization(),id);
|
||||
if(status.state()!=WriteState.PREPARING)throw ReportingException.conflict("私有文件写入状态异常,需核对后继续");
|
||||
for(long offset=status.nextOffset();offset<bytes.length;){
|
||||
byte[] chunk=Arrays.copyOfRange(bytes,(int)offset,(int)Math.min(bytes.length,offset+MAX_CHUNK_BYTES));
|
||||
status=files.append(new AppendRequest(query,offset,chunk,sha(chunk)));
|
||||
if(status.nextOffset()!=offset+chunk.length)throw ReportingException.conflict("文件写入偏移不一致");offset=status.nextOffset();
|
||||
}
|
||||
status=files.finish(query);verifyBinding(target,status.binding());
|
||||
if(status.state()!=WriteState.STAGED)throw ReportingException.conflict("文件未完成暂存");
|
||||
Stored stored=required(a,id);readBytes(a,stored,true);
|
||||
commit(a,stored);return id;
|
||||
}
|
||||
private void commit(ReportingActor.Scope a,Stored stored){
|
||||
jdbc.update("UPDATE dg_reporting_artifact SET artifact_state='COMMITTED' WHERE organization_id=? AND artifact_id=? AND artifact_state='PENDING'",a.organization(),stored.id());
|
||||
var status=files.complete(new WriteQuery(context(a,stored.id()),stored.operation()));verifyBinding(stored.target(),status.binding());
|
||||
if(status.state()!=WriteState.BOUND)throw ReportingException.conflict("文件绑定结果未知,请核对后继续");
|
||||
jdbc.update("UPDATE dg_reporting_artifact SET artifact_state='BOUND' WHERE organization_id=? AND artifact_id=? AND artifact_state='COMMITTED'",a.organization(),stored.id());
|
||||
}
|
||||
/** Reconcile the SAME immutable operation; never regenerate source data on an uncertain write. */
|
||||
String reconcile(ReportingActor.Scope a,String batch,String kind){
|
||||
var found=jdbc.query("SELECT artifact_id FROM dg_reporting_artifact WHERE organization_id=? AND batch_id=? AND artifact_kind=?",(r,n)->r.getString(1),a.organization(),batch,kind);
|
||||
if(found.size()!=1)throw ReportingException.conflict("未发现唯一文件操作;请保留原批次并新建批次");
|
||||
return reconcileArtifact(a,found.getFirst());
|
||||
}
|
||||
String reconcileArtifact(ReportingActor.Scope a,String id){
|
||||
var stored=required(a,id);var status=files.status(new WriteQuery(context(a,stored.id()),stored.operation()));verifyBinding(stored.target(),status.binding());
|
||||
if(stored.binding()==null){jdbc.update("UPDATE dg_reporting_artifact SET binding_json=? WHERE organization_id=? AND artifact_id=?",json.writeValueAsString(status.binding()),a.organization(),stored.id());stored=required(a,stored.id());}
|
||||
if(status.state()==WriteState.STAGED){readBytes(a,stored,true);commit(a,stored);}
|
||||
else if(status.state()==WriteState.BOUND&&Set.of("COMMITTED","BOUND").contains(stored.state())){
|
||||
jdbc.update("UPDATE dg_reporting_artifact SET artifact_state='BOUND' WHERE organization_id=? AND artifact_id=?",a.organization(),stored.id());read(a,stored.id());
|
||||
}else throw ReportingException.conflict("文件尚未完整暂存,不能认定成功;保留原操作并新建批次");
|
||||
return stored.id();
|
||||
}
|
||||
Stored required(ReportingActor.Scope a,String id){
|
||||
ReportingPolicy.id(id);
|
||||
return jdbc.query("SELECT * FROM dg_reporting_artifact WHERE organization_id=? AND artifact_id=?",(r,n)->new Stored(id,r.getString("batch_id"),r.getString("artifact_kind"),json.readValue(r.getString("target_json"),Target.class),r.getString("binding_json")==null?null:json.readValue(r.getString("binding_json"),Binding.class),Arrays.asList(json.readValue(r.getString("proof_json"),SourceProof[].class)),r.getString("operation_key"),r.getString("artifact_state"),r.getLong("create_by"),r.getTimestamp("create_time").toLocalDateTime().toString()),a.organization(),id).stream().findFirst().orElseThrow(ReportingException::forbidden);
|
||||
}
|
||||
List<Artifact> list(ReportingActor.Scope a,String batch){
|
||||
return jdbc.query("SELECT artifact_id FROM dg_reporting_artifact WHERE organization_id=? AND batch_id=? ORDER BY create_time,artifact_id",(r,n)->r.getString(1),a.organization(),batch).stream().map(id->{var s=required(a,id);return new Artifact(id,batch,s.kind().startsWith("ATTACHMENT:")?"ATTACHMENT":s.kind(),s.target().originalName(),s.target().bytesSha256(),s.target().byteLength(),s.state(),s.createdAt());}).toList();
|
||||
}
|
||||
byte[] read(ReportingActor.Scope a,String id){var s=required(a,id);if(!"BOUND".equals(s.state()))throw ReportingException.conflict("文件未完成绑定");return readBytes(a,s,false);}
|
||||
void authorizeMetadata(ReportingActor.Scope a,String id){
|
||||
var stored=required(a,id);if(stored.proofs().isEmpty())throw ReportingException.forbidden();
|
||||
for(var proof:stored.proofs())datasets.authorize(proof.query(),proof.authorizationSha256());
|
||||
}
|
||||
private byte[] readBytes(ReportingActor.Scope a,Stored s,boolean staged){
|
||||
if(staged&&s.creator()!=a.user()||s.binding()==null)throw ReportingException.forbidden();
|
||||
var out=new ByteArrayOutputStream();var context=context(a,s.id());long offset=0;
|
||||
while(offset<s.target().byteLength()){
|
||||
var chunk=staged?files.readStaged(new StagedRead(new WriteQuery(context,s.operation()),offset,MAX_CHUNK_BYTES)):
|
||||
files.readChunk(new ChunkQuery(new FileQuery(context,s.binding(),s.target().purpose(),s.batchId()),offset,MAX_CHUNK_BYTES));
|
||||
if(chunk.binding().offset()!=offset||!chunk.binding().file().context().equals(context)||!chunk.binding().file().binding().equals(s.binding())||chunk.bytes().length!=Math.min(MAX_CHUNK_BYTES,s.target().byteLength()-offset)||chunk.nextOffset()!=offset+chunk.bytes().length||chunk.endOfFile()!=(chunk.nextOffset()==s.target().byteLength())||!sha(chunk.bytes()).equals(chunk.chunkSha256()))throw ReportingException.conflict("私有文件分块完整性校验失败");
|
||||
out.writeBytes(chunk.bytes());offset=chunk.nextOffset();
|
||||
}
|
||||
byte[] bytes=out.toByteArray();if(bytes.length!=s.target().byteLength()||!sha(bytes).equals(s.target().bytesSha256()))throw ReportingException.conflict("私有文件内容完整性校验失败");return bytes;
|
||||
}
|
||||
AuthorizationDecision authorize(AuthorizationQuery query){
|
||||
var a=actors.current(query.action()==PrivateBusinessFileOwner.Action.READ?"view":"edit");
|
||||
var c=query.context();var t=query.target();
|
||||
if(c.actorId()!=a.user()||c.organizationId()!=a.organization()||c.departmentId()!=a.organization()||!"integration".equals(c.callerService())||!c.delegationRef().equals("reporting:"+t.objectId()))throw ReportingException.forbidden();
|
||||
var stored=required(a,t.objectId());
|
||||
if(query.action()!=PrivateBusinessFileOwner.Action.READ&&stored.creator()!=a.user()||!stored.target().equals(t)||!stored.operation().equals(query.operationKey()))throw ReportingException.forbidden();
|
||||
if(query.binding()!=null){verifyBinding(t,query.binding());if(stored.binding()!=null&&!stored.binding().equals(query.binding()))throw ReportingException.forbidden();}
|
||||
if(query.action()==PrivateBusinessFileOwner.Action.READ&&(!"BOUND".equals(stored.state())||query.binding()==null))throw ReportingException.forbidden();
|
||||
if(query.action()==PrivateBusinessFileOwner.Action.CANCEL||query.action()==PrivateBusinessFileOwner.Action.ERASE_KNOWLEDGE)throw ReportingException.forbidden();
|
||||
if(stored.proofs().isEmpty())throw ReportingException.forbidden();
|
||||
for(var proof:stored.proofs())datasets.authorize(proof.query(),proof.authorizationSha256());
|
||||
Instant now=Instant.now();return new AuthorizationDecision(query,State.AVAILABLE,"reporting:"+stored.id(),1,"reporting-current-policy:"+stored.id(),now,now.plusSeconds(5),Set.of("COMMITTED","BOUND").contains(stored.state()),null);
|
||||
}
|
||||
private static Context context(ReportingActor.Scope a,String id){return new Context(1,a.user(),a.organization(),a.organization(),"integration","reporting:"+id,UUID.randomUUID().toString());}
|
||||
private static void verifyBinding(Target t,Binding b){if(b==null||!t.businessOwner().equals(b.businessOwner())||!t.objectType().equals(b.objectType())||!t.objectId().equals(b.objectId())||t.artifactVersion()!=b.objectVersion()||!t.bytesSha256().equals(b.bytesSha256())||t.byteLength()!=b.byteLength()||!t.mime().equals(b.mime())||t.use()!=b.use())throw ReportingException.forbidden();}
|
||||
static String sha(byte[] bytes){try{return HexFormat.of().formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(bytes));}catch(Exception e){throw new IllegalStateException(e);}}
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
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 org.springframework.web.multipart.MultipartFile;
|
||||
import java.util.List;
|
||||
|
||||
@RestController @RequiredArgsConstructor
|
||||
@RequestMapping("/api/integration/v1/regulatory-reporting/standard-imports")
|
||||
class ReportingImportController {
|
||||
private final ReportingImportService service;
|
||||
@PostMapping(value = "/preview", consumes = "multipart/form-data")
|
||||
@SaCheckPermission(ReportingActor.PREFIX + "standard")
|
||||
public R<ReportingImportService.Preview> preview(@RequestParam("files") List<MultipartFile> files) { return R.ok(service.preview(files)); }
|
||||
@PostMapping(value = "/confirm", consumes = "multipart/form-data")
|
||||
@SaCheckPermission(ReportingActor.PREFIX + "standard")
|
||||
@Log(title = "确认导入监管标准", businessType = BusinessType.INSERT, isSaveRequestData = false, isSaveResponseData = false)
|
||||
public R<ReportingImportService.Preview> confirm(@RequestParam("files") List<MultipartFile> files) { return R.ok(service.confirm(files)); }
|
||||
}
|
||||
+269
@@ -0,0 +1,269 @@
|
||||
package cn.aixunkeji.datagov.integration.regulatoryreporting;
|
||||
|
||||
import org.apache.poi.ss.usermodel.*;
|
||||
import tools.jackson.databind.JsonNode;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
import java.io.*;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.charset.CodingErrorAction;
|
||||
import java.util.*;
|
||||
import java.util.zip.ZipInputStream;
|
||||
import static cn.aixunkeji.datagov.integration.regulatoryreporting.ReportingStandardApi.*;
|
||||
|
||||
/** Bounded, side-effect-free parsing. No sample record values become standard defaults. */
|
||||
final class ReportingImportParser {
|
||||
static final int MAX_BYTES = 10 * 1024 * 1024;
|
||||
record Input(String name, byte[] bytes) { }
|
||||
record Issue(String file, String location, String severity, String message) { }
|
||||
record Parsed(Resource resource, String xml) { }
|
||||
record Result(List<Parsed> resources, List<Issue> issues, int fields, int required, int nullable, List<ReportingDocumentNotes.Note> notes) { }
|
||||
private final List<ReportingDocumentNotes.Note> notes = new ArrayList<>();
|
||||
private final JsonMapper json;
|
||||
private final List<Parsed> resources = new ArrayList<>();
|
||||
private final List<Issue> issues = new ArrayList<>();
|
||||
private final Set<String> digests = new HashSet<>();
|
||||
private final Set<String> codes = new HashSet<>();
|
||||
private int expanded, entries;
|
||||
ReportingImportParser(JsonMapper json) { this.json = json; }
|
||||
|
||||
Result parse(List<Input> inputs) {
|
||||
if (inputs == null || inputs.isEmpty() || inputs.size() > 50) throw ReportingException.invalid("请选择1至50个文件");
|
||||
for (var input : inputs) parseFile(input, false);
|
||||
int total = resources.stream().mapToInt(p -> p.resource().fields().size()).sum();
|
||||
if (total > 2000 || resources.size() > 50) throw ReportingException.invalid("单次最多50张资源表、2000个字段");
|
||||
int required = (int) resources.stream().flatMap(p -> p.resource().fields().stream()).filter(Field::required).count();
|
||||
int nullable = (int) resources.stream().flatMap(p -> p.resource().fields().stream()).filter(f -> f.details() != null && Boolean.TRUE.equals(f.details().nullable())).count();
|
||||
return new Result(List.copyOf(resources), List.copyOf(issues), total, required, nullable, List.copyOf(notes));
|
||||
}
|
||||
private void parseFile(Input input, boolean zipped) {
|
||||
String name = input.name();
|
||||
if (name == null || name.length() > 255 || input.bytes() == null || input.bytes().length == 0 || input.bytes().length > MAX_BYTES) throw ReportingException.invalid("文件为空、名称过长或超过10 MiB");
|
||||
expanded += input.bytes().length;
|
||||
if (++entries > 100 || expanded > 30 * 1024 * 1024) throw ReportingException.invalid("批量文件解压后超过30 MiB或条目过多");
|
||||
String digest = hash(input.bytes());
|
||||
if (!digests.add(digest)) { issue(name, "文件", "WARNING", "重复文件,未重复导入"); return; }
|
||||
try {
|
||||
String extension = name.substring(name.lastIndexOf('.') + 1).toLowerCase(Locale.ROOT);
|
||||
switch (extension) {
|
||||
case "xml" -> xml(name, utf8(input.bytes()));
|
||||
case "json" -> json(name, utf8(input.bytes()));
|
||||
case "xlsx", "xls" -> excel(name, input.bytes());
|
||||
case "pdf", "docx" -> {
|
||||
notes.addAll(ReportingDocumentNotes.extract(name,input.bytes()));
|
||||
if(notes.size()>4000||notes.stream().mapToInt(n->n.text().length()).sum()>400000)throw ReportingException.invalid("辅助说明过多,请分批导入");
|
||||
issue(name,"辅助说明","WARNING","辅助文本须人工核对并回填字段说明和规则,不自动生成约束或发布标准");
|
||||
}
|
||||
case "zip" -> {
|
||||
if (zipped) throw ReportingException.invalid("不支持嵌套ZIP");
|
||||
try (var zip = new ZipInputStream(new ByteArrayInputStream(input.bytes()), StandardCharsets.UTF_8)) {
|
||||
for (var e = zip.getNextEntry(); e != null; e = zip.getNextEntry()) {
|
||||
if (e.isDirectory()) { if (++entries > 100) throw ReportingException.invalid("ZIP条目过多"); continue; }
|
||||
if (!e.getName().toLowerCase(Locale.ROOT).endsWith(".xml") || e.getName().contains("..") || e.getName().startsWith("/")) {
|
||||
issue(name, e.getName(), "BLOCKING", "ZIP只接受XML模板,存在非法路径或非XML文件");
|
||||
break;
|
||||
}
|
||||
byte[] bytes = zip.readNBytes(MAX_BYTES + 1);
|
||||
parseFile(new Input(name + "/" + e.getName(), bytes), true);
|
||||
}
|
||||
}
|
||||
}
|
||||
default -> issue(name, "文件", "BLOCKING", "请选择XML、XML ZIP、JSON、Excel、PDF或DOCX");
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
issue(name, "文件", "BLOCKING", ex instanceof ReportingException ? ex.getMessage() : "解析失败,请检查文件格式、编码及字段结构");
|
||||
}
|
||||
}
|
||||
private static String utf8(byte[] bytes) throws Exception {
|
||||
String value = StandardCharsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPORT).onUnmappableCharacter(CodingErrorAction.REPORT).decode(ByteBuffer.wrap(bytes)).toString();
|
||||
return value.startsWith("\uFEFF") ? value.substring(1) : value;
|
||||
}
|
||||
private static String hash(byte[] bytes) {
|
||||
try { return HexFormat.of().formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(bytes)); }
|
||||
catch (Exception e) { throw new IllegalStateException(e); }
|
||||
}
|
||||
private void issue(String file, String location, String severity, String message) {
|
||||
if (issues.size() >= 2000) throw ReportingException.invalid("导入错误过多,请分批修正");
|
||||
issues.add(new Issue(file, location, severity, message));
|
||||
}
|
||||
private void add(String file, Resource resource, String xml) {
|
||||
try {
|
||||
ReportingStandardService.normalize(new Definition("IMPORT", "导入预览", "1", "", "", List.of(resource)));
|
||||
if (!codes.add(resource.code())) {
|
||||
int index = java.util.stream.IntStream.range(0, resources.size()).filter(i -> resources.get(i).resource().code().equals(resource.code())).findFirst().orElseThrow();
|
||||
Parsed old = resources.get(index);
|
||||
if ((old.xml() == null) == (xml == null)) { issue(file, resource.code(), "BLOCKING", "资源编码重复;不能自动覆盖或拼接定义"); return; }
|
||||
Resource definition = xml == null ? resource : old.resource();
|
||||
String template = xml == null ? old.xml() : xml;
|
||||
var shape = ReportingTemplateParser.parse(template, "Record");
|
||||
if (!TemplateConsistency.compare(definition.fields().stream().map(Field::name).toList(), shape.fields()).consistent())
|
||||
issue(file, resource.code(), "BLOCKING", "规范与XML字段或顺序不一致,须修正后导入");
|
||||
resources.set(index, new Parsed(definition, template));
|
||||
return;
|
||||
}
|
||||
resources.add(new Parsed(resource, xml));
|
||||
} catch (ReportingException e) { issue(file, resource.code(), "BLOCKING", e.getMessage()); }
|
||||
}
|
||||
private void xml(String file, String xml) {
|
||||
var shape = ReportingTemplateParser.parse(xml, "Record");
|
||||
var s = shape.structure();
|
||||
String code = s.resourceCode();
|
||||
if (code.isBlank()) { issue(file, "/Head/resCode", "BLOCKING", "模板缺少资源编码,不能从文件名猜测监管资源代号"); return; }
|
||||
var fields = new ArrayList<Field>();
|
||||
for (String name : shape.fields()) fields.add(new Field(name, name, "STRING", false, null, null, null,
|
||||
new FieldDetails("", null, null, List.of(), "", "", "", "BLOCKING",
|
||||
new Source(file, s.recordPath() + "/" + name, name, "REVIEW_REQUIRED", false))));
|
||||
issue(file, s.recordPath(), "WARNING", "XML仅声明字段和顺序,无法确定类型、长度和必填;请根据正式规范逐字段核对");
|
||||
add(file, new Resource(code, s.resourceName().isBlank() ? code : s.resourceName(), fields, null), xml);
|
||||
}
|
||||
private void json(String file, String text) {
|
||||
JsonNode root = JsonMapper.builder().enable(tools.jackson.core.StreamReadFeature.STRICT_DUPLICATE_DETECTION).build().readTree(text);
|
||||
if (!root.isObject() || !root.path("resources").isArray()) { issue(file, "$.resources", "BLOCKING", "需要对象根节点及resources数组;请按导入格式示例提供,不自动猜测表归属"); return; }
|
||||
unknown(file, "$", root, Set.of("resources", "code", "name", "versionLabel", "publisher", "description"));
|
||||
if (root.path("resources").size() > 50) throw ReportingException.invalid("资源表超过50张");
|
||||
int ri = 0;
|
||||
for (var resource : root.path("resources")) {
|
||||
String path = "$.resources[" + ri++ + "]";
|
||||
if (!resource.isObject()) { issue(file, path, "BLOCKING", "资源必须为对象"); continue; }
|
||||
unknown(file, path, resource, Set.of("code", "name", "fields"));
|
||||
if (!resource.path("fields").isArray() || resource.path("fields").size() > 500) { issue(file, path + ".fields", "BLOCKING", "字段必须为数组且不超过500个"); continue; }
|
||||
List<Field> fields = new ArrayList<>(); int fi = 0;
|
||||
for (var field : resource.path("fields")) {
|
||||
String fp = path + ".fields[" + fi++ + "]";
|
||||
try {
|
||||
if (!field.isObject()) throw ReportingException.invalid("字段必须为对象");
|
||||
unknown(file, fp, field, Set.of("name", "label", "type", "required", "nullable", "maxLength", "precision", "scale", "description", "defaultValue", "enumeration", "dictionary", "fillingRule", "validationRule", "severity"));
|
||||
if (!field.path("required").isBoolean()) throw ReportingException.invalid("required必须是布尔值");
|
||||
if (field.hasNonNull("nullable") && !field.path("nullable").isBoolean()) throw ReportingException.invalid("nullable必须是布尔值");
|
||||
var values = new ArrayList<String>();
|
||||
if (field.hasNonNull("enumeration")) {
|
||||
if (!field.path("enumeration").isArray()) throw ReportingException.invalid("enumeration必须为字符串数组");
|
||||
for (var v : field.path("enumeration")) { if (!v.isString()) throw ReportingException.invalid("枚举必须为字符串"); values.add(v.asString()); }
|
||||
}
|
||||
TypeSpec type = type(requiredText(field, "type"), integer(field, "maxLength"), integer(field, "precision"), integer(field, "scale"));
|
||||
var parsed = new Field(requiredText(field, "name"), optionalText(field, "label"), type.name(), field.path("required").asBoolean(), type.length(), type.precision(), type.scale(),
|
||||
new FieldDetails(optionalText(field, "description"), field.hasNonNull("nullable") ? field.path("nullable").asBoolean() : !field.path("required").asBoolean(),
|
||||
optionalText(field, "defaultValue"), values, optionalText(field, "dictionary"), optionalText(field, "fillingRule"), optionalText(field, "validationRule"),
|
||||
field.hasNonNull("severity") ? requiredText(field, "severity") : "BLOCKING", new Source(file, fp, field.toString(), "EXACT", false)));
|
||||
validateField(parsed); fields.add(parsed);
|
||||
} catch (Exception e) { issue(file, fp, "BLOCKING", e instanceof ReportingException ? e.getMessage() : "字段格式无效"); }
|
||||
}
|
||||
try { add(file, new Resource(requiredText(resource, "code"), requiredText(resource, "name"), fields, null), null); }
|
||||
catch (ReportingException e) { issue(file, path, "BLOCKING", e.getMessage()); }
|
||||
}
|
||||
}
|
||||
private void unknown(String file, String path, JsonNode node, Set<String> allowed) {
|
||||
for (String key : node.propertyNames()) if (!allowed.contains(key)) issue(file, path + "." + key, "BLOCKING", "未知属性,不能静默忽略,请确认字段映射");
|
||||
}
|
||||
private static String requiredText(JsonNode node, String name) { String v = optionalText(node, name); if (v.isBlank()) throw ReportingException.invalid(name + "不能为空"); return v; }
|
||||
private static String optionalText(JsonNode node, String name) {
|
||||
if (!node.hasNonNull(name)) return "";
|
||||
if (!node.path(name).isString()) throw ReportingException.invalid(name + "必须为字符串");
|
||||
return node.path(name).asString();
|
||||
}
|
||||
private static Integer integer(JsonNode node, String name) {
|
||||
if (!node.hasNonNull(name)) return null;
|
||||
if (!node.path(name).isIntegralNumber() || !node.path(name).canConvertToInt()) throw ReportingException.invalid(name + "必须为整数");
|
||||
return node.path(name).asInt();
|
||||
}
|
||||
private static final Map<String, String> HEADERS = Map.ofEntries(
|
||||
Map.entry("资源编码", "resourceCode"), Map.entry("表编码", "resourceCode"), Map.entry("resourcecode", "resourceCode"),
|
||||
Map.entry("资源名称", "resourceName"), Map.entry("表名称", "resourceName"), Map.entry("resourcename", "resourceName"),
|
||||
Map.entry("字段编码", "name"), Map.entry("字段名", "name"), Map.entry("name", "name"),
|
||||
Map.entry("字段名称", "label"), Map.entry("中文名称", "label"), Map.entry("label", "label"),
|
||||
Map.entry("类型", "type"), Map.entry("数据类型", "type"), Map.entry("type", "type"),
|
||||
Map.entry("必填", "required"), Map.entry("是否必填", "required"), Map.entry("required", "required"),
|
||||
Map.entry("允许空值", "nullable"), Map.entry("nullable", "nullable"),
|
||||
Map.entry("长度", "maxLength"), Map.entry("maxlength", "maxLength"), Map.entry("精度", "precision"), Map.entry("precision", "precision"),
|
||||
Map.entry("小数位", "scale"), Map.entry("scale", "scale"), Map.entry("说明", "description"), Map.entry("备注", "description"), Map.entry("description", "description"),
|
||||
Map.entry("填写规则", "fillingRule"), Map.entry("fillingrule", "fillingRule"), Map.entry("校验规则", "validationRule"), Map.entry("validationrule", "validationRule"),
|
||||
Map.entry("校验级别", "severity"), Map.entry("severity", "severity"), Map.entry("字典", "dictionary"), Map.entry("dictionary", "dictionary"),
|
||||
Map.entry("默认值", "defaultValue"), Map.entry("defaultvalue", "defaultValue"), Map.entry("枚举", "enumeration"), Map.entry("enumeration", "enumeration"));
|
||||
private void excel(String file, byte[] bytes) throws IOException {
|
||||
try (Workbook book = WorkbookFactory.create(new ByteArrayInputStream(bytes))) {
|
||||
if (book.getNumberOfSheets() > 50) throw ReportingException.invalid("工作表数量超过50");
|
||||
Map<String, List<Field>> groups = new LinkedHashMap<>(); Map<String, String> names = new HashMap<>();
|
||||
for (Sheet sheet : book) {
|
||||
if (sheet.getLastRowNum() > 10000 || sheet.getNumMergedRegions() > 2000) throw ReportingException.invalid("工作表行数或合并单元格过多");
|
||||
int header = -1; Map<String, Integer> columns = new LinkedHashMap<>();
|
||||
for (int r = 0; r <= Math.min(50, sheet.getLastRowNum()); r++) {
|
||||
var row = sheet.getRow(r); if (row == null) continue;
|
||||
Map<String, Integer> found = new LinkedHashMap<>();
|
||||
for (Cell cell : row) {
|
||||
String key = HEADERS.get(new DataFormatter(Locale.ROOT).formatCellValue(cell).strip().replace(" ", "").toLowerCase(Locale.ROOT));
|
||||
if (key != null && found.put(key, cell.getColumnIndex()) != null) issue(file, sheet.getSheetName() + "!" + cell.getAddress(), "BLOCKING", "重复语义列");
|
||||
}
|
||||
if (found.keySet().containsAll(Set.of("resourceCode", "resourceName", "name", "type")) && (found.containsKey("required") || found.containsKey("nullable"))) { header = r; columns = found; break; }
|
||||
}
|
||||
if (header < 0) { issue(file, sheet.getSheetName(), "BLOCKING", "未识别表头,需要资源编码、资源名称、字段编码、类型和必填/允许空值列"); continue; }
|
||||
Row headerRow = sheet.getRow(header);
|
||||
for (Cell cell : headerRow) if (!new DataFormatter().formatCellValue(cell).isBlank() && !columns.containsValue(cell.getColumnIndex()))
|
||||
issue(file, sheet.getSheetName() + "!" + cell.getAddress(), "BLOCKING", "未识别表头,须显式调整,不能丢弃规范列");
|
||||
for (int r = header + 1; r <= sheet.getLastRowNum(); r++) {
|
||||
Row row = sheet.getRow(r); if (row == null) continue;
|
||||
String location = sheet.getSheetName() + "!" + (r + 1);
|
||||
final int sourceRow = r;
|
||||
try {
|
||||
Map<String, String> values = new LinkedHashMap<>();
|
||||
for (var col : columns.entrySet()) values.put(col.getKey(), cell(sheet, r, col.getValue()));
|
||||
// Only skip genuinely empty rows, not malformed field rows.
|
||||
boolean hasOwnValue = false;
|
||||
for (Cell c : row) if (!new DataFormatter().formatCellValue(c).isBlank()) { hasOwnValue = true; break; }
|
||||
if (!hasOwnValue) continue;
|
||||
String code = value(values, "resourceCode"), resourceName = value(values, "resourceName");
|
||||
if (code.isBlank() || resourceName.isBlank() || value(values, "name").isBlank()) throw ReportingException.invalid("资源编码、资源名称或字段编码为空");
|
||||
if (names.containsKey(code) && !names.get(code).equals(resourceName)) throw ReportingException.invalid("同一资源编码有不同名称");
|
||||
boolean required = values.containsKey("required") ? bool(value(values, "required")) : !bool(value(values, "nullable"));
|
||||
Boolean nullable = values.containsKey("nullable") ? bool(value(values, "nullable")) : !required;
|
||||
TypeSpec type = type(value(values, "type"), number(values, "maxLength"), number(values, "precision"), number(values, "scale"));
|
||||
var f = new Field(value(values, "name"), value(values, "label"), type.name(), required, type.length(), type.precision(), type.scale(),
|
||||
new FieldDetails(value(values, "description"), nullable, value(values, "defaultValue"),
|
||||
value(values, "enumeration").isBlank() ? List.of() : Arrays.asList(value(values, "enumeration").split("\\|", -1)),
|
||||
value(values, "dictionary"), value(values, "fillingRule"), value(values, "validationRule"), value(values, "severity").isBlank() ? "BLOCKING" : value(values, "severity"),
|
||||
new Source(file, location + " " + columns.entrySet().stream().map(e -> e.getKey() + "=" + new org.apache.poi.ss.util.CellReference(sourceRow, e.getValue()).formatAsString()).toList(), json.writeValueAsString(values), "EXACT", false)));
|
||||
validateField(f); names.put(code, resourceName); groups.computeIfAbsent(code, k -> new ArrayList<>()).add(f);
|
||||
} catch (Exception e) { issue(file, location, "BLOCKING", e instanceof ReportingException ? e.getMessage() : "单元格数值或格式无效"); }
|
||||
}
|
||||
}
|
||||
groups.forEach((code, fields) -> add(file, new Resource(code, names.get(code), fields, null), null));
|
||||
}
|
||||
}
|
||||
private static String cell(Sheet sheet, int r, int c) {
|
||||
for (var range : sheet.getMergedRegions()) if (range.isInRange(r, c)) { r = range.getFirstRow(); c = range.getFirstColumn(); break; }
|
||||
Row row = sheet.getRow(r); Cell cell = row == null ? null : row.getCell(c);
|
||||
if (cell == null) return "";
|
||||
if (cell.getCellType() == CellType.FORMULA) throw ReportingException.invalid("规范单元格包含公式,请确认并转换为明确值");
|
||||
return new DataFormatter(Locale.ROOT).formatCellValue(cell).strip();
|
||||
}
|
||||
private static String value(Map<String, String> values, String key) { return values.getOrDefault(key, ""); }
|
||||
private static void validateField(Field f) { ReportingStandardService.normalize(new Definition("IMPORT", "预览", "1", "", "", List.of(new Resource("ROW", "资源", List.of(f), null)))); }
|
||||
private record TypeSpec(String name, Integer length, Integer precision, Integer scale) { }
|
||||
private static TypeSpec type(String value, Integer length, Integer precision, Integer scale) {
|
||||
var m = java.util.regex.Pattern.compile("([A-Z][A-Z0-9]*)(?:\\((\\d+)(?:,(\\d+))?\\))?").matcher(value.toUpperCase(Locale.ROOT).replace(" ", ""));
|
||||
if (!m.matches()) throw ReportingException.invalid("字段类型无法识别:" + value);
|
||||
String name = switch (m.group(1)) {
|
||||
case "STRING", "CHAR", "VARCHAR", "VARCHAR2", "NVARCHAR", "NVARCHAR2", "TEXT", "CLOB" -> "STRING";
|
||||
case "INTEGER", "INT", "BIGINT", "SMALLINT", "TINYINT" -> "INTEGER";
|
||||
case "DECIMAL", "NUMERIC", "NUMBER" -> "DECIMAL";
|
||||
case "DATE" -> "DATE";
|
||||
case "DATETIME", "TIMESTAMP" -> "DATETIME";
|
||||
case "BOOLEAN", "BOOL" -> "BOOLEAN";
|
||||
default -> throw ReportingException.invalid("不支持的标准类型:" + value);
|
||||
};
|
||||
if (m.group(2) != null) {
|
||||
int a = Integer.parseInt(m.group(2)); Integer b = m.group(3) == null ? null : Integer.parseInt(m.group(3));
|
||||
if ("STRING".equals(name) && b == null) { if (length != null && length != a) throw ReportingException.invalid("类型内长度与长度列冲突"); length = a; }
|
||||
else if ("DECIMAL".equals(name)) {
|
||||
if (precision != null && precision != a || scale != null && b != null && !scale.equals(b)) throw ReportingException.invalid("类型内精度与精度列冲突");
|
||||
precision = a; if (b != null) scale = b;
|
||||
} else throw ReportingException.invalid("该类型的参数需要人工确认,不能忽略:" + value);
|
||||
}
|
||||
return new TypeSpec(name, length, precision, scale);
|
||||
}
|
||||
private static Integer number(Map<String, String> values, String key) { return value(values, key).isBlank() ? null : Integer.valueOf(value(values, key)); }
|
||||
private static boolean bool(String value) {
|
||||
if (Set.of("true", "1", "是", "Y", "YES").contains(value)) return true;
|
||||
if (Set.of("false", "0", "否", "N", "NO").contains(value)) return false;
|
||||
throw ReportingException.invalid("布尔标识须明确填写是/否或true/false");
|
||||
}
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
package cn.aixunkeji.datagov.integration.regulatoryreporting;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
import java.util.*;
|
||||
import static cn.aixunkeji.datagov.integration.regulatoryreporting.ReportingStandardApi.*;
|
||||
|
||||
@Service @RequiredArgsConstructor
|
||||
class ReportingImportService {
|
||||
private final ReportingActor actors;
|
||||
private final ReportingStandardService standards;
|
||||
private final JsonMapper json;
|
||||
record Preview(List<Resource> resources, List<ReportingImportParser.Issue> issues, int fields, int required, int nullable, List<ReportingDocumentNotes.Note> notes) { }
|
||||
Preview preview(List<MultipartFile> files) { actors.current("standard"); return response(parse(files)); }
|
||||
@Transactional
|
||||
public Preview confirm(List<MultipartFile> files) {
|
||||
actors.current("standard");
|
||||
var result = parse(files);
|
||||
if (result.resources().isEmpty() || result.issues().stream().anyMatch(i -> "BLOCKING".equals(i.severity())))
|
||||
throw ReportingException.invalid("导入存在阻断错误,请先修正;未写入任何模板或标准");
|
||||
var resources = new ArrayList<Resource>();
|
||||
for (var p : result.resources()) {
|
||||
var r = p.resource();
|
||||
String templateId = p.xml() == null ? null : standards.importTemplate(new TemplateImport(p.xml(), "Record")).id();
|
||||
resources.add(new Resource(r.code(), r.name(), r.fields(), templateId));
|
||||
}
|
||||
return new Preview(resources, result.issues(), result.fields(), result.required(), result.nullable(), result.notes());
|
||||
}
|
||||
private Preview response(ReportingImportParser.Result r) {
|
||||
// XML sample values are neither returned nor persisted by preview.
|
||||
return new Preview(r.resources().stream().map(ReportingImportParser.Parsed::resource).toList(), r.issues(), r.fields(), r.required(), r.nullable(), r.notes());
|
||||
}
|
||||
private ReportingImportParser.Result parse(List<MultipartFile> files) {
|
||||
if (files == null || files.isEmpty() || files.size() > 50) throw ReportingException.invalid("请选择1至50个文件");
|
||||
var inputs = new ArrayList<ReportingImportParser.Input>(); long total = 0;
|
||||
for (var file : files) {
|
||||
if (file.isEmpty() || file.getSize() > ReportingImportParser.MAX_BYTES || (total += file.getSize()) > 30 * 1024 * 1024) throw ReportingException.invalid("单文件不能超过10 MiB,总计不能超过30 MiB");
|
||||
try { inputs.add(new ReportingImportParser.Input(file.getOriginalFilename(), file.getBytes())); }
|
||||
catch (java.io.IOException e) { throw ReportingException.invalid("文件读取失败"); }
|
||||
}
|
||||
return new ReportingImportParser(json).parse(inputs);
|
||||
}
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
package cn.aixunkeji.datagov.integration.regulatoryreporting;
|
||||
|
||||
import java.util.*;
|
||||
import java.math.*;
|
||||
import java.time.*;
|
||||
import java.time.format.*;
|
||||
import static cn.aixunkeji.datagov.integration.regulatoryreporting.ReportingPlanApi.*;
|
||||
|
||||
/** Closed operations, no script, SQL, reflection or expression interpreter. */
|
||||
final class ReportingMapping {
|
||||
static void validate(Mapping m){
|
||||
var t=m.transform();if(t==null)return;
|
||||
if(!Set.of("DIRECT","CONSTANT","DEFAULT","TRIM","UPPER","LOWER","DICTIONARY","DATE","DATETIME","DECIMAL","CONCAT").contains(Objects.toString(t.kind(),"")))throw ReportingException.invalid("不支持的转换类型");
|
||||
if(t.argument()!=null&&t.argument().length()>2000||t.outputFormat()!=null&&t.outputFormat().length()>100||t.values()!=null&&t.values().size()>1000||t.sources()!=null&&t.sources().size()>20)throw ReportingException.invalid("转换配置超过范围");
|
||||
if(t.values()!=null)for(var entry:t.values().entrySet())if(entry.getKey()==null||entry.getValue()==null||entry.getKey().length()>2000||entry.getValue().length()>2000)throw ReportingException.invalid("字典项无效");
|
||||
if(t.sources()!=null&&t.sources().stream().anyMatch(s->s==null||!s.matches("[A-Za-z_][A-Za-z0-9_.-]{0,127}")))throw ReportingException.invalid("表达式来源字段无效");
|
||||
if("CONSTANT".equals(t.kind())&&t.argument()==null||"DEFAULT".equals(t.kind())&&t.argument()==null||"DICTIONARY".equals(t.kind())&&(t.values()==null||t.values().isEmpty())||"CONCAT".equals(t.kind())&&(t.sources()==null||t.sources().isEmpty()))throw ReportingException.invalid("转换参数不完整");
|
||||
try{
|
||||
if(Set.of("DATE","DATETIME").contains(t.kind())){formatter(t.argument());formatter(t.outputFormat());}
|
||||
if("DECIMAL".equals(t.kind())&&(Integer.parseInt(t.argument())<0||Integer.parseInt(t.argument())>30))throw new IllegalArgumentException();
|
||||
}catch(Exception e){throw ReportingException.invalid("日期格式或小数位配置无效");}
|
||||
}
|
||||
static List<String> sources(Mapping m){
|
||||
if(m.transform()!=null&&"CONSTANT".equals(m.transform().kind()))return List.of();
|
||||
if(m.transform()!=null&&"CONCAT".equals(m.transform().kind()))return m.transform().sources();
|
||||
return m.source()==null||m.source().isBlank()?List.of():List.of(m.source());
|
||||
}
|
||||
static String apply(Mapping m,Map<String,String> row){
|
||||
String v=row.get(m.source());var t=m.transform();if(t==null||"DIRECT".equals(t.kind()))return v;
|
||||
if("CONSTANT".equals(t.kind()))return t.argument();
|
||||
if("DEFAULT".equals(t.kind()))return v==null||v.isBlank()?t.argument():v;
|
||||
if("CONCAT".equals(t.kind())){
|
||||
if(t.sources().stream().anyMatch(s->row.get(s)==null))return null;
|
||||
return String.join(Objects.toString(t.argument(),""),t.sources().stream().map(row::get).toList());
|
||||
}
|
||||
if(v==null)return null;
|
||||
return switch(t.kind()){
|
||||
case "TRIM"->v.strip();case "UPPER"->v.toUpperCase(Locale.ROOT);case "LOWER"->v.toLowerCase(Locale.ROOT);
|
||||
case "DICTIONARY"->{if(!t.values().containsKey(v))throw new IllegalArgumentException("字典未命中");yield t.values().get(v);}
|
||||
case "DATE"->LocalDate.parse(v,formatter(t.argument())).format(formatter(t.outputFormat()));
|
||||
case "DATETIME"->LocalDateTime.parse(v,formatter(t.argument())).format(formatter(t.outputFormat()));
|
||||
case "DECIMAL"->new BigDecimal(v).setScale(Integer.parseInt(t.argument()),RoundingMode.UNNECESSARY).toPlainString();
|
||||
default->throw new IllegalArgumentException("转换类型无效");
|
||||
};
|
||||
}
|
||||
private static DateTimeFormatter formatter(String pattern){
|
||||
if(pattern==null||pattern.isBlank()||pattern.length()>100||pattern.contains("yy")&&!pattern.contains("uuuu"))throw new IllegalArgumentException();
|
||||
return DateTimeFormatter.ofPattern(pattern,Locale.ROOT).withResolverStyle(ResolverStyle.STRICT);
|
||||
}
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
package cn.aixunkeji.datagov.integration.regulatoryreporting;
|
||||
|
||||
import java.util.*;
|
||||
import java.io.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.zip.*;
|
||||
import javax.xml.XMLConstants;
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
import javax.xml.transform.*;
|
||||
import javax.xml.transform.dom.DOMSource;
|
||||
import javax.xml.transform.stream.StreamResult;
|
||||
import org.w3c.dom.Element;
|
||||
import static cn.aixunkeji.datagov.integration.regulatoryreporting.ReportingExecutionApi.*;
|
||||
|
||||
/** Deterministic local format production; not a claim of target-system acceptance. */
|
||||
final class ReportingPackage {
|
||||
static byte[] generate(Frozen frozen,Snapshot snapshot){
|
||||
return generate(frozen,snapshot,Map.of());
|
||||
}
|
||||
static byte[] generate(Frozen frozen,Snapshot snapshot,Map<String,byte[]> attachments){
|
||||
try{
|
||||
var expected=ReportingAttachments.expected(frozen,snapshot);
|
||||
if(!expected.keySet().equals(attachments.keySet()))throw ReportingException.conflict("打包附件与冻结快照引用不一致");
|
||||
var output=new ByteArrayOutputStream();Set<String> names=new HashSet<>();int expanded=0;
|
||||
if(snapshot.resources().size()!=frozen.standard().resources().size())throw ReportingException.conflict("快照资源数量与标准不一致");
|
||||
try(var zip=new ZipOutputStream(output,StandardCharsets.UTF_8)){
|
||||
for(var resource:frozen.standard().resources()){
|
||||
if(!names.add(resource.code().toLowerCase(Locale.ROOT)))throw ReportingException.invalid("资源文件名存在大小写冲突");
|
||||
var rows=snapshot.resources().stream().filter(r->r.resource().equals(resource.code())).toList();if(rows.size()!=1)throw ReportingException.conflict("快照资源不唯一或缺失");
|
||||
var template=frozen.templates().stream().filter(t->t.id().equals(resource.templateId())).findFirst().orElseThrow(()->ReportingException.invalid("资源缺少固定XML模板:"+resource.code()));
|
||||
byte[] xml=xml(resource,template,rows.getFirst());expanded+=xml.length;
|
||||
if(expanded>10*1024*1024)throw ReportingException.invalid("XML文件总量超过10 MiB,请拆分任务期间");
|
||||
var entry=new ZipEntry(resource.code()+".xml");entry.setTime(0);zip.putNextEntry(entry);zip.write(xml);zip.closeEntry();
|
||||
}
|
||||
long attachmentSize=0;
|
||||
for(String name:new TreeSet<>(expected.keySet())){
|
||||
byte[] bytes=attachments.get(name);cn.aixunkeji.resource.api.assetupgrade.ReportingAttachmentPolicy.verify(name,bytes);
|
||||
attachmentSize+=bytes.length;expanded+=bytes.length;
|
||||
if(attachmentSize>cn.aixunkeji.resource.api.assetupgrade.ReportingAttachmentPolicy.MAX_BYTES||expanded>10*1024*1024)throw ReportingException.invalid("附件或XML总量超限,请拆分任务期间");
|
||||
var entry=new ZipEntry("unStruct/"+name);entry.setTime(0);zip.putNextEntry(entry);zip.write(bytes);zip.closeEntry();
|
||||
}
|
||||
}
|
||||
if(output.size()>10*1024*1024)throw ReportingException.invalid("报送ZIP超过10 MiB");return output.toByteArray();
|
||||
}catch(ReportingException e){throw e;}catch(Exception e){throw ReportingException.invalid("XML/ZIP生成失败,请核对模板及字段内容");}
|
||||
}
|
||||
static byte[] xml(ReportingStandardApi.Resource resource,ReportingStandardApi.Template template,ResourceRows rows) throws Exception {
|
||||
var shape=template.structure();
|
||||
if(shape==null||shape.generationXml()==null||!resource.code().equals(shape.resourceCode()))throw ReportingException.invalid("资源模板缺少可执行结构或资源编码不匹配,请重新导入完整Package模板:"+resource.code());
|
||||
if(!TemplateConsistency.compare(resource.fields().stream().map(ReportingStandardApi.Field::name).toList(),template.fields()).consistent())throw ReportingException.invalid("固定模板字段与标准不一致");
|
||||
var factory=DocumentBuilderFactory.newInstance();factory.setNamespaceAware(true);factory.setXIncludeAware(false);factory.setExpandEntityReferences(false);
|
||||
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING,true);factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl",true);factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD,"");factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA,"");
|
||||
var doc=factory.newDocumentBuilder().parse(new ByteArrayInputStream(shape.generationXml().getBytes(StandardCharsets.UTF_8)));
|
||||
var record=doc.getElementsByTagNameNS("*","Record").item(0);if(record==null)throw ReportingException.invalid("固定模板缺少Record节点");var parent=record.getParentNode();parent.removeChild(record);
|
||||
for(var row:rows.rows()){
|
||||
if(!new ArrayList<>(row.keySet()).equals(template.fields()))throw ReportingException.conflict("快照字段顺序或集合发生变化");
|
||||
var next=record.cloneNode(true);int index=0;
|
||||
for(var child=next.getFirstChild();child!=null;child=child.getNextSibling())if(child instanceof Element field){
|
||||
var definition=resource.fields().get(index++);String value=row.get(definition.name());if(ReportingRows.validate(definition,value)!=null)throw ReportingException.conflict("冻结快照存在不符合标准的字段");field.setTextContent(value==null?"":value);
|
||||
}
|
||||
parent.appendChild(next);
|
||||
}
|
||||
var factoryT=TransformerFactory.newInstance();factoryT.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING,true);factoryT.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD,"");factoryT.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET,"");
|
||||
var t=factoryT.newTransformer();t.setOutputProperty(OutputKeys.ENCODING,"UTF-8");t.setOutputProperty(OutputKeys.INDENT,"no");var out=new ByteArrayOutputStream();t.transform(new DOMSource(doc),new StreamResult(out));return out.toByteArray();
|
||||
}
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package cn.aixunkeji.datagov.integration.regulatoryreporting;
|
||||
|
||||
import java.util.List;
|
||||
import cn.aixunkeji.datagov.dataproduct.api.reporting.ReportingDatasetDirectory;
|
||||
|
||||
public final class ReportingPlanApi {
|
||||
private ReportingPlanApi() { }
|
||||
public record Transform(String kind,String argument,String outputFormat,java.util.Map<String,String> values,List<String> sources) { }
|
||||
public record Mapping(String target, String source, boolean confirmed,Transform transform) {
|
||||
public Mapping(String target,String source,boolean confirmed){this(target,source,confirmed,null);}
|
||||
}
|
||||
public record Binding(String resourceCode, String datasetId, long datasetVersion, String releaseId,
|
||||
String schemaVersionId, String schemaSha256, List<Mapping> mappings) { }
|
||||
public record Definition(String code, String name, String versionLabel, String regulatorId, String systemId,
|
||||
String topicId, String standardId, long standardVersion, String adapterProfile,
|
||||
String description, List<Binding> bindings) { }
|
||||
public record Save(long version, Definition definition) { }
|
||||
public record StateChange(long version, String reason) { }
|
||||
public record Issue(String location, String severity, String message) { }
|
||||
public record Check(List<Issue> issues, boolean configurationValid, boolean executable) { }
|
||||
public record View(String id, long version, String state, Definition definition, String updatedAt) { }
|
||||
public record Suggestion(String target, List<String> candidates, String method, String confidence, boolean compatible, String reason) { }
|
||||
public record MatchRequest(String standardId, String resourceCode, String datasetId) { }
|
||||
public record MatchResult(ReportingDatasetDirectory.Dataset dataset, List<Suggestion> suggestions) { }
|
||||
public record Sample(String resource,int row,java.util.Map<String,String> source,java.util.Map<String,String> target,List<Issue> issues) { }
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
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.aixunkeji.datagov.dataproduct.api.reporting.ReportingDatasetDirectory;
|
||||
import cn.dev33.satoken.annotation.SaCheckPermission;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import static cn.aixunkeji.datagov.integration.regulatoryreporting.ReportingPlanApi.*;
|
||||
|
||||
@RestController @RequiredArgsConstructor
|
||||
@RequestMapping("/api/integration/v1/regulatory-reporting/plans")
|
||||
class ReportingPlanController {
|
||||
private final ReportingPlanService service;
|
||||
@GetMapping @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("/{id}") @SaCheckPermission(ReportingActor.PREFIX+"view")
|
||||
public R<View> get(@PathVariable String id){return R.ok(service.get(id));}
|
||||
@GetMapping("/{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("/{id}") @SaCheckPermission(ReportingActor.PREFIX+"edit")
|
||||
@Log(title="报送方案",businessType=BusinessType.UPDATE,isSaveRequestData=false,isSaveResponseData=false)
|
||||
public R<View> save(@PathVariable String id,@RequestBody Save request){return R.ok(service.save(id,request));}
|
||||
@PostMapping("/{id}/freeze") @SaCheckPermission(ReportingActor.PREFIX+"edit")
|
||||
@Log(title="冻结报送方案配置",businessType=BusinessType.UPDATE,isSaveRequestData=false,isSaveResponseData=false)
|
||||
public R<View> freeze(@PathVariable String id,@RequestBody StateChange request){return R.ok(service.transition(id,request,false));}
|
||||
@PostMapping("/{id}/disable") @SaCheckPermission(ReportingActor.PREFIX+"edit")
|
||||
@Log(title="停用报送方案",businessType=BusinessType.UPDATE,isSaveRequestData=false,isSaveResponseData=false)
|
||||
public R<View> disable(@PathVariable String id,@RequestBody StateChange request){return R.ok(service.transition(id,request,true));}
|
||||
@PostMapping("/check") @SaCheckPermission(ReportingActor.PREFIX+"edit")
|
||||
public R<Check> check(@RequestBody Definition definition){return R.ok(service.check(definition));}
|
||||
@GetMapping("/datasets") @SaCheckPermission(ReportingActor.PREFIX+"view")
|
||||
public R<ReportingDatasetDirectory.Page> datasets(@RequestParam(defaultValue="") String keyword,
|
||||
@RequestParam(defaultValue="1") int pageNum,@RequestParam(defaultValue="20") int pageSize){return R.ok(service.datasets(keyword,pageNum,pageSize));}
|
||||
@PostMapping("/match") @SaCheckPermission(ReportingActor.PREFIX+"edit")
|
||||
public R<MatchResult> match(@RequestBody MatchRequest request){return R.ok(service.match(request));}
|
||||
@PostMapping("/sample") @SaCheckPermission(ReportingActor.PREFIX+"edit")
|
||||
public R<java.util.List<Sample>> sample(@RequestBody Definition request){return R.ok(service.sample(request));}
|
||||
}
|
||||
+197
@@ -0,0 +1,197 @@
|
||||
package cn.aixunkeji.datagov.integration.regulatoryreporting;
|
||||
|
||||
import cn.aixunkeji.datagov.dataproduct.api.reporting.ReportingDatasetDirectory;
|
||||
import org.apache.dubbo.config.annotation.DubboReference;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import java.util.*;
|
||||
import static cn.aixunkeji.datagov.integration.regulatoryreporting.ReportingPlanApi.*;
|
||||
import static cn.aixunkeji.datagov.integration.regulatoryreporting.ReportingException.*;
|
||||
|
||||
@Service @RequiredArgsConstructor
|
||||
class ReportingPlanService {
|
||||
private final JdbcTemplate jdbc;
|
||||
private final JsonMapper json;
|
||||
private final ReportingActor actors;
|
||||
private final ReportingRepository configs;
|
||||
private final ReportingStandardService standards;
|
||||
@DubboReference(version=ReportingDatasetDirectory.VERSION,group=ReportingDatasetDirectory.GROUP,check=false,timeout=10000,retries=0)
|
||||
private ReportingDatasetDirectory datasets;
|
||||
|
||||
ReportingDatasetDirectory.Page datasets(String keyword,int page,int size) {
|
||||
actors.current("view");ReportingService.paging(page,size);
|
||||
return datasets.candidates(ReportingPolicy.text(keyword,100,false,"关键词"),page,size);
|
||||
}
|
||||
ReportingApi.Page<View> list(String keyword,int page,int size) {
|
||||
var a=actors.current("view");ReportingService.paging(page,size);String k=ReportingPolicy.text(keyword,100,false,"关键词");
|
||||
String where=" WHERE organization_id=? AND (INSTR(LOWER(plan_name),LOWER(?))>0 OR INSTR(LOWER(plan_code),LOWER(?))>0)";
|
||||
long total=jdbc.queryForObject("SELECT COUNT(*) FROM dg_reporting_plan"+where,Long.class,a.organization(),k,k);
|
||||
var ids=jdbc.query("SELECT plan_id FROM dg_reporting_plan"+where+" ORDER BY update_time DESC,plan_id LIMIT ? OFFSET ?",(r,n)->r.getString(1),a.organization(),k,k,size,(page-1)*size);
|
||||
return new ReportingApi.Page<>(ids.stream().map(id->read(a,id,false)).toList(),total);
|
||||
}
|
||||
View get(String id){return required(actors.current("view"),ReportingPolicy.id(id),false);}
|
||||
ReportingApi.Page<ReportingApi.Audit> history(String id,int page,int size){var a=actors.current("view");ReportingService.paging(page,size);required(a,ReportingPolicy.id(id),false);return configs.objectHistory(a,id,page,size);}
|
||||
private View required(ReportingActor.Scope a,String id,boolean lock){var v=read(a,id,lock);if(v==null)throw forbidden();return v;}
|
||||
View read(ReportingActor.Scope a,String id,boolean lock) {
|
||||
return jdbc.query("SELECT * FROM dg_reporting_plan WHERE organization_id=? AND plan_id=?"+(lock?" FOR UPDATE":""),(r,n)->{
|
||||
var bindings=jdbc.query("SELECT * FROM dg_reporting_plan_resource WHERE organization_id=? AND plan_id=? ORDER BY resource_code",(b,i)->
|
||||
new Binding(b.getString("resource_code"),b.getString("dataset_id"),b.getLong("dataset_version"),b.getString("release_id"),b.getString("schema_version_id"),b.getString("schema_sha256"),Arrays.asList(json.readValue(b.getString("mapping_json"),Mapping[].class))),a.organization(),id);
|
||||
return new View(id,r.getLong("version"),r.getString("plan_state"),new Definition(r.getString("plan_code"),r.getString("plan_name"),r.getString("version_label"),r.getString("regulator_id"),r.getString("system_id"),r.getString("topic_id"),r.getString("standard_id"),r.getLong("standard_version"),r.getString("adapter_profile"),r.getString("description"),bindings),r.getTimestamp("update_time").toLocalDateTime().toString());
|
||||
},a.organization(),id).stream().findFirst().orElse(null);
|
||||
}
|
||||
@Transactional public View save(String id,Save request) {
|
||||
var a=actors.current("edit");ReportingPolicy.id(id);
|
||||
if(request==null||request.version() < -1||request.version()==Long.MAX_VALUE)throw invalid("方案版本无效");
|
||||
Definition d=normalize(request.definition());
|
||||
var before=read(a,id,true);
|
||||
String hash=ReportingService.hash(json.writeValueAsString(new Save(request.version(),d)));
|
||||
if(before!=null){
|
||||
String previous=jdbc.queryForObject("SELECT command_sha256 FROM dg_reporting_plan WHERE organization_id=? AND plan_id=?",String.class,a.organization(),id);
|
||||
if(hash.equals(previous))return before;
|
||||
if(!"DRAFT".equals(before.state())||before.version()!=request.version())throw conflict("方案版本已变化或已冻结,请刷新或创建新版本");
|
||||
if(!before.definition().code().equals(d.code())||!before.definition().versionLabel().equals(d.versionLabel()))throw conflict("方案编码和版本号创建后不可更改");
|
||||
}else if(request.version()!=-1)throw forbidden();
|
||||
// Object ownership is mandatory even for incomplete drafts. No client-supplied organization.
|
||||
var standard=dependencies(a,d);
|
||||
if(!"PUBLISHED".equals(standard.status())||standard.version()!=d.standardVersion())throw conflict("请重新选择当前已发布的固定标准版本");
|
||||
for(var b:d.bindings()) {
|
||||
var source=datasets.resolve(b.datasetId());
|
||||
if(!sameVersion(b,source))throw conflict("数据集版本已变化,请重新选择:"+b.resourceCode());
|
||||
}
|
||||
if(before==null)jdbc.update("INSERT INTO dg_reporting_plan(organization_id,plan_id,plan_code,plan_name,version_label,regulator_id,system_id,topic_id,standard_id,standard_version,adapter_profile,description,plan_state,version,command_sha256,create_by,update_by) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,'DRAFT',0,?,?,?)",
|
||||
a.organization(),id,d.code(),d.name(),d.versionLabel(),d.regulatorId(),d.systemId(),d.topicId(),d.standardId(),d.standardVersion(),d.adapterProfile(),d.description(),hash,a.user(),a.user());
|
||||
else if(jdbc.update("UPDATE dg_reporting_plan SET plan_name=?,regulator_id=?,system_id=?,topic_id=?,standard_id=?,standard_version=?,adapter_profile=?,description=?,version=version+1,command_sha256=?,update_by=?,update_time=CURRENT_TIMESTAMP WHERE organization_id=? AND plan_id=? AND version=?",
|
||||
d.name(),d.regulatorId(),d.systemId(),d.topicId(),d.standardId(),d.standardVersion(),d.adapterProfile(),d.description(),hash,a.user(),a.organization(),id,request.version())!=1)throw conflict("方案版本已变化");
|
||||
jdbc.update("DELETE FROM dg_reporting_plan_resource WHERE organization_id=? AND plan_id=?",a.organization(),id);
|
||||
for(var b:d.bindings())jdbc.update("INSERT INTO dg_reporting_plan_resource(organization_id,plan_id,resource_code,dataset_id,dataset_version,release_id,schema_version_id,schema_sha256,mapping_json) VALUES(?,?,?,?,?,?,?,?,?)",
|
||||
a.organization(),id,b.resourceCode(),b.datasetId(),b.datasetVersion(),b.releaseId(),b.schemaVersionId(),b.schemaSha256(),json.writeValueAsString(b.mappings()));
|
||||
configs.audit(a,id,before==null?"PLAN_CREATE":"PLAN_UPDATE",request.version()+1);
|
||||
return required(a,id,false);
|
||||
}
|
||||
Check check(Definition raw) {
|
||||
var a=actors.current("edit");Definition d=normalize(raw);var issues=new ArrayList<Issue>();
|
||||
var standard=dependencies(a,d);
|
||||
if(!"PUBLISHED".equals(standard.status())||standard.version()!=d.standardVersion())issues.add(new Issue("标准","BLOCKING","必须选择当前未停用的已发布标准固定版本"));
|
||||
for(String id:List.of(d.regulatorId(),d.systemId(),d.topicId()))if(!configs.required(a,id,false).command().enabled())issues.add(new Issue("基础配置","BLOCKING","监管机构、系统或主题已停用"));
|
||||
Set<String> expected=new HashSet<>();
|
||||
for(var resource:standard.definition().resources()) {
|
||||
expected.add(resource.code());var binding=d.bindings().stream().filter(b->b.resourceCode().equals(resource.code())).findFirst().orElse(null);
|
||||
if(binding==null){issues.add(new Issue(resource.code(),"BLOCKING","未绑定数据集"));continue;}
|
||||
ReportingDatasetDirectory.Dataset dataset;
|
||||
try{dataset=datasets.resolve(binding.datasetId());}catch(RuntimeException e){issues.add(new Issue(resource.code(),"BLOCKING","数据集不存在、无访问权限或当前不可读取"));continue;}
|
||||
if(!sameVersion(binding,dataset)){issues.add(new Issue(resource.code(),"BLOCKING","数据集版本已变化,需重新绑定"));continue;}
|
||||
for(var target:resource.fields()) {
|
||||
var mapping=binding.mappings().stream().filter(m->m.target().equals(target.name())).findFirst().orElse(null);
|
||||
if(mapping==null){issues.add(new Issue(resource.code()+"."+target.name(),"BLOCKING","目标字段缺少来源;不能静默省略"));continue;}
|
||||
if(mapping.transform()!=null&&!"DIRECT".equals(mapping.transform().kind())){
|
||||
if(!mapping.confirmed()||!dataset.fields().stream().map(ReportingDatasetDirectory.Field::name).toList().containsAll(ReportingMapping.sources(mapping))||ReportingMapping.sources(mapping).isEmpty()&&!"CONSTANT".equals(mapping.transform().kind()))issues.add(new Issue(resource.code()+"."+target.name(),"BLOCKING","转换未确认或来源字段无效"));
|
||||
continue;
|
||||
}
|
||||
var source=dataset.fields().stream().filter(f->f.name().equals(mapping.source())).findFirst().orElse(null);
|
||||
if(source==null||!mapping.confirmed())issues.add(new Issue(resource.code()+"."+target.name(),"BLOCKING","来源字段不存在或映射尚未确认"));
|
||||
else if(!compatible(target,source))issues.add(new Issue(resource.code()+"."+target.name(),"BLOCKING","源类型、长度、精度或空值与目标不兼容,需要配置转换规则"));
|
||||
}
|
||||
var names=resource.fields().stream().map(ReportingStandardApi.Field::name).toList();
|
||||
if(binding.mappings().stream().anyMatch(m->!names.contains(m.target())))issues.add(new Issue(resource.code(),"BLOCKING","映射包含标准以外的字段"));
|
||||
}
|
||||
if(d.bindings().stream().anyMatch(b->!expected.contains(b.resourceCode())))issues.add(new Issue("资源绑定","BLOCKING","存在标准以外的资源表"));
|
||||
boolean valid=issues.isEmpty();
|
||||
issues.add(new Issue("外部提交","BLOCKING","外部传输适配器及凭据环境尚未完成正式接口联调;可准备和校验批次,不能提交监管系统"));
|
||||
return new Check(List.copyOf(issues),valid,false);
|
||||
}
|
||||
@Transactional public View transition(String id,StateChange request,boolean disable){
|
||||
var a=actors.current("edit");ReportingPolicy.id(id);
|
||||
if(request==null||request.version()<0||request.version()==Long.MAX_VALUE)throw invalid("方案版本无效");
|
||||
String reason=ReportingPolicy.text(request.reason(),1000,true,"操作原因");
|
||||
String action=disable?"PLAN_DISABLE":"PLAN_FREEZE";
|
||||
String hash=ReportingService.hash(json.writeValueAsString(List.of(action,request.version(),reason)));
|
||||
var before=required(a,id,true);
|
||||
String previous=jdbc.queryForObject("SELECT command_sha256 FROM dg_reporting_plan WHERE organization_id=? AND plan_id=?",String.class,a.organization(),id);
|
||||
if(hash.equals(previous))return before;
|
||||
if(before.version()!=request.version()||"DISABLED".equals(before.state())||!disable&&!"DRAFT".equals(before.state()))throw conflict("方案状态或版本已变化,请刷新");
|
||||
if(!disable&&!check(before.definition()).configurationValid())throw conflict("基础引用或映射检查未通过,不能冻结配置");
|
||||
if(jdbc.update("UPDATE dg_reporting_plan SET plan_state=?,version=version+1,command_sha256=?,update_by=?,update_time=CURRENT_TIMESTAMP WHERE organization_id=? AND plan_id=? AND version=?",
|
||||
disable?"DISABLED":"FROZEN",hash,a.user(),a.organization(),id,request.version())!=1)throw conflict("方案版本已变化");
|
||||
configs.audit(a,id,action,request.version()+1,reason);
|
||||
return required(a,id,false);
|
||||
}
|
||||
private ReportingStandardService.Stored dependencies(ReportingActor.Scope a,Definition d) {
|
||||
var regulator=configs.required(a,d.regulatorId(),false);var system=configs.required(a,d.systemId(),false);var topic=configs.required(a,d.topicId(),false);
|
||||
if(regulator.kind()!=ReportingApi.Kind.DEPARTMENT||regulator.command().department()==null||!"REGULATOR".equals(regulator.command().department().role())
|
||||
||system.kind()!=ReportingApi.Kind.SYSTEM||!d.regulatorId().equals(system.parentId())||topic.kind()!=ReportingApi.Kind.TOPIC||!d.systemId().equals(topic.parentId()))throw invalid("监管接收机构、上报系统和主题关系无效");
|
||||
var standard=standards.read(a,d.standardId(),false);if(standard==null)throw forbidden();return standard;
|
||||
}
|
||||
MatchResult match(MatchRequest r) {
|
||||
var a=actors.current("edit");if(r==null)throw invalid("请选择标准、资源和数据集");
|
||||
var standard=standards.read(a,ReportingPolicy.id(r.standardId()),false);if(standard==null)throw forbidden();
|
||||
var resource=standard.definition().resources().stream().filter(v->v.code().equals(r.resourceCode())).findFirst().orElseThrow(()->invalid("标准中不存在该资源"));
|
||||
var dataset=datasets.resolve(r.datasetId());
|
||||
return new MatchResult(dataset,suggest(resource.fields(),dataset.fields()));
|
||||
}
|
||||
List<Sample> sample(Definition raw){
|
||||
var a=actors.current("edit");var d=normalize(raw);var standard=dependencies(a,d);
|
||||
if(!"PUBLISHED".equals(standard.status())||standard.version()!=d.standardVersion())throw conflict("标准版本已变化");
|
||||
if(d.bindings().size()>10)throw invalid("单次试算最多10张资源表,请按资源拆分试算");
|
||||
List<Sample> samples=new ArrayList<>();
|
||||
for(var b:d.bindings()){
|
||||
var dataset=datasets.resolve(b.datasetId());if(!sameVersion(b,dataset))throw conflict("数据集版本已变化");
|
||||
var resource=standard.definition().resources().stream().filter(r->r.code().equals(b.resourceCode())).findFirst().orElseThrow(()->invalid("资源不属于标准"));
|
||||
var columns=new LinkedHashSet<String>();b.mappings().forEach(m->columns.addAll(ReportingMapping.sources(m)));if(columns.isEmpty())columns.add(dataset.fields().getFirst().name());
|
||||
var preview=datasets.preview(new ReportingDatasetDirectory.Read(dataset,List.copyOf(columns),List.of()));
|
||||
if(preview==null||preview.complete()||preview.rows().size()>5)throw conflict("样例响应无效,不能作为快照使用");
|
||||
int row=0;for(var values:preview.rows()){
|
||||
var target=new LinkedHashMap<String,String>();List<Issue> issues=new ArrayList<>();
|
||||
for(var f:resource.fields()){
|
||||
var mapping=b.mappings().stream().filter(m->m.target().equals(f.name())).findFirst().orElse(null);String value=null;
|
||||
if(mapping==null)issues.add(new Issue(f.name(),"BLOCKING","缺少映射"));
|
||||
else try{value=ReportingMapping.apply(mapping,values);}catch(RuntimeException e){issues.add(new Issue(f.name(),"BLOCKING","转换失败或字典未命中"));}
|
||||
target.put(f.name(),value);String error=ReportingRows.validate(f,value);if(error!=null)issues.add(new Issue(f.name(),"BLOCKING",error));
|
||||
}
|
||||
samples.add(new Sample(resource.code(),++row,values,target,List.copyOf(issues)));
|
||||
}
|
||||
}
|
||||
return List.copyOf(samples);
|
||||
}
|
||||
static List<Suggestion> suggest(List<ReportingStandardApi.Field> targets,List<ReportingDatasetDirectory.Field> sources) {
|
||||
return targets.stream().map(t->{
|
||||
var exact=sources.stream().filter(s->s.name().equals(t.name())).toList();
|
||||
var names=exact.isEmpty()?sources.stream().filter(s->s.name().equalsIgnoreCase(t.name())||t.label()!=null&&!t.label().isBlank()&&t.label().equals(s.label())).toList():exact;
|
||||
boolean unique=names.size()==1,compatible=unique&&compatible(t,names.getFirst());
|
||||
return new Suggestion(t.name(),names.stream().map(ReportingDatasetDirectory.Field::name).toList(),!exact.isEmpty()?"EXACT_CODE":names.isEmpty()?"NONE":"NAME_CANDIDATE",
|
||||
!exact.isEmpty()&&unique?"HIGH":unique?"REVIEW_REQUIRED":"AMBIGUOUS",compatible,!unique?"无唯一候选,请人工选择":compatible?"仍需确认业务含义":"类型、容量或空值约束需进一步处理");
|
||||
}).toList();
|
||||
}
|
||||
static boolean compatible(ReportingStandardApi.Field target,ReportingDatasetDirectory.Field source) {
|
||||
if((target.required()||target.details()!=null&&Boolean.FALSE.equals(target.details().nullable()))&&source.nullable())return false;
|
||||
String type=source.type()==null?"":source.type().toUpperCase(Locale.ROOT).replace(" ","");
|
||||
var m=java.util.regex.Pattern.compile("([A-Z0-9]+)(?:\\((\\d+)(?:,(\\d+))?\\))?").matcher(type);
|
||||
if(!m.matches())return false;String base=m.group(1);
|
||||
try{return switch(target.type()){
|
||||
case "STRING"->Set.of("STRING","CHAR","VARCHAR","VARCHAR2","NVARCHAR","TEXT").contains(base)&&(target.maxLength()==null||m.group(2)!=null&&Integer.parseInt(m.group(2))<=target.maxLength());
|
||||
case "INTEGER"->Set.of("TINYINT","SMALLINT","INT","INTEGER","BIGINT").contains(base);
|
||||
case "DECIMAL"->Set.of("DECIMAL","NUMERIC","NUMBER").contains(base)&&target.precision()!=null&&target.scale()!=null&&m.group(2)!=null&&m.group(3)!=null&&Integer.parseInt(m.group(3))<=target.scale()&&Integer.parseInt(m.group(2))-Integer.parseInt(m.group(3))<=target.precision()-target.scale();
|
||||
case "DATE"->"DATE".equals(base);
|
||||
case "DATETIME"->Set.of("DATETIME","TIMESTAMP").contains(base)&&m.group(2)==null;
|
||||
case "BOOLEAN"->Set.of("BOOLEAN","BOOL").contains(base);
|
||||
default->false;
|
||||
};}catch(NumberFormatException e){return false;}
|
||||
}
|
||||
private static boolean sameVersion(Binding b,ReportingDatasetDirectory.Dataset d){return b.datasetVersion()==d.version()&&b.releaseId().equals(d.releaseId())&&b.schemaVersionId().equals(d.schemaVersionId())&&b.schemaSha256().equals(d.schemaSha256());}
|
||||
static Definition normalize(Definition d){
|
||||
if(d==null||d.code()==null||!d.code().matches("[A-Za-z][A-Za-z0-9_-]{0,63}")||d.standardVersion()<0||d.bindings()==null||d.bindings().size()>50)throw invalid("方案编码、标准版本或资源绑定无效");
|
||||
for(String id:new String[]{d.regulatorId(),d.systemId(),d.topicId(),d.standardId()})ReportingPolicy.id(id);
|
||||
if(!Set.of("SASAC_SCIENCE_B","SASAC_TREASURY_B").contains(Objects.toString(d.adapterProfile(),"")))throw invalid("请选择独立的报送适配配置");
|
||||
Set<String> resources=new HashSet<>();int count=0;
|
||||
for(var b:d.bindings()){
|
||||
if(b==null||b.resourceCode()==null||!b.resourceCode().matches("[A-Za-z_][A-Za-z0-9_.-]{0,127}")||!resources.add(b.resourceCode())||b.datasetId()==null||!b.datasetId().matches("[1-9][0-9]{0,18}")||b.datasetVersion()<0||b.releaseId()==null||!b.releaseId().matches("[1-9][0-9]{0,18}")||b.schemaVersionId()==null||!b.schemaVersionId().matches("[1-9][0-9]{0,18}")||b.schemaSha256()==null||!b.schemaSha256().matches("[a-f0-9]{64}")||b.mappings()==null||b.mappings().size()>500)throw invalid("资源或数据集版本引用无效");
|
||||
Set<String> targets=new HashSet<>();for(var m:b.mappings())if(m==null||m.target()==null||!m.target().matches("[A-Za-z_][A-Za-z0-9_.-]{0,127}")||!targets.add(m.target())||m.source()==null||!m.source().isEmpty()&&!m.source().matches("[A-Za-z_][A-Za-z0-9_.-]{0,127}"))throw invalid("映射字段无效或重复");
|
||||
count+=b.mappings().size();
|
||||
b.mappings().forEach(ReportingMapping::validate);
|
||||
}
|
||||
if(count>2000)throw invalid("映射字段总数超过2000");
|
||||
return new Definition(d.code(),ReportingPolicy.text(d.name(),160,true,"方案名称"),ReportingPolicy.text(d.versionLabel(),64,true,"方案版本"),d.regulatorId(),d.systemId(),d.topicId(),d.standardId(),d.standardVersion(),d.adapterProfile(),ReportingPolicy.text(d.description(),2000,false,"说明"),List.copyOf(d.bindings()));
|
||||
}
|
||||
}
|
||||
+3
-1
@@ -32,7 +32,9 @@ final class ReportingPolicy {
|
||||
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, "主管机构"));
|
||||
String role = d.role() == null ? "UNCLASSIFIED" : d.role();
|
||||
if (!Set.of("REGULATOR", "INTERNAL", "UNCLASSIFIED").contains(role)) throw invalid("机构角色无效");
|
||||
department = new Department(text(d.shortName(), 80, false, "简称"), text(d.level(), 80, false, "层级"), text(d.supervisor(), 200, false, "主管机构"), role);
|
||||
} else if (c.kind() == Kind.SYSTEM) {
|
||||
if (c.system() == null || c.department() != null || c.topic() != null) throw invalid("系统配置无效");
|
||||
var s = c.system();
|
||||
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
package cn.aixunkeji.datagov.integration.regulatoryreporting;
|
||||
|
||||
import cn.aixunkeji.datagov.governance.api.qualityrule.QualityRuleExecutionService;
|
||||
import cn.dev33.satoken.stp.StpUtil;
|
||||
import org.apache.dubbo.config.annotation.DubboReference;
|
||||
import org.springframework.stereotype.Service;
|
||||
import java.time.LocalDate;
|
||||
import java.util.*;
|
||||
import static cn.aixunkeji.datagov.integration.regulatoryreporting.ReportingExecutionApi.*;
|
||||
|
||||
/** Explicit frozen owner references. Prose is never interpreted as executable code. */
|
||||
@Service
|
||||
class ReportingQuality {
|
||||
@DubboReference(version=QualityRuleExecutionService.VERSION,group=QualityRuleExecutionService.GROUP,check=false,retries=0,timeout=30000)
|
||||
private QualityRuleExecutionService owner;
|
||||
record Reference(long ruleId,long snapshotId,String sha) { }
|
||||
static Reference reference(String value){
|
||||
if(value==null)return null;
|
||||
var matcher=java.util.regex.Pattern.compile("GOVERNANCE:([1-9][0-9]{0,18}):([1-9][0-9]{0,18}):([a-f0-9]{64})").matcher(value);
|
||||
if(!matcher.matches())return null;
|
||||
try{return new Reference(Long.parseLong(matcher.group(1)),Long.parseLong(matcher.group(2)),matcher.group(3));}catch(NumberFormatException e){return null;}
|
||||
}
|
||||
String resolveReference(ReportingActor.Scope actor,long ruleId){
|
||||
if(ruleId<=0)throw ReportingException.invalid("质量规则标识无效");
|
||||
StpUtil.checkPermission("aixun:governance:quality-rule:validate");
|
||||
var current=owner.resolve(new QualityRuleExecutionService.ResolveCommand(actor.user(),actor.organization(),actor.organization(),ruleId));
|
||||
if(current==null||current.state()!=QualityRuleExecutionService.ResolutionState.AUTHORIZED||current.ruleId()!=ruleId
|
||||
||current.snapshotId()<=0||current.configSha256()==null||!current.configSha256().matches("[a-f0-9]{64}"))throw ReportingException.conflict("质量规则未启用、不可执行或无权限");
|
||||
return "GOVERNANCE:"+ruleId+":"+current.snapshotId()+":"+current.configSha256();
|
||||
}
|
||||
void validateCurrent(ReportingActor.Scope actor,ReportingStandardApi.Definition standard){
|
||||
for(var ref:references(standard)){
|
||||
if(!resolveReference(actor,ref.ruleId()).equals("GOVERNANCE:"+ref.ruleId()+":"+ref.snapshotId()+":"+ref.sha()))throw ReportingException.conflict("质量规则固定版本已变化、未启用或无执行权限");
|
||||
}
|
||||
}
|
||||
List<QualityEvidence> execute(ReportingActor.Scope actor,String batch,String start,ReportingStandardApi.Definition standard,List<Issue> issues){
|
||||
validateCurrent(actor,standard);List<QualityEvidence> evidence=new ArrayList<>();
|
||||
for(var ref:references(standard)){
|
||||
String key=ReportingService.hash("reporting-quality:"+actor.organization()+":"+batch+":"+ref.ruleId()+":"+ref.snapshotId());
|
||||
QualityRuleExecutionService.Outcome outcome;
|
||||
try{outcome=owner.execute(new QualityRuleExecutionService.ExecuteCommand(actor.user(),actor.organization(),actor.organization(),ref.ruleId(),ref.snapshotId(),ref.sha(),key,LocalDate.parse(start)));}
|
||||
catch(RuntimeException e){outcome=null;}
|
||||
boolean passed=outcome!=null&&outcome.state()==QualityRuleExecutionService.State.SUCCEEDED&&ref.sha().equals(outcome.configSha256())&&outcome.evidenceRef()!=null&&outcome.observedAt()!=null;
|
||||
evidence.add(new QualityEvidence(ref.ruleId(),ref.snapshotId(),ref.sha(),key,outcome==null?"UNKNOWN":outcome.state().name(),outcome==null?null:outcome.validationId(),outcome==null?null:outcome.evidenceRef()));
|
||||
issues.add(new Issue("质量规则",0,"","","GOVERNANCE:"+ref.ruleId(),passed?"WARNING":"BLOCKING",passed?"固定版本源数据质量检查通过;与批次内容读取为两次观测,审核须确认其适用范围":"源数据质量检查失败或结果未知,请到质量中心核对该规则;不自动重复执行"));
|
||||
}
|
||||
return List.copyOf(evidence);
|
||||
}
|
||||
private static Set<Reference> references(ReportingStandardApi.Definition standard){Set<Reference> result=new LinkedHashSet<>();for(var r:standard.resources())for(var f:r.fields())if(f.details()!=null){var ref=reference(f.details().validationRule());if(ref!=null)result.add(ref);}return result;}
|
||||
}
|
||||
+10
-1
@@ -53,6 +53,9 @@ class ReportingRepository {
|
||||
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;
|
||||
}
|
||||
boolean children(ReportingActor.Scope actor, String id) {
|
||||
return jdbc.queryForObject("SELECT COUNT(*) FROM dg_reporting_config WHERE organization_id=? AND parent_id=?", 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);
|
||||
@@ -95,6 +98,12 @@ class ReportingRepository {
|
||||
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]);
|
||||
long[] roles = new long[3];
|
||||
jdbc.query("SELECT state_json FROM dg_reporting_config WHERE organization_id=? AND config_kind='DEPARTMENT'", r -> {
|
||||
var department = json.readValue(r.getString(1), Command.class).department();
|
||||
String role = department == null ? null : department.role();
|
||||
roles["REGULATOR".equals(role) ? 0 : "INTERNAL".equals(role) ? 1 : 2]++;
|
||||
}, a.organization());
|
||||
return new Overview(counts[0], counts[1], counts[2], counts[3], roles[0], roles[1], roles[2]);
|
||||
}
|
||||
}
|
||||
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
package cn.aixunkeji.datagov.integration.regulatoryreporting;
|
||||
|
||||
import java.util.*;
|
||||
import java.math.*;
|
||||
import java.time.*;
|
||||
import static cn.aixunkeji.datagov.integration.regulatoryreporting.ReportingExecutionApi.*;
|
||||
|
||||
final class ReportingRows {
|
||||
private static final tools.jackson.databind.json.JsonMapper JSON=tools.jackson.databind.json.JsonMapper.builder().build();
|
||||
record Result(ResourceRows data,List<Issue> issues) { }
|
||||
static Result map(ReportingStandardApi.Resource resource,ReportingPlanApi.Binding binding,Selection selection,List<Map<String,String>> rows){
|
||||
List<Issue> issues=new ArrayList<>();List<Map<String,String>> mapped=new ArrayList<>(),sourceKeys=new ArrayList<>();Set<String> keys=new HashSet<>();int index=0;
|
||||
for(var source:rows){
|
||||
index++;String key=selection.keyFields().stream().map(f->Objects.toString(source.get(f),"<NULL>")).reduce((a,b)->a+" | "+b).orElse("");
|
||||
// Error locations retain a stable key fingerprint, never leak masked values in logs/list pages.
|
||||
String keyRef=ReportingService.hash(key).substring(0,16);
|
||||
if(selection.keyFields().stream().anyMatch(f->source.get(f)==null||source.get(f).isBlank()))add(issues,resource.code(),index,keyRef,"","KEY_REQUIRED","业务主键为空");
|
||||
var keyParts=selection.keyFields().stream().map(source::get).toList();
|
||||
Map<String,String> originalKey=new LinkedHashMap<>();selection.keyFields().forEach(f->originalKey.put(f,source.get(f)));sourceKeys.add(Collections.unmodifiableMap(originalKey));
|
||||
String distinctKey=JSON.writeValueAsString(keyParts);
|
||||
if(!keys.add(distinctKey))add(issues,resource.code(),index,keyRef,"","KEY_UNIQUE","业务主键重复");
|
||||
Map<String,String> target=new LinkedHashMap<>();
|
||||
for(var f:resource.fields()){
|
||||
var mapping=binding.mappings().stream().filter(m->m.target().equals(f.name())).findFirst().orElseThrow(()->ReportingException.invalid("缺少目标字段映射"));
|
||||
String value=null;
|
||||
try{value=ReportingMapping.apply(mapping,source);}
|
||||
catch(RuntimeException e){add(issues,resource.code(),index,keyRef,f.name(),"TRANSFORM","转换失败或字典未命中;请核对来源及转换配置");}
|
||||
target.put(f.name(),value);
|
||||
String error=validate(f,value);
|
||||
if(error!=null)add(issues,resource.code(),index,keyRef,f.name(),"FIELD_CONSTRAINT",error);
|
||||
}
|
||||
mapped.add(Collections.unmodifiableMap(target));
|
||||
}
|
||||
if(rows.isEmpty())issues.add(new Issue(resource.code(),0,"","","EMPTY_RESOURCE","WARNING","本期间没有记录,审核时须确认空报含义"));
|
||||
return new Result(new ResourceRows(resource.code(),List.copyOf(mapped),List.copyOf(sourceKeys)),List.copyOf(issues));
|
||||
}
|
||||
static String validate(ReportingStandardApi.Field f,String v){
|
||||
if(v==null||v.isBlank())return f.required()||f.details()!=null&&Boolean.FALSE.equals(f.details().nullable())?"必填字段为空":null;
|
||||
if(v.codePoints().anyMatch(c->!(c==9||c==10||c==13||c>=32&&c<=0xD7FF||c>=0xE000&&c<=0xFFFD||c>=0x10000&&c<=0x10FFFF)))return "包含XML不允许的字符";
|
||||
if(f.maxLength()!=null&&v.codePointCount(0,v.length())>f.maxLength())return "字段长度超出标准";
|
||||
try{
|
||||
switch(f.type()){
|
||||
case "INTEGER"->{if(!v.matches("-?\\d+"))throw new IllegalArgumentException();new BigInteger(v);}
|
||||
case "DECIMAL"->{if(!v.matches("-?\\d+(?:\\.\\d+)?"))throw new IllegalArgumentException();var d=new BigDecimal(v);if(f.scale()==null||f.precision()==null||d.scale()>f.scale()||Math.max(0,d.precision()-d.scale())>f.precision()-f.scale())return "数值精度或小数位超出标准";}
|
||||
case "DATE"->LocalDate.parse(v);
|
||||
case "DATETIME"->LocalDateTime.parse(v.replace(' ','T'));
|
||||
case "BOOLEAN"->{if(!Set.of("true","false","0","1").contains(v))throw new IllegalArgumentException();}
|
||||
case "STRING"->{ }
|
||||
default->{return "不支持的目标类型";}
|
||||
}
|
||||
}catch(RuntimeException e){return "字段值不符合目标类型或日期格式";}
|
||||
if(f.details()!=null&&f.details().enumeration()!=null&&!f.details().enumeration().isEmpty()&&!f.details().enumeration().contains(v))return "字段值不在标准枚举范围内";
|
||||
return null;
|
||||
}
|
||||
static void rules(ReportingStandardApi.Definition standard,List<Issue> issues){
|
||||
for(var r:standard.resources())for(var f:r.fields())if(f.details()!=null){
|
||||
var d=f.details();
|
||||
if(d.validationRule()!=null&&!d.validationRule().isBlank()&&ReportingQuality.reference(d.validationRule())==null||d.fillingRule()!=null&&!d.fillingRule().isBlank()||d.dictionary()!=null&&!d.dictionary().isBlank())
|
||||
add(issues,r.code(),0,"",f.name(),"UNBOUND_BUSINESS_RULE","存在说明型规则或外部字典,尚未绑定可执行版本,不能按校验通过处理");
|
||||
}
|
||||
}
|
||||
private static void add(List<Issue> issues,String resource,int row,String key,String field,String rule,String message){
|
||||
if(issues.size()>=2000)throw ReportingException.invalid("校验问题超过2000项,请先整改再生成新批次");
|
||||
issues.add(new Issue(resource,row,key,field,rule,"BLOCKING",message));
|
||||
}
|
||||
}
|
||||
+4
@@ -58,8 +58,12 @@ class ReportingService {
|
||||
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 (department.command().department() == null || !"REGULATOR".equals(department.command().department().role()))
|
||||
throw ReportingException.conflict("上报系统必须关联已确认为监管接收机构的对象;内部部门或历史待分类对象不能作为接收机构");
|
||||
if (command.enabled() && (!parent.command().enabled() || !department.command().enabled())) throw ReportingException.conflict("所属部门或系统已停用,不能启用当前配置");
|
||||
}
|
||||
if (command.kind() == Kind.DEPARTMENT && before != null && !"REGULATOR".equals(command.department().role()) && repository.children(actor, id))
|
||||
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) {
|
||||
|
||||
+16
-2
@@ -4,13 +4,27 @@ 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 Source(String file, String location, String rawDefinition, String confidence, boolean confirmed) { }
|
||||
public record FieldDetails(String description, Boolean nullable, String defaultValue, List<String> enumeration,
|
||||
String dictionary, String fillingRule, String validationRule, String severity, Source source) { }
|
||||
public record Field(String name, String label, String type, boolean required, Integer maxLength, Integer precision, Integer scale, FieldDetails details) {
|
||||
public Field(String name, String label, String type, boolean required, Integer maxLength, Integer precision, Integer scale) {
|
||||
this(name, label, type, required, maxLength, precision, scale, null);
|
||||
}
|
||||
}
|
||||
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 TemplateStructure(String root, String namespace, String recordPath, String resourceCode, String resourceName,
|
||||
List<String> qualifiedFields, String generationXml) {
|
||||
public TemplateStructure(String root,String namespace,String recordPath,String resourceCode,String resourceName,List<String> qualifiedFields){this(root,namespace,recordPath,resourceCode,resourceName,qualifiedFields,null);}
|
||||
}
|
||||
public record Template(String id, String sha256, String recordElement, List<String> fields, TemplateStructure structure) {
|
||||
public Template(String id, String sha256, String recordElement, List<String> fields) { this(id, sha256, recordElement, fields, null); }
|
||||
}
|
||||
public record TemplateShape(List<String> fields, TemplateStructure structure) { }
|
||||
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) { }
|
||||
|
||||
+47
-7
@@ -50,24 +50,36 @@ class ReportingStandardService {
|
||||
}).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))),
|
||||
return jdbc.query("SELECT t.*,s.structure_json FROM dg_reporting_template t LEFT JOIN dg_reporting_template_structure s ON s.organization_id=t.organization_id AND s.template_id=t.template_id WHERE t.organization_id=? AND t.template_id=?",
|
||||
(r, n) -> {
|
||||
String value = r.getString("fields_json");
|
||||
String structure = r.getString("structure_json");
|
||||
return new Template(id, r.getString("file_sha256"), r.getString("record_element"), Arrays.asList(json.readValue(value, String[].class)),
|
||||
structure == null ? null : json.readValue(structure, TemplateStructure.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());
|
||||
var shape = ReportingTemplateParser.parse(input.xml(), input.recordElement());
|
||||
String record = input.recordElement() == null || input.recordElement().isBlank() ? "Record" : 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());
|
||||
(r, n) -> r.getString(1), a.organization(), digest, record);
|
||||
if (!existing.isEmpty()) {
|
||||
var old=template(a,existing.getFirst());
|
||||
if(old.structure()!=null&&old.structure().generationXml()==null&&shape.structure().generationXml()!=null)
|
||||
jdbc.update("UPDATE dg_reporting_template_structure SET structure_json=? WHERE organization_id=? AND template_id=?",json.writeValueAsString(shape.structure()),a.organization(),old.id());
|
||||
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());
|
||||
id, a.organization(), digest, record, json.writeValueAsString(shape.fields()), a.user());
|
||||
jdbc.update("INSERT INTO dg_reporting_template_structure(organization_id,template_id,structure_json) VALUES(?,?,?)", a.organization(), id, json.writeValueAsString(shape.structure()));
|
||||
audit.audit(a, id, "TEMPLATE_IMPORT", 0);
|
||||
return new Template(id, digest, input.recordElement(), fields);
|
||||
return new Template(id, digest, record, shape.fields(), shape.structure());
|
||||
}
|
||||
@Transactional
|
||||
public View save(String id, Save request) {
|
||||
@@ -101,9 +113,19 @@ class ReportingStandardService {
|
||||
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("标准已冻结或版本已变化");
|
||||
if (before.definition().resources().stream().flatMap(r -> r.fields().stream()).anyMatch(f -> f.details() != null && f.details().source() != null && !f.details().source().confirmed()))
|
||||
throw conflict("导入字段尚未全部人工确认,请核对类型、必填和来源定义后再发布");
|
||||
if (before.definition().resources().stream().flatMap(r -> r.fields().stream()).anyMatch(f -> f.details() != null && f.details().source() != null && f.details().nullable() == null))
|
||||
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) throw conflict("存在阻断差异:资源字段缺失、多出或顺序不一致,必须修正后才能发布,填写原因不能绕过");
|
||||
for (Resource resource : before.definition().resources()) {
|
||||
var t = template(a, resource.templateId());
|
||||
if (t.structure() != null && !t.structure().resourceCode().isBlank() && !resource.code().equals(t.structure().resourceCode()))
|
||||
throw conflict("资源编码与目标模板Head声明不一致:" + resource.code());
|
||||
}
|
||||
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);
|
||||
@@ -139,6 +161,7 @@ class ReportingStandardService {
|
||||
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("小数位数不能超过精度");
|
||||
validateDetails(f);
|
||||
}
|
||||
fieldCount += r.fields().size();
|
||||
if (r.templateId() != null && !r.templateId().isBlank()) ReportingPolicy.id(r.templateId());
|
||||
@@ -147,6 +170,23 @@ class ReportingStandardService {
|
||||
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 void validateDetails(Field f) {
|
||||
var d = f.details(); if (d == null) return;
|
||||
ReportingPolicy.text(d.description(), 4000, false, "字段描述");
|
||||
ReportingPolicy.text(d.fillingRule(), 4000, false, "填写规则");
|
||||
ReportingPolicy.text(d.validationRule(), 4000, false, "校验规则");
|
||||
ReportingPolicy.text(d.dictionary(), 500, false, "字典引用");
|
||||
ReportingPolicy.text(d.defaultValue(), 2000, false, "默认值");
|
||||
if (f.required() && Boolean.TRUE.equals(d.nullable())) throw invalid("必填字段不能声明允许空值:" + f.name());
|
||||
if (d.enumeration() != null && (d.enumeration().size() > 500 || d.enumeration().stream().anyMatch(v -> v == null || v.length() > 500))) throw invalid("枚举值数量或长度超限");
|
||||
if (d.severity() != null && !Set.of("BLOCKING", "WARNING", "INFO").contains(d.severity())) throw invalid("校验等级无效");
|
||||
if (d.source() != null) {
|
||||
ReportingPolicy.text(d.source().file(), 255, true, "来源文件");
|
||||
ReportingPolicy.text(d.source().location(), 1000, true, "来源位置");
|
||||
ReportingPolicy.text(d.source().rawDefinition(), 16000, false, "原始定义");
|
||||
if (!Set.of("EXACT", "REVIEW_REQUIRED").contains(Objects.toString(d.source().confidence(), ""))) throw invalid("解析置信度无效");
|
||||
}
|
||||
}
|
||||
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;
|
||||
|
||||
+64
-6
@@ -10,14 +10,21 @@ import javax.xml.parsers.DocumentBuilderFactory;
|
||||
import java.io.StringReader;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
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 模板及有效记录节点名");
|
||||
return parse(xml, recordElement).fields();
|
||||
}
|
||||
static ReportingStandardApi.TemplateShape parse(String xml, String recordElement) {
|
||||
if (xml == null || xml.isBlank() || xml.length() > 2097152)
|
||||
throw ReportingException.invalid("XML 模板不能为空或超过 2 MiB 字符");
|
||||
if (recordElement == null || recordElement.isBlank()) recordElement = "Record";
|
||||
if (!recordElement.matches("[A-Za-z_][A-Za-z0-9_.-]{0,127}")) throw ReportingException.invalid("记录节点名格式无效");
|
||||
try {
|
||||
var factory = DocumentBuilderFactory.newInstance();
|
||||
factory.setNamespaceAware(true);
|
||||
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);
|
||||
@@ -32,26 +39,77 @@ final class ReportingTemplateParser {
|
||||
@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);
|
||||
var records = document.getElementsByTagNameNS("*", recordElement);
|
||||
if (records.getLength() == 0 || records.getLength() > 1000) throw ReportingException.invalid("模板未找到记录节点或记录节点过多");
|
||||
List<String> result = null;
|
||||
List<String> qualified = null;
|
||||
String path = null;
|
||||
for (int i = 0; i < records.getLength(); i++) {
|
||||
var names = new ArrayList<String>();
|
||||
var qnames = new ArrayList<String>();
|
||||
String currentPath = path(records.item(i));
|
||||
if (path != null && !path.equals(currentPath)) throw ReportingException.invalid("记录节点路径不唯一,请拆分资源模板");
|
||||
path = currentPath;
|
||||
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 (element.getElementsByTagName("*").getLength() != 0) throw ReportingException.invalid("记录字段包含嵌套结构,需配置专用格式适配器,不能静默展开");
|
||||
names.add(element.getLocalName());
|
||||
qnames.add("{" + Objects.toString(element.getNamespaceURI(), "") + "}" + element.getTagName());
|
||||
}
|
||||
}
|
||||
if (names.size() > 500) throw ReportingException.invalid("单张资源表字段不得超过 500 个");
|
||||
TemplateConsistency.compare(names, names);
|
||||
if (result != null && !result.equals(names)) throw ReportingException.invalid("多个记录节点的字段或顺序不一致");
|
||||
if (qualified != null && !qualified.equals(qnames)) throw ReportingException.invalid("多个记录节点的命名空间不一致");
|
||||
result = List.copyOf(names);
|
||||
qualified = List.copyOf(qnames);
|
||||
}
|
||||
return result;
|
||||
var root = document.getDocumentElement();
|
||||
return new ReportingStandardApi.TemplateShape(result, new ReportingStandardApi.TemplateStructure(root.getTagName(),
|
||||
Objects.toString(root.getNamespaceURI(), ""), path, head(root, "resCode"), head(root, "resCaption"), qualified, generationXml(document,recordElement)));
|
||||
} catch (ReportingException e) { throw e; }
|
||||
catch (Exception e) { throw ReportingException.invalid("XML 模板无效,或含重复字段、DTD、外部实体等不支持内容"); }
|
||||
}
|
||||
private static String path(Node node) {
|
||||
if (!(node instanceof Element e)) return "";
|
||||
return path(node.getParentNode()) + "/{" + Objects.toString(e.getNamespaceURI(), "") + "}" + e.getTagName();
|
||||
}
|
||||
private static String generationXml(org.w3c.dom.Document document,String recordName) throws Exception {
|
||||
// Only a fully understood flat Package can become an executable template.
|
||||
var root=document.getDocumentElement();if(!"Package".equals(root.getLocalName())||!"Record".equals(recordName))return null;
|
||||
var all=document.getElementsByTagName("*");
|
||||
for(int i=0;i<all.getLength();i++){
|
||||
var e=(Element)all.item(i);var attrs=e.getAttributes();
|
||||
for(int j=0;j<attrs.getLength();j++)if(!XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(attrs.item(j).getNamespaceURI()))return null;
|
||||
String local=e.getLocalName(),parent=e.getParentNode() instanceof Element p?p.getLocalName():"";
|
||||
if(e==root)continue;
|
||||
boolean known=switch(parent){case "Package"->List.of("Head","Records").contains(local);case "Head"->List.of("resCode","resCaption").contains(local)&&e.getElementsByTagName("*").getLength()==0;case "Records"->"Record".equals(local);case "Record"->e.getElementsByTagName("*").getLength()==0;default->false;};
|
||||
if(!known)return null;
|
||||
}
|
||||
if(root.getElementsByTagNameNS("*","Head").getLength()!=1||root.getElementsByTagNameNS("*","Records").getLength()!=1)return null;
|
||||
var records=root.getElementsByTagNameNS("*","Record");
|
||||
while(records.getLength()>1){var last=records.item(records.getLength()-1);last.getParentNode().removeChild(last);}
|
||||
var first=records.item(0);if(!(first.getParentNode() instanceof Element p)||!"Records".equals(p.getLocalName())||p.getParentNode()!=root)return null;
|
||||
for(Node n=first.getFirstChild();n!=null;n=n.getNextSibling())if(n instanceof Element)eClear(n);
|
||||
removeNonDataNodes(document);
|
||||
var tf=javax.xml.transform.TransformerFactory.newInstance();tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING,true);tf.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD,"");tf.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET,"");
|
||||
var writer=new java.io.StringWriter();tf.newTransformer().transform(new javax.xml.transform.dom.DOMSource(document),new javax.xml.transform.stream.StreamResult(writer));return writer.toString();
|
||||
}
|
||||
private static void eClear(Node node){node.setTextContent("");}
|
||||
private static void removeNonDataNodes(Node parent){
|
||||
for(Node node=parent.getFirstChild();node!=null;){Node next=node.getNextSibling();
|
||||
if(node.getNodeType()==Node.COMMENT_NODE||node.getNodeType()==Node.PROCESSING_INSTRUCTION_NODE)parent.removeChild(node);
|
||||
else removeNonDataNodes(node);node=next;
|
||||
}
|
||||
}
|
||||
private static String head(Element root, String name) {
|
||||
var heads = root.getElementsByTagNameNS("*", "Head");
|
||||
if (heads.getLength() == 0) return "";
|
||||
if (heads.getLength() != 1) throw ReportingException.invalid("模板包含多个Head节点");
|
||||
var nodes = ((Element) heads.item(0)).getElementsByTagNameNS("*", name);
|
||||
if (nodes.getLength() > 1) throw ReportingException.invalid("Head资源声明重复");
|
||||
return nodes.getLength() == 0 ? "" : ReportingPolicy.text(nodes.item(0).getTextContent(), 160, false, name);
|
||||
}
|
||||
}
|
||||
|
||||
+19
-2
@@ -34,6 +34,20 @@ public final class AnalyticsSqlCompiler {
|
||||
private static Compiled budget(Compiled sql,AnalyticsQuery.Plan plan){
|
||||
return new Compiled(sql.sql(),sql.parameters(),sql.columns(),sql.limit(),sql.timeBucket(),sql.comparison(),sql.relativeWindow(),SqlExecutionBudget.seconds(plan.maxExecutionSeconds()));
|
||||
}
|
||||
/** Complete tabular export only; the ordinary analytics limit stays unchanged. */
|
||||
public static Compiled compileForSnapshot(AnalyticsQuery.Plan p,List<String> allowed,String source,String database,String schema,String table) {
|
||||
if(p==null||p.limit()!=100000||p.dimensions()==null||!p.dimensions().isEmpty()||p.measures()==null||!p.measures().isEmpty()
|
||||
||p.pivotTotals()||p.categoryRemainder()!=null||p.timeBucket()!=null||p.comparison()!=null||p.relativeWindow()!=null)throw invalid();
|
||||
SqlExecutionBudget.seconds(p.maxExecutionSeconds());
|
||||
return budget(switch(source){
|
||||
case "MYSQL","MARIADB","HIVE" -> compile(p,allowed,"`",List.of(database,table),"LIMIT",100000);
|
||||
case "DORIS" -> compile(p,allowed,"`",List.of("internal",database,table),"LIMIT",100000);
|
||||
case "POSTGRESQL","KINGBASE" -> compile(p,allowed,"\"",List.of(schema,table),"LIMIT",100000);
|
||||
case "SQLSERVER" -> compile(p,allowed,"\"",List.of(database,schema,table),"TOP",100000);
|
||||
case "DAMENG","ORACLE" -> compile(p,allowed,"\"",List.of(schema,table),"FETCH",100000);
|
||||
default -> throw invalid();
|
||||
},p);
|
||||
}
|
||||
private static Compiled compileSource(AnalyticsQuery.Plan plan, List<String> allowedColumns, String sourceType,
|
||||
String database, String schema, String table) {
|
||||
if (sourceType == null) throw invalid();
|
||||
@@ -57,12 +71,15 @@ public final class AnalyticsSqlCompiler {
|
||||
|
||||
private static Compiled compile(AnalyticsQuery.Plan p, List<String> allowedColumns, String quote,
|
||||
List<String> targetParts, String limitStyle) {
|
||||
return compile(p,allowedColumns,quote,targetParts,limitStyle,1000);
|
||||
}
|
||||
private static Compiled compile(AnalyticsQuery.Plan p,List<String> allowedColumns,String quote,List<String> targetParts,String limitStyle,int maximum) {
|
||||
if (p == null || allowedColumns == null || allowedColumns.isEmpty() || allowedColumns.size() > 500) throw invalid();
|
||||
if (p.limit() < 1 || p.limit() > 1000) throw invalid();
|
||||
if (p.limit() < 1 || p.limit() > maximum) throw invalid();
|
||||
DateBucketSql.validate(p);
|
||||
Set<String> allowed = new HashSet<>();
|
||||
for (String field : allowedColumns) if (!allowed.add(identifier(field))) throw invalid();
|
||||
var columns = list(p.columns(), 200); var dims = list(p.dimensions(), 10);
|
||||
var columns = list(p.columns(), maximum>1000?500:200); var dims = list(p.dimensions(), 10);
|
||||
var measures = list(p.measures(), 20); var filters = list(p.filters(), 30); var sorting = list(p.sort(), 10);
|
||||
List<String> select = new ArrayList<>(); List<String> outputs = new ArrayList<>();
|
||||
if (measures.isEmpty()) {
|
||||
|
||||
+4
-1
@@ -10,6 +10,9 @@ import static cn.aixunkeji.datagov.integration.workbenchplan.TaskPlanApi.*;
|
||||
|
||||
@Repository @RequiredArgsConstructor
|
||||
class TaskPlanRepository {
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect = cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG;
|
||||
|
||||
private final JdbcTemplate jdbc;
|
||||
private final JsonMapper json;
|
||||
List<Plan> list(TaskPlanActor.Actor a,String session) { return jdbc.query("SELECT state_json FROM dg_ai_task_plan WHERE session_id=? AND actor_id=? AND department_id=? AND del_flag='0' ORDER BY update_time DESC LIMIT 100",(r,n)->json.readValue(r.getString(1),Plan.class),session,a.id(),a.department()); }
|
||||
@@ -24,7 +27,7 @@ class TaskPlanRepository {
|
||||
if(rows.isEmpty()) return null; if(!hash.equals(rows.getFirst()[0])) throw TaskPlanException.conflict("同一幂等键不能用于不同请求"); return rows.getFirst()[1]==null?null:json.readValue(rows.getFirst()[1],Plan.class);
|
||||
}
|
||||
Plan write(TaskPlanActor.Actor a,String key,String hash,String id,Supplier<Plan> action) {
|
||||
jdbc.update("INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(dg_ai_task_plan_request) */ INTO dg_ai_task_plan_request(actor_id,department_id,request_key,request_hash,plan_id,create_dept,create_by,update_by) VALUES(?,?,?,?,?,?,?,?)",a.id(),a.department(),key,hash,id,a.department(),a.id(),a.id());
|
||||
jdbc.update(databaseDialect.sql("INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(dg_ai_task_plan_request) */ INTO dg_ai_task_plan_request(actor_id,department_id,request_key,request_hash,plan_id,create_dept,create_by,update_by) VALUES(?,?,?,?,?,?,?,?)", "INSERT IGNORE INTO dg_ai_task_plan_request(actor_id,department_id,request_key,request_hash,plan_id,create_dept,create_by,update_by) VALUES(?,?,?,?,?,?,?,?)"),a.id(),a.department(),key,hash,id,a.department(),a.id(),a.id());
|
||||
var row=jdbc.queryForObject("SELECT request_hash,response_json FROM dg_ai_task_plan_request WHERE actor_id=? AND department_id=? AND request_key=? FOR UPDATE",(r,n)->new String[]{r.getString(1),r.getString(2)},a.id(),a.department(),key);
|
||||
if(row==null||!hash.equals(row[0])) throw TaskPlanException.conflict("同一幂等键不能用于不同请求");
|
||||
if(row[1]!=null) return json.readValue(row[1],Plan.class);
|
||||
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package cn.aixunkeji.datagov.integration.datasource;
|
||||
|
||||
import cn.aixunkeji.datagov.integration.api.datasource.DataSourceBiQueryApi;
|
||||
import cn.aixunkeji.datagov.integration.api.tablefile.AnalyticsQuery;
|
||||
import cn.aixunkeji.datagov.governance.api.nativemetadata.NativeQueryPolicyApi;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import java.util.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class ReportingReadProofTest {
|
||||
DataSourceBiQueryApi.Query query(long user,long department){return new DataSourceBiQueryApi.Query(user,department,"table",List.of("id"),new AnalyticsQuery.Plan(List.of("id"),List.of(),List.of(),List.of(),List.of(),100000),"EXPORT");}
|
||||
NativeQueryPolicyApi.Decision decision(String tenant){return new NativeQueryPolicyApi.Decision("ticket","actor-specific-fingerprint","table/version/1",List.of("id"),List.of(new NativeQueryPolicyApi.Filter("tenant","EQ",List.of(tenant))),List.of(),List.of(new NativeQueryPolicyApi.Version("ACCESS",1,1)));}
|
||||
@Test void sameEffectiveScopeMayBeIndependentlyAuthorizedForAnotherReviewer(){assertEquals(DataSourceBiQueryService.completeProof(query(7,9),decision("A")),DataSourceBiQueryService.completeProof(query(8,9),decision("A")));}
|
||||
@Test void differentDepartmentOrRowScopeCannotReadTheSameSnapshot(){String proof=DataSourceBiQueryService.completeProof(query(7,9),decision("A"));assertNotEquals(proof,DataSourceBiQueryService.completeProof(query(8,10),decision("A")));assertNotEquals(proof,DataSourceBiQueryService.completeProof(query(8,9),decision("B")));}
|
||||
@Test void maskingAndPolicyVersionsArePartOfTheScope(){var original=decision("A");var masked=new NativeQueryPolicyApi.Decision(original.queryId(),original.fingerprint(),original.resourceRef(),original.columns(),original.filters(),List.of(new NativeQueryPolicyApi.Mask("id","REPLACE",null,null,null,"hidden")),original.policies());assertNotEquals(DataSourceBiQueryService.completeProof(query(7,9),original),DataSourceBiQueryService.completeProof(query(7,9),masked));}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package cn.aixunkeji.datagov.integration.regulatoryreporting;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
import java.util.*;
|
||||
import java.io.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.zip.ZipInputStream;
|
||||
import cn.aixunkeji.resource.api.assetupgrade.ReportingAttachmentPolicy;
|
||||
import static cn.aixunkeji.datagov.integration.regulatoryreporting.ReportingExecutionApi.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class ReportingAttachmentsTest {
|
||||
static final byte[] BYTES="真实内容的测试夹具".getBytes(StandardCharsets.UTF_8);
|
||||
static final String NAME=ReportingAttachmentPolicy.md5(BYTES)+"_证据.txt";
|
||||
static Frozen fixed(){
|
||||
var xml="<Package><Head><resCode>R</resCode><resCaption>资源</resCaption></Head><Records><Record><file/></Record></Records></Package>";
|
||||
var template=new ReportingStandardApi.Template("t","a".repeat(64),"Record",List.of("file"),ReportingTemplateParser.parse(xml,"Record").structure());
|
||||
var resource=new ReportingStandardApi.Resource("R","资源",List.of(new ReportingStandardApi.Field("file","附件","STRING",false,240,null,null)),"t");
|
||||
return new Frozen(null,new ReportingStandardApi.Definition("S","标准","1","","",List.of(resource)),List.of(template),List.of(new Selection("R","",List.of("id"),List.of(),List.of("file"))));
|
||||
}
|
||||
static Snapshot snapshot(String... names){return new Snapshot("batch","2026-01-01","2026-02-01","a".repeat(64),List.of(new ResourceRows("R",Arrays.stream(names).map(n->Map.of("file",n)).toList())));}
|
||||
static Artifact artifact(String name,String state){return new Artifact("file-id","batch","ATTACHMENT",name,"a".repeat(64),BYTES.length,state,"");}
|
||||
@Test void oldTaskJsonHasNoAttachmentRules(){var s=JsonMapper.builder().build().readValue("{\"resourceCode\":\"R\",\"periodField\":\"\",\"keyFields\":[\"id\"],\"filters\":[]}",Selection.class);assertTrue(s.attachmentFields().isEmpty());}
|
||||
@Test void repeatedReferenceKeepsEveryBusinessAssociation(){var manifest=ReportingAttachments.expected(fixed(),snapshot(NAME,"unStruct/"+NAME,""));assertEquals(1,manifest.size());assertEquals(List.of(new AttachmentUse("R",1,"file"),new AttachmentUse("R",2,"file")),manifest.get(NAME));}
|
||||
@Test void missingAndPendingFilesBlockApproval(){assertThrows(ReportingException.class,()->ReportingAttachments.describe(fixed(),snapshot(NAME),List.of(),true));assertThrows(ReportingException.class,()->ReportingAttachments.describe(fixed(),snapshot(NAME),List.of(artifact(NAME,"PENDING")),true));assertEquals("MISSING",ReportingAttachments.describe(fixed(),snapshot(NAME),List.of(),false).getFirst().state());}
|
||||
@Test void readyFilePreservesHashLengthAndAssociation(){var a=ReportingAttachments.describe(fixed(),snapshot(NAME),List.of(artifact(NAME,"BOUND")),true).getFirst();assertEquals(NAME.substring(0,32),a.md5());assertEquals(BYTES.length,a.length());assertEquals("file-id",a.artifactId());}
|
||||
@Test void unrelatedAndDuplicateArtifactsCannotEnterPackage(){assertThrows(ReportingException.class,()->ReportingAttachments.describe(fixed(),snapshot(NAME),List.of(artifact(NAME.replace("证据","其他"),"BOUND")),true));assertThrows(ReportingException.class,()->ReportingAttachments.describe(fixed(),snapshot(NAME),List.of(artifact(NAME,"BOUND"),artifact(NAME,"BOUND")),true));}
|
||||
@Test void uploadChecksOriginalNameAndContentRatherThanClientMime(){assertDoesNotThrow(()->ReportingAttachments.validateUpload(NAME,"证据.txt",BYTES));assertThrows(ReportingException.class,()->ReportingAttachments.validateUpload(NAME,"其他.txt",BYTES));assertThrows(ReportingException.class,()->ReportingAttachments.validateUpload(NAME,"证据.txt",new byte[]{1}));}
|
||||
@Test void malformedReferencesAndCaseCollisionsAreRejected(){for(String name:List.of("../"+NAME,"https://example.com/"+NAME,NAME.toLowerCase(Locale.ROOT),"A".repeat(16)+"_a.txt",NAME.replace(".txt",".exe"),NAME+"/x"))assertThrows(ReportingException.class,()->ReportingAttachments.expected(fixed(),snapshot(name)));assertThrows(ReportingException.class,()->ReportingAttachments.expected(fixed(),snapshot(NAME.replace(".txt",".TXT"),NAME)));}
|
||||
@Test void maximumFileAndTotalByteBudgetsAreEnforced(){String[] names=new String[51];for(int i=0;i<names.length;i++)names[i]=NAME.replace("证据","证据"+i);assertThrows(ReportingException.class,()->ReportingAttachments.expected(fixed(),snapshot(names)));var huge=new Artifact("f","batch","ATTACHMENT",NAME,"a".repeat(64),ReportingAttachmentPolicy.MAX_BYTES+1,"BOUND","");assertThrows(ReportingException.class,()->ReportingAttachments.describe(fixed(),snapshot(NAME),List.of(huge),true));}
|
||||
@Test void packageContainsExactApprovedAttachmentAndXmlReference()throws Exception{
|
||||
var snapshot=snapshot("unStruct/"+NAME);byte[] zip=ReportingPackage.generate(fixed(),snapshot,Map.of(NAME,BYTES));
|
||||
assertArrayEquals(zip,ReportingPackage.generate(fixed(),snapshot,Map.of(NAME,BYTES)));
|
||||
try(var input=new ZipInputStream(new ByteArrayInputStream(zip))){assertEquals("R.xml",input.getNextEntry().getName());assertTrue(new String(input.readAllBytes(),StandardCharsets.UTF_8).contains("unStruct/"+NAME));assertEquals("unStruct/"+NAME,input.getNextEntry().getName());assertArrayEquals(BYTES,input.readAllBytes());assertNull(input.getNextEntry());}
|
||||
}
|
||||
@Test void packageRejectsMissingExtraOrTamperedAttachment(){assertThrows(ReportingException.class,()->ReportingPackage.generate(fixed(),snapshot(NAME)));assertThrows(ReportingException.class,()->ReportingPackage.generate(fixed(),snapshot(""),Map.of(NAME,BYTES)));assertThrows(ReportingException.class,()->ReportingPackage.generate(fixed(),snapshot(NAME),Map.of(NAME,new byte[]{3})));}
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package cn.aixunkeji.datagov.integration.regulatoryreporting;
|
||||
|
||||
import java.io.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.zip.*;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class ReportingDocumentNotesTest {
|
||||
byte[] docx(String content)throws Exception{var out=new ByteArrayOutputStream();try(var zip=new ZipOutputStream(out)){zip.putNextEntry(new ZipEntry("word/document.xml"));zip.write(content.getBytes(StandardCharsets.UTF_8));zip.closeEntry();}return out.toByteArray();}
|
||||
@Test void extractsProseWithLocationAndManualConfirmation()throws Exception{var notes=ReportingDocumentNotes.extract("规范.docx",docx("<w:document xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main'><w:body><w:p><w:r><w:t>字段必填,请核对</w:t></w:r></w:p></w:body></w:document>"));assertEquals("段落1",notes.getFirst().location());assertTrue(notes.getFirst().confirmationRequired());assertEquals("字段必填,请核对",notes.getFirst().text());}
|
||||
@Test void scannedPdfIsExplicitlyUncertain()throws Exception{var out=new ByteArrayOutputStream();try(var pdf=new org.apache.pdfbox.pdmodel.PDDocument()){pdf.addPage(new org.apache.pdfbox.pdmodel.PDPage());pdf.save(out);}var notes=ReportingDocumentNotes.extract("扫描.pdf",out.toByteArray());assertTrue(notes.getFirst().text().contains("人工"));}
|
||||
@Test void invalidDocxCannotBecomeSilentEmptySuccess(){assertThrows(ReportingException.class,()->ReportingDocumentNotes.extract("a.docx",new byte[]{1,2,3}));}
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
package cn.aixunkeji.datagov.integration.regulatoryreporting;
|
||||
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
import java.util.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
import static cn.aixunkeji.datagov.integration.regulatoryreporting.ReportingExecutionApi.*;
|
||||
|
||||
class ReportingExecutionTest {
|
||||
final JdbcTemplate jdbc=mock(JdbcTemplate.class);
|
||||
final JsonMapper json=JsonMapper.builder().build();
|
||||
final ReportingActor actors=mock(ReportingActor.class);
|
||||
final ReportingRepository audit=mock(ReportingRepository.class);
|
||||
final ReportingFiles files=mock(ReportingFiles.class);
|
||||
final org.springframework.transaction.support.TransactionTemplate transactions=mock(org.springframework.transaction.support.TransactionTemplate.class);
|
||||
final ReportingExecutionService service=spy(new ReportingExecutionService(jdbc,json,actors,mock(ReportingPlanService.class),mock(ReportingStandardService.class),audit,files,mock(ReportingQuality.class),transactions));
|
||||
final ReportingActor.Scope actor=new ReportingActor.Scope(7,9);
|
||||
final String id=UUID.randomUUID().toString(),snapshot=UUID.randomUUID().toString();
|
||||
Batch batch(String state,int blocking){return new Batch(id,id,1,3,state,"2026-01-01","2026-02-01",10,blocking,0,List.of(),snapshot,null,"","2026-01-01T00:00:00");}
|
||||
@BeforeEach void setup(){when(actors.current(anyString())).thenReturn(actor);when(jdbc.update(anyString(),any(Object[].class))).thenReturn(1);doReturn(new Frozen(null,null,List.of(),List.of())).when(service).frozen(actor,id);when(transactions.execute(any())).thenAnswer(call->((org.springframework.transaction.support.TransactionCallback<?>)call.getArgument(0)).doInTransaction(mock(org.springframework.transaction.TransactionStatus.class)));}
|
||||
@Test void staleReviewCannotFreeze(){doReturn(batch("REVIEW_PENDING",0)).when(service).batch(actor,id);assertThrows(ReportingException.class,()->service.review(id,new Action(2,"已核对"),true));verifyNoInteractions(files,audit);}
|
||||
@Test void blockingIssuesCannotBeApproved(){doReturn(batch("REVIEW_PENDING",1)).when(service).batch(actor,id);assertThrows(ReportingException.class,()->service.review(id,new Action(3,"已核对"),true));verifyNoInteractions(files,audit);}
|
||||
@Test void generatedFileIsNeverSubmissionSuccess(){doReturn(batch("FILE_READY",0)).when(service).batch(actor,id);var result=service.precheck(id);assertFalse(result.submissionReady());assertFalse(result.blockers().isEmpty());}
|
||||
@Test void unknownStateCannotBeCancelledOrReprepared(){doReturn(batch("UNKNOWN",0)).when(service).batch(actor,id);assertThrows(ReportingException.class,()->service.cancel(id,new Action(3,"撤销")));assertThrows(ReportingException.class,()->service.prepare(id,new Action(3,"读取")));verifyNoInteractions(files,audit);}
|
||||
@Test void duplicateActionReturnsCurrentStateWithoutMutation(){var b=batch("FROZEN",0);doReturn(b).when(service).batch(actor,id);var action=new Action(2,"已核对");when(jdbc.queryForObject(startsWith("SELECT command_sha256"),eq(String.class),eq(9L),eq(id))).thenReturn(ReportingService.hash(json.writeValueAsString(List.of("APPROVE",2L,"已核对"))));assertEquals(b,service.review(id,action,true));verify(jdbc,never()).update(anyString(),any(Object[].class));verifyNoInteractions(files,audit);}
|
||||
@Test void reviewRequiresBoundImmutableFile(){doReturn(batch("REVIEW_PENDING",0)).when(service).batch(actor,id);when(files.required(actor,snapshot)).thenReturn(new ReportingFiles.Stored(snapshot,id,"SNAPSHOT",null,null,List.of(),"","PENDING",7,""));assertThrows(ReportingException.class,()->service.review(id,new Action(3,"已核对"),true));verifyNoInteractions(audit);}
|
||||
@Test void successfulReviewPreservesSnapshotAndAuditsReason(){doReturn(batch("REVIEW_PENDING",0)).when(service).batch(actor,id);when(files.required(actor,snapshot)).thenReturn(new ReportingFiles.Stored(snapshot,id,"SNAPSHOT",null,null,List.of(),"","BOUND",7,""));service.review(id,new Action(3,"空报和警告均已核对"),true);verify(audit).audit(actor,id,"BATCH_APPROVE_AND_FREEZE",4,"空报和警告均已核对");verify(files,never()).write(any(),anyString(),anyString(),anyString(),anyString(),any(),any());}
|
||||
@Test void periodsRejectOffByOneAndWrongQuarter(){assertDoesNotThrow(()->ReportingExecutionService.period("MONTH","2024-02-01","2024-03-01"));assertThrows(ReportingException.class,()->ReportingExecutionService.period("MONTH","2024-02-01","2024-02-29"));assertThrows(ReportingException.class,()->ReportingExecutionService.period("QUARTER","2024-02-01","2024-05-01"));assertThrows(ReportingException.class,()->ReportingExecutionService.period("CUSTOM","2024-01-01","2026-01-01"));}
|
||||
@Test void whitespaceCannotBypassAuditReasonStorageLimit(){doReturn(batch("DRAFT",0)).when(service).batch(actor,id);assertThrows(ReportingException.class,()->service.cancel(id,new Action(3," ".repeat(1000)+"x")));verify(jdbc,never()).update(anyString(),any(Object[].class));}
|
||||
void attachmentSnapshot(){
|
||||
doReturn(ReportingAttachmentsTest.fixed()).when(service).frozen(actor,id);
|
||||
var value=new Snapshot(id,"2026-01-01","2026-02-01","a".repeat(64),ReportingAttachmentsTest.snapshot(ReportingAttachmentsTest.NAME).resources());
|
||||
when(files.read(actor,snapshot)).thenReturn(json.writeValueAsBytes(value));
|
||||
when(jdbc.queryForObject(startsWith("SELECT frozen_sha256"),eq(String.class),eq(9L),eq(id))).thenReturn("a".repeat(64));
|
||||
when(files.required(actor,snapshot)).thenReturn(new ReportingFiles.Stored(snapshot,id,"SNAPSHOT",null,null,List.of(),"","BOUND",7,""));
|
||||
}
|
||||
@Test void missingAttachmentCannotFreezeEvenWithoutFieldErrors(){doReturn(batch("REVIEW_PENDING",0)).when(service).batch(actor,id);attachmentSnapshot();assertThrows(ReportingException.class,()->service.review(id,new Action(3,"审核"),true));verifyNoInteractions(audit);}
|
||||
@Test void unreadableAttachmentCannotFreeze(){doReturn(batch("REVIEW_PENDING",0)).when(service).batch(actor,id);attachmentSnapshot();when(files.list(actor,id)).thenReturn(List.of(ReportingAttachmentsTest.artifact(ReportingAttachmentsTest.NAME,"BOUND")));when(files.read(actor,"file-id")).thenThrow(ReportingException.forbidden());assertThrows(ReportingException.class,()->service.review(id,new Action(3,"审核"),true));verifyNoInteractions(audit);}
|
||||
@Test void afterFreezeUploadsCannotMutateArtifacts(){doReturn(batch("FROZEN",0)).when(service).batch(actor,id);assertThrows(ReportingException.class,()->service.attach(id,3,ReportingAttachmentsTest.NAME,"证据.txt",ReportingAttachmentsTest.BYTES));verifyNoInteractions(files,audit);}
|
||||
@Test void uploadedFileMustBelongToMappedSnapshotRecord(){doReturn(batch("REVIEW_PENDING",0)).when(service).batch(actor,id);attachmentSnapshot();String name=ReportingAttachmentsTest.NAME.replace("证据","其他");assertThrows(ReportingException.class,()->service.attach(id,3,name,"其他.txt",ReportingAttachmentsTest.BYTES));verify(files,never()).write(any(),anyString(),anyString(),anyString(),anyString(),any(),any());verifyNoInteractions(audit);}
|
||||
@Test void concurrentUploadAndReviewCannotBothClaimVersion(){doReturn(batch("REVIEW_PENDING",0)).when(service).batch(actor,id);attachmentSnapshot();when(jdbc.update(contains("command_sha256"),any(Object[].class))).thenReturn(0);assertThrows(ReportingException.class,()->service.attach(id,3,ReportingAttachmentsTest.NAME,"证据.txt",ReportingAttachmentsTest.BYTES));verify(files,never()).write(any(),anyString(),anyString(),anyString(),anyString(),any(),any());verifyNoInteractions(audit);}
|
||||
@Test void unknownAttachmentUploadIsNotReplayed(){var b=batch("ATTACHMENT_UNKNOWN",0);doReturn(b).when(service).batch(actor,id);var action=new Action(2,"附件:"+ReportingAttachmentsTest.NAME+":"+ReportingFiles.sha(ReportingAttachmentsTest.BYTES));when(jdbc.queryForObject(startsWith("SELECT command_sha256"),eq(String.class),eq(9L),eq(id))).thenReturn(ReportingService.hash(json.writeValueAsString(List.of("ATTACH",2L,action.reason()))));assertEquals(b,service.attach(id,2,ReportingAttachmentsTest.NAME,"证据.txt",ReportingAttachmentsTest.BYTES));verifyNoInteractions(files,audit);}
|
||||
@Test void reconcileCannotUnlockMissingCurrentUploadUsingAnOlderBoundFile(){doReturn(batch("ATTACHMENT_UNKNOWN",0)).when(service).batch(actor,id);when(files.reconcile(actor,id,"ATTACHMENT:2")).thenThrow(ReportingException.conflict("没有该操作"));assertThrows(ReportingException.class,()->service.reconcile(id));verify(jdbc,never()).update(anyString(),any(Object[].class));verifyNoInteractions(audit);}
|
||||
@Test void hangingUploadReconcilesItsClaimVersionOnly(){doReturn(batch("ATTACHING",0)).when(service).batch(actor,id);when(files.reconcile(actor,id,"ATTACHMENT:3")).thenThrow(ReportingException.conflict("没有该操作"));assertThrows(ReportingException.class,()->service.reconcile(id));verify(files).reconcile(actor,id,"ATTACHMENT:3");verify(jdbc,never()).update(anyString(),any(Object[].class));}
|
||||
@Test void attachmentNamesAreNotDisclosedAfterDatasetAccessIsRevoked(){doReturn(batch("FROZEN",0)).when(service).batch(actor,id);doThrow(ReportingException.forbidden()).when(files).authorizeMetadata(actor,snapshot);assertThrows(ReportingException.class,()->service.artifacts(id));verify(files,never()).list(any(),anyString());}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package cn.aixunkeji.datagov.integration.regulatoryreporting;
|
||||
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
import cn.aixunkeji.resource.api.assetupgrade.PrivateBusinessFileOwner.*;
|
||||
import cn.aixunkeji.datagov.dataproduct.api.reporting.ReportingDatasetDirectory;
|
||||
import java.util.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class ReportingFilesTest {
|
||||
final JdbcTemplate jdbc=mock(JdbcTemplate.class);
|
||||
final ReportingActor actors=mock(ReportingActor.class);
|
||||
final ReportingDatasetDirectory datasets=mock(ReportingDatasetDirectory.class);
|
||||
final ReportingFiles files=spy(new ReportingFiles(jdbc,JsonMapper.builder().build(),actors));
|
||||
final ReportingActor.Scope actor=new ReportingActor.Scope(7,9);
|
||||
final String id=UUID.randomUUID().toString(),batch=UUID.randomUUID().toString(),hash="a".repeat(64);
|
||||
final Target target=new Target("integration","REGULATORY_REPORTING_ARTIFACT",id,1,FileUse.EVIDENCE,"REGULATORY_REPORTING",batch,"snapshot.json",hash,2,"application/json",null,null);
|
||||
final Binding binding=new Binding("integration",target.objectType(),id,1,"file1","v1",hash,2,"application/json",FileUse.EVIDENCE,null,null);
|
||||
final ReportingDatasetDirectory.Read read=new ReportingDatasetDirectory.Read(null,List.of("id"),List.of());
|
||||
@BeforeEach void setup(){when(actors.current(anyString())).thenReturn(actor);ReflectionTestUtils.setField(files,"datasets",datasets);doReturn(new ReportingFiles.Stored(id,batch,"SNAPSHOT",target,binding,List.of(new ReportingExecutionApi.SourceProof("R",read,hash,"now")),hash,"BOUND",7,"now")).when(files).required(actor,id);}
|
||||
AuthorizationQuery query(long user,Binding b){return new AuthorizationQuery(new Context(1,user,9,9,"integration","reporting:"+id,"request"),target,Action.READ,b,hash);}
|
||||
@Test void everyChunkRequiresCurrentPolicyAndExactImmutableBinding(){var decision=files.authorize(query(7,binding));assertEquals(State.AVAILABLE,decision.state());assertTrue(decision.committedReference());verify(datasets).authorize(read,hash);}
|
||||
@Test void guessedIdAndCrossActorCannotRead(){assertThrows(ReportingException.class,()->files.authorize(query(8,binding)));verifyNoInteractions(datasets);}
|
||||
@Test void sameObjectWithDifferentPhysicalFileCannotRead(){var swapped=new Binding(binding.businessOwner(),binding.objectType(),id,1,"other","v1",hash,2,"application/json",FileUse.EVIDENCE,null,null);assertThrows(ReportingException.class,()->files.authorize(query(7,swapped)));verifyNoInteractions(datasets);}
|
||||
@Test void revokedSourcePolicyStopsOldSnapshotDownload(){doThrow(new IllegalStateException("revoked")).when(datasets).authorize(read,hash);assertThrows(IllegalStateException.class,()->files.authorize(query(7,binding)));}
|
||||
@Test void reviewerNeedsIndependentCurrentDatasetAuthorization(){var reviewer=new ReportingActor.Scope(8,9);var stored=files.required(actor,id);when(actors.current(anyString())).thenReturn(reviewer);doReturn(stored).when(files).required(reviewer,id);assertEquals(State.AVAILABLE,files.authorize(query(8,binding)).state());verify(datasets).authorize(read,hash);}
|
||||
}
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
package cn.aixunkeji.datagov.integration.regulatoryreporting;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||
import org.apache.poi.ss.util.CellRangeAddress;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.zip.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class ReportingImportParserTest {
|
||||
final JsonMapper json = JsonMapper.builder().build();
|
||||
ReportingImportParser.Input input(String name, String text) { return new ReportingImportParser.Input(name, text.getBytes(StandardCharsets.UTF_8)); }
|
||||
String xml(String code) { return "<p:Package xmlns:p='urn:test'><p:Head><p:resCode>"+code+"</p:resCode><p:resCaption>资源</p:resCaption></p:Head><p:Records><p:Record><p:ID>not-a-default</p:ID><p:AMOUNT>999</p:AMOUNT></p:Record></p:Records></p:Package>"; }
|
||||
String definition() { return """
|
||||
{"resources":[{"code":"R","name":"资源","fields":[
|
||||
{"name":"ID","label":"标识","type":"STRING","required":true,"nullable":false,"maxLength":36,"description":"说明","fillingRule":"正式规则","enumeration":["A","B"]},
|
||||
{"name":"AMOUNT","type":"DECIMAL","required":false,"nullable":true,"precision":18,"scale":2}]}]}
|
||||
"""; }
|
||||
@Test void namespaceAndHeadSurviveWithoutSampleValues() {
|
||||
var shape = ReportingTemplateParser.parse(xml("R"), null);
|
||||
assertEquals("urn:test", shape.structure().namespace()); assertEquals("R", shape.structure().resourceCode());
|
||||
assertEquals(List.of("ID", "AMOUNT"), shape.fields());
|
||||
assertFalse(json.writeValueAsString(shape).contains("not-a-default"));
|
||||
}
|
||||
@Test void xmlOnlyDoesNotInventConstraintsAndRequiresReview() {
|
||||
var r = new ReportingImportParser(json).parse(List.of(input("r.xml", xml("R"))));
|
||||
assertEquals(2, r.fields()); assertEquals(0, r.required()); assertEquals(0, r.nullable());
|
||||
var f = r.resources().getFirst().resource().fields().getFirst();
|
||||
assertNull(f.details().nullable()); assertNull(f.details().defaultValue()); assertFalse(f.details().source().confirmed());
|
||||
}
|
||||
@Test void jsonKeepsConstraintsRulesAndExactLocation() {
|
||||
var r = new ReportingImportParser(json).parse(List.of(input("spec.json", definition())));
|
||||
assertTrue(r.issues().isEmpty()); assertEquals(2,r.fields());assertEquals(1,r.required()); assertEquals(1,r.nullable());
|
||||
var f = r.resources().getFirst().resource().fields().getFirst();
|
||||
assertEquals("$.resources[0].fields[0]", f.details().source().location()); assertEquals("正式规则", f.details().fillingRule());
|
||||
assertEquals(List.of("A","B"), f.details().enumeration()); assertFalse(f.details().source().confirmed());
|
||||
}
|
||||
@Test void typedDefinitionAndXmlMergeWithoutLosingNumericConstraints() {
|
||||
for (var inputs : List.of(List.of(input("r.xml",xml("R")),input("d.json",definition())), List.of(input("d.json",definition()),input("r.xml",xml("R"))))) {
|
||||
var r = new ReportingImportParser(json).parse(inputs);
|
||||
assertEquals(1,r.resources().size()); assertFalse(r.issues().stream().anyMatch(i -> i.severity().equals("BLOCKING")));
|
||||
assertEquals("DECIMAL",r.resources().getFirst().resource().fields().get(1).type());assertNotNull(r.resources().getFirst().xml());
|
||||
}
|
||||
}
|
||||
@Test void unknownPropertiesAndInvalidRequiredHaveJsonPaths() {
|
||||
var r = new ReportingImportParser(json).parse(List.of(input("d.json",definition().replace("\"required\":true", "\"required\":\"yes\",\"unhandledRule\":true"))));
|
||||
assertTrue(r.issues().stream().anyMatch(i -> i.location().endsWith(".unhandledRule")));
|
||||
assertTrue(r.issues().stream().anyMatch(i -> i.location().equals("$.resources[0].fields[0]") && i.message().contains("required")));
|
||||
}
|
||||
@Test void duplicateFilesAndDuplicateResourceDefinitionsAreVisible() {
|
||||
var r = new ReportingImportParser(json).parse(List.of(input("a.json",definition()),input("b.json",definition())));
|
||||
assertEquals(1,r.resources().size());assertEquals("WARNING",r.issues().getFirst().severity());
|
||||
r = new ReportingImportParser(json).parse(List.of(input("a.json",definition()),input("b.json",definition()+" ")));
|
||||
assertTrue(r.issues().stream().anyMatch(i -> i.severity().equals("BLOCKING")));
|
||||
}
|
||||
@Test void zipProcessesAllXmlAndRejectsNonXmlOrTraversal() throws Exception {
|
||||
for (String bad : List.of("../bad.xml","unexpected.txt")) {
|
||||
var out = new ByteArrayOutputStream();
|
||||
try(var zip = new ZipOutputStream(out)) { zip.putNextEntry(new ZipEntry(bad));zip.write(xml("R").getBytes(StandardCharsets.UTF_8));zip.closeEntry(); }
|
||||
var r = new ReportingImportParser(json).parse(List.of(new ReportingImportParser.Input("files.zip",out.toByteArray())));
|
||||
assertTrue(r.issues().stream().anyMatch(i -> i.severity().equals("BLOCKING")));
|
||||
}
|
||||
var out = new ByteArrayOutputStream();
|
||||
try(var zip = new ZipOutputStream(out)) { for(String code:List.of("A","B")){ zip.putNextEntry(new ZipEntry(code+".xml"));zip.write(xml(code).getBytes(StandardCharsets.UTF_8));zip.closeEntry(); } }
|
||||
assertEquals(2,new ReportingImportParser(json).parse(List.of(new ReportingImportParser.Input("files.zip",out.toByteArray()))).resources().size());
|
||||
}
|
||||
@Test void excelRecognizesOffsetHeaderAndMergedResourceWithCoordinates() throws Exception {
|
||||
var out = new ByteArrayOutputStream();
|
||||
try(var book = new XSSFWorkbook()) {
|
||||
var sheet=book.createSheet("规范");var header=sheet.createRow(2);
|
||||
String[] names={"资源编码","资源名称","字段编码","类型","必填","长度","填写规则"};
|
||||
for(int i=0;i<names.length;i++)header.createCell(i).setCellValue(names[i]);
|
||||
for(int r=3;r<5;r++){var row=sheet.createRow(r);row.createCell(2).setCellValue(r==3?"ID":"NAME");row.createCell(3).setCellValue("STRING");row.createCell(4).setCellValue("是");row.createCell(5).setCellValue(100);row.createCell(6).setCellValue("完整填写");}
|
||||
sheet.getRow(3).createCell(0).setCellValue("R");sheet.getRow(3).createCell(1).setCellValue("资源");
|
||||
sheet.addMergedRegion(new CellRangeAddress(3,4,0,0));sheet.addMergedRegion(new CellRangeAddress(3,4,1,1));book.write(out);
|
||||
}
|
||||
var r=new ReportingImportParser(json).parse(List.of(new ReportingImportParser.Input("spec.xlsx",out.toByteArray())));
|
||||
assertTrue(r.issues().isEmpty(),r.issues().toString());assertEquals(2,r.fields());assertEquals(2,r.required());
|
||||
assertTrue(r.resources().getFirst().resource().fields().get(1).details().source().location().contains("C5"));
|
||||
}
|
||||
@Test void unsupportedAndMalformedDocumentsAreNotSuccessfulImports() {
|
||||
for(var file:List.of(input("spec.pdf","text"),input("bad.json","{}"),input("bad.xml","<!DOCTYPE a><Record><X/></Record>"))) {
|
||||
var r=new ReportingImportParser(json).parse(List.of(file));assertTrue(r.issues().stream().anyMatch(i -> i.severity().equals("BLOCKING")));
|
||||
}
|
||||
}
|
||||
@Test void oldDefinitionsDeserializeWithoutLosingCompatibility() {
|
||||
var old=json.readValue("{\"name\":\"ID\",\"label\":\"标识\",\"type\":\"STRING\",\"required\":true,\"maxLength\":36}", ReportingStandardApi.Field.class);
|
||||
assertNull(old.details());assertEquals(36,old.maxLength());
|
||||
var dept=json.readValue("{\"shortName\":\"\",\"level\":\"\",\"supervisor\":\"\"}", ReportingApi.Department.class);
|
||||
assertNull(dept.role());
|
||||
}
|
||||
@Test void explicitSqlTypeParametersArePreservedAndConflictsBlockAtField() {
|
||||
var r = new ReportingImportParser(json).parse(List.of(input("spec.json", definition().replace("\"STRING\"", "\"VARCHAR2(36)\"").replace("\"DECIMAL\"", "\"NUMBER(18,2)\""))));
|
||||
assertTrue(r.issues().isEmpty()); assertEquals(36,r.resources().getFirst().resource().fields().getFirst().maxLength());
|
||||
var bad = new ReportingImportParser(json).parse(List.of(input("bad.json", definition().replace("\"STRING\"", "\"VARCHAR(99)\""))));
|
||||
assertTrue(bad.issues().stream().anyMatch(i -> i.location().equals("$.resources[0].fields[0]") && i.message().contains("冲突")));
|
||||
}
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package cn.aixunkeji.datagov.integration.regulatoryreporting;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.mock.web.MockMultipartFile;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
|
||||
class ReportingImportServiceTest {
|
||||
final ReportingActor actors = mock(ReportingActor.class);
|
||||
final ReportingStandardService standards = mock(ReportingStandardService.class);
|
||||
final ReportingImportService service = new ReportingImportService(actors, standards, JsonMapper.builder().build());
|
||||
MockMultipartFile file(String name, String text) { return new MockMultipartFile("files",name,"application/octet-stream",text.getBytes(StandardCharsets.UTF_8)); }
|
||||
String xml = "<Package><Head><resCode>R</resCode><resCaption>资源</resCaption></Head><Records><Record><ID>PRIVATE_SAMPLE</ID></Record></Records></Package>";
|
||||
@Test void previewDoesNotPersistTemplatesOrReturnSamples() {
|
||||
var p = service.preview(List.of(file("r.xml",xml)));
|
||||
assertEquals(1,p.resources().size());verifyNoInteractions(standards);verify(actors).current("standard");
|
||||
assertFalse(JsonMapper.builder().build().writeValueAsString(p).contains("PRIVATE_SAMPLE"));
|
||||
}
|
||||
@Test void anyBlockedFilePreventsEveryTemplateWrite() {
|
||||
assertThrows(ReportingException.class, () -> service.confirm(List.of(file("r.xml",xml),file("bad.json","{}"))));
|
||||
verifyNoInteractions(standards);
|
||||
}
|
||||
@Test void confirmationBindsTemplateButDoesNotSaveOrPublishStandard() {
|
||||
when(standards.importTemplate(any())).thenReturn(new ReportingStandardApi.Template("id","hash","Record",List.of("ID")));
|
||||
var result=service.confirm(List.of(file("r.xml",xml)));
|
||||
assertEquals("id",result.resources().getFirst().templateId());
|
||||
verify(standards).importTemplate(any());verifyNoMoreInteractions(standards);
|
||||
}
|
||||
@Test void unauthorizedActorCannotParseOrWrite() {
|
||||
when(actors.current("standard")).thenThrow(ReportingException.forbidden());
|
||||
assertThrows(ReportingException.class, () -> service.preview(List.of(file("r.xml",xml))));
|
||||
assertThrows(ReportingException.class, () -> service.confirm(List.of(file("r.xml",xml))));verifyNoInteractions(standards);
|
||||
}
|
||||
@Test void duplicateJsonKeyIsBlockedRatherThanLastValueWinning() {
|
||||
var result=service.preview(List.of(file("r.json","{\"resources\":[],\"resources\":[]}")));
|
||||
assertTrue(result.issues().stream().anyMatch(i -> "BLOCKING".equals(i.severity())));
|
||||
}
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package cn.aixunkeji.datagov.integration.regulatoryreporting;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import java.util.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static cn.aixunkeji.datagov.integration.regulatoryreporting.ReportingExecutionApi.*;
|
||||
|
||||
class ReportingPackageTest {
|
||||
final String xml="<Package xmlns='urn:report'><Head><resCode>R</resCode><resCaption>资源</resCaption></Head><Records><Record><x>样例不是默认值</x></Record></Records></Package>";
|
||||
@Test void preservesNamespaceEscapesValuesAndDropsSample()throws Exception{var shape=ReportingTemplateParser.parse(xml,"Record");assertFalse(shape.structure().generationXml().contains("样例不是默认值"));var template=new ReportingStandardApi.Template("t","a".repeat(64),"Record",List.of("x"),shape.structure());var resource=new ReportingStandardApi.Resource("R","资源",List.of(new ReportingStandardApi.Field("x","","STRING",false,null,null,null)),"t");var data=new ResourceRows("R",List.of(Map.of("x","<&")));String generated=new String(ReportingPackage.xml(resource,template,data),StandardCharsets.UTF_8);assertTrue(generated.contains("urn:report"));assertTrue(generated.contains("<&"));assertEquals(List.of("x"),ReportingTemplateParser.fields(generated,"Record"));}
|
||||
@Test void unsupportedHeaderOrAttributesNeverSilentlyDisappear(){assertNull(ReportingTemplateParser.parse(xml.replace("</Head>","<unknown>v</unknown></Head>"),"Record").structure().generationXml());assertNull(ReportingTemplateParser.parse(xml.replace("<x>","<x required='Y'>"),"Record").structure().generationXml());}
|
||||
@Test void zipIsDeterministicAndContainsOnlyFixedResourceFile(){var shape=ReportingTemplateParser.parse(xml,"Record");var template=new ReportingStandardApi.Template("t","a".repeat(64),"Record",List.of("x"),shape.structure());var resource=new ReportingStandardApi.Resource("R","资源",List.of(new ReportingStandardApi.Field("x","","STRING",false,null,null,null)),"t");var frozen=new Frozen(null,new ReportingStandardApi.Definition("S","S","1","","",List.of(resource)),List.of(template),List.of());var snapshot=new Snapshot("batch","2026-01-01","2026-02-01","a".repeat(64),List.of(new ResourceRows("R",List.of(Map.of("x","value")))));assertArrayEquals(ReportingPackage.generate(frozen,snapshot),ReportingPackage.generate(frozen,snapshot));}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
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.mockito.Mockito.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static cn.aixunkeji.datagov.integration.regulatoryreporting.ReportingPlanApi.*;
|
||||
|
||||
class ReportingPlanMutationTest {
|
||||
final JdbcTemplate jdbc=mock(JdbcTemplate.class);
|
||||
final JsonMapper json=JsonMapper.builder().build();
|
||||
final ReportingActor actors=mock(ReportingActor.class);
|
||||
final ReportingRepository configs=mock(ReportingRepository.class);
|
||||
final ReportingStandardService standards=mock(ReportingStandardService.class);
|
||||
final ReportingPlanService service=spy(new ReportingPlanService(jdbc,json,actors,configs,standards));
|
||||
final ReportingActor.Scope actor=new ReportingActor.Scope(7,9);
|
||||
final String id="e8d386e0-5ad7-477c-9f40-62ef70789234";
|
||||
final Definition definition=new ReportingPlanServiceTest().definition(id,List.of());
|
||||
@BeforeEach void setup(){when(actors.current(anyString())).thenReturn(actor);when(jdbc.queryForObject(startsWith("SELECT command_sha256"),eq(String.class),eq(9L),eq(id))).thenReturn("other");}
|
||||
void state(String state,long version){doReturn(new View(id,version,state,definition,"now")).when(service).read(actor,id,true);}
|
||||
@Test void staleVersionCannotOverwriteOrReadDependencies(){state("DRAFT",4);assertThrows(ReportingException.class,()->service.save(id,new Save(3,definition)));verifyNoInteractions(configs,standards);verify(jdbc,never()).update(anyString(),any(Object[].class));}
|
||||
@Test void frozenConfigurationCannotBeOverwritten(){state("FROZEN",4);assertThrows(ReportingException.class,()->service.save(id,new Save(4,definition)));verifyNoInteractions(configs,standards);verify(jdbc,never()).update(anyString(),any(Object[].class));}
|
||||
@Test void exactSaveReplayDoesNotMutateOrAudit(){state("DRAFT",4);when(jdbc.queryForObject(startsWith("SELECT command_sha256"),eq(String.class),eq(9L),eq(id))).thenReturn(ReportingService.hash(json.writeValueAsString(new Save(3,definition))));assertEquals(4,service.save(id,new Save(3,definition)).version());verifyNoInteractions(configs,standards);verify(jdbc,never()).update(anyString(),any(Object[].class));}
|
||||
@Test void hiddenPlanCannotBeTransitionedOrAudited(){doReturn(null).when(service).read(actor,id,true);assertThrows(ReportingException.class,()->service.transition(id,new StateChange(4,"停用"),true));verifyNoInteractions(configs,standards);}
|
||||
@Test void invalidConfigurationCannotFreeze(){state("DRAFT",4);doReturn(new Check(List.of(new Issue("标准","BLOCKING","缺少映射")),false,false)).when(service).check(definition);assertThrows(ReportingException.class,()->service.transition(id,new StateChange(4,"核对配置"),false));verify(jdbc,never()).update(anyString(),any(Object[].class));verifyNoInteractions(configs);}
|
||||
@Test void freezePreservesNonExecutableBoundaryAndAuditsReason(){state("DRAFT",4);doReturn(new Check(List.of(new Issue("执行条件","BLOCKING","缺少完整读取")),true,false)).when(service).check(definition);when(jdbc.update(startsWith("UPDATE dg_reporting_plan"),any(Object[].class))).thenReturn(1);doReturn(new View(id,5,"FROZEN",definition,"now")).when(service).read(actor,id,false);var result=service.transition(id,new StateChange(4,"固定已核对的配置"),false);assertEquals("FROZEN",result.state());verify(configs).audit(actor,id,"PLAN_FREEZE",5,"固定已核对的配置");assertFalse(service.check(definition).executable());}
|
||||
@Test void disabledAndStalePlansCannotTransition(){state("DISABLED",4);assertThrows(ReportingException.class,()->service.transition(id,new StateChange(4,"停用"),true));state("DRAFT",5);assertThrows(ReportingException.class,()->service.transition(id,new StateChange(4,"停用"),true));verifyNoInteractions(configs);}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package cn.aixunkeji.datagov.integration.regulatoryreporting;
|
||||
|
||||
import cn.aixunkeji.datagov.dataproduct.api.reporting.ReportingDatasetDirectory;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import java.util.List;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static cn.aixunkeji.datagov.integration.regulatoryreporting.ReportingPlanApi.*;
|
||||
|
||||
class ReportingPlanServiceTest {
|
||||
final String id="e8d386e0-5ad7-477c-9f40-62ef70789234";
|
||||
ReportingStandardApi.Field text(boolean required,Integer max){return new ReportingStandardApi.Field("code","编码","STRING",required,max,null,null);}
|
||||
ReportingDatasetDirectory.Field source(String name,String label,String type,boolean nullable){return new ReportingDatasetDirectory.Field(name,label,type,nullable);}
|
||||
Definition definition(String regulator,List<Binding> bindings){return new Definition("science","科技","V1",regulator,id,id,id,1,"SASAC_SCIENCE_B","",bindings);}
|
||||
Binding binding(List<Mapping> mappings){return new Binding("T1","42",3,"100","200","a".repeat(64),mappings);}
|
||||
@Test void exactCodeWinsButStillRequiresHumanConfirmation(){
|
||||
var result=ReportingPlanService.suggest(List.of(text(true,20)),List.of(source("code","其他说明","VARCHAR(20)",false),source("other","编码","VARCHAR(20)",false))).getFirst();
|
||||
assertEquals(List.of("code"),result.candidates());assertEquals("EXACT_CODE",result.method());assertEquals("HIGH",result.confidence());assertTrue(result.compatible());assertTrue(result.reason().contains("确认"));
|
||||
}
|
||||
@Test void ambiguousAliasesAreNeverAutoSelected(){
|
||||
var result=ReportingPlanService.suggest(List.of(text(false,null)),List.of(source("first","编码","STRING",false),source("second","编码","STRING",false))).getFirst();
|
||||
assertEquals(2,result.candidates().size());assertEquals("AMBIGUOUS",result.confidence());assertFalse(result.compatible());
|
||||
}
|
||||
@Test void sourceCapacityMustFitWithoutTruncation(){assertFalse(ReportingPlanService.compatible(text(false,20),source("code","","VARCHAR(21)",false)));assertFalse(ReportingPlanService.compatible(text(false,20),source("code","","STRING",false)));assertTrue(ReportingPlanService.compatible(text(false,20),source("code","","VARCHAR(20)",false)));}
|
||||
@Test void nullableSourceCannotSatisfyRequiredTarget(){assertFalse(ReportingPlanService.compatible(text(true,null),source("code","","STRING",true)));}
|
||||
@Test void decimalsCheckBothIntegerAndFractionalCapacity(){
|
||||
var target=new ReportingStandardApi.Field("value","","DECIMAL",false,null,10,2);
|
||||
assertTrue(ReportingPlanService.compatible(target,source("value","","DECIMAL(8,2)",false)));
|
||||
assertFalse(ReportingPlanService.compatible(target,source("value","","DECIMAL(10,1)",false)));
|
||||
assertFalse(ReportingPlanService.compatible(target,source("value","","DECIMAL(8,3)",false)));
|
||||
assertFalse(ReportingPlanService.compatible(target,source("value","","DOUBLE",false)));
|
||||
}
|
||||
@Test void emptyIdentifiersReturnDomainValidationInsteadOfNullPointer(){var e=assertThrows(ReportingException.class,()->ReportingPlanService.normalize(definition(null,List.of())));assertEquals(400,e.status);}
|
||||
@Test void duplicateResourcesAndTargetsAreRejected(){var b=binding(List.of(new Mapping("code","code",true)));assertThrows(ReportingException.class,()->ReportingPlanService.normalize(definition(id,List.of(b,b))));assertThrows(ReportingException.class,()->ReportingPlanService.normalize(definition(id,List.of(binding(List.of(new Mapping("code","first",true),new Mapping("code","second",true)))))));}
|
||||
@Test void draftCanKeepUnmappedTargetButNotArbitraryIdentity(){assertEquals(1,ReportingPlanService.normalize(definition(id,List.of(binding(List.of(new Mapping("code","",false)))))).bindings().size());var b=new Binding("T1","42 OR 1=1",3,"100","200","a".repeat(64),List.of());assertThrows(ReportingException.class,()->ReportingPlanService.normalize(definition(id,List.of(b))));}
|
||||
}
|
||||
+1
-1
@@ -7,7 +7,7 @@ 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);
|
||||
return new Command(version, Kind.DEPARTMENT, "REGULATOR", "监管部门", null, "", enabled, new Department("", "", "", "REGULATOR"), 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,
|
||||
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package cn.aixunkeji.datagov.integration.regulatoryreporting;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import java.util.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
import cn.aixunkeji.datagov.governance.api.qualityrule.QualityRuleExecutionService;
|
||||
import cn.dev33.satoken.stp.StpUtil;
|
||||
|
||||
class ReportingQualityTest {
|
||||
@Test void pickerResolvesOwnerVersionWithoutRunningRule(){
|
||||
var owner=mock(QualityRuleExecutionService.class);var service=new ReportingQuality();org.springframework.test.util.ReflectionTestUtils.setField(service,"owner",owner);
|
||||
var actor=new ReportingActor.Scope(7,9);var command=new QualityRuleExecutionService.ResolveCommand(7,9,9,123);
|
||||
try(var auth=mockStatic(StpUtil.class)){
|
||||
when(owner.resolve(command)).thenReturn(new QualityRuleExecutionService.Resolution(QualityRuleExecutionService.ResolutionState.AUTHORIZED,123,456,"a".repeat(64),null));
|
||||
assertEquals("GOVERNANCE:123:456:"+"a".repeat(64),service.resolveReference(actor,123));
|
||||
auth.verify(()->StpUtil.checkPermission("aixun:governance:quality-rule:validate"));verify(owner,never()).execute(any());
|
||||
}
|
||||
}
|
||||
@Test void pickerRejectsUnavailableMismatchedOrMalformedOwnerEvidence(){
|
||||
var owner=mock(QualityRuleExecutionService.class);var service=new ReportingQuality();org.springframework.test.util.ReflectionTestUtils.setField(service,"owner",owner);
|
||||
try(var auth=mockStatic(StpUtil.class)){
|
||||
for(var response:List.of(new QualityRuleExecutionService.Resolution(QualityRuleExecutionService.ResolutionState.NOT_EXECUTABLE,1,2,"a".repeat(64),"DISABLED"),new QualityRuleExecutionService.Resolution(QualityRuleExecutionService.ResolutionState.AUTHORIZED,2,2,"a".repeat(64),null),new QualityRuleExecutionService.Resolution(QualityRuleExecutionService.ResolutionState.AUTHORIZED,1,0,"bad",null))){when(owner.resolve(any())).thenReturn(response);assertThrows(ReportingException.class,()->service.resolveReference(new ReportingActor.Scope(7,9),1));}
|
||||
}
|
||||
}
|
||||
@Test void pickerCannotBypassGovernancePermission(){var owner=mock(QualityRuleExecutionService.class);var service=new ReportingQuality();org.springframework.test.util.ReflectionTestUtils.setField(service,"owner",owner);try(var auth=mockStatic(StpUtil.class)){auth.when(()->StpUtil.checkPermission("aixun:governance:quality-rule:validate")).thenThrow(new IllegalStateException("DENIED"));assertThrows(IllegalStateException.class,()->service.resolveReference(new ReportingActor.Scope(7,9),1));verifyNoInteractions(owner);}}
|
||||
@Test void requiresExactFrozenOwnerReference(){assertNull(ReportingQuality.reference("校验金额大于零"));assertNull(ReportingQuality.reference("GOVERNANCE:1:2:latest"));assertNull(ReportingQuality.reference("GOVERNANCE:9999999999999999999:2:"+"a".repeat(64)));var ref=ReportingQuality.reference("GOVERNANCE:1:2:"+"a".repeat(64));assertEquals(1,ref.ruleId());assertEquals(2,ref.snapshotId());}
|
||||
@Test void proseRemainsBlockingAndOwnerReferenceIsExplicit(){var details=new ReportingStandardApi.FieldDetails("",false,"",List.of(),"","","金额必须正确","BLOCKING",null);var field=new ReportingStandardApi.Field("x","","STRING",true,null,null,null,details);var standard=new ReportingStandardApi.Definition("S","S","1","","",List.of(new ReportingStandardApi.Resource("R","R",List.of(field),null)));var issues=new ArrayList<ReportingExecutionApi.Issue>();ReportingRows.rules(standard,issues);assertEquals("UNBOUND_BUSINESS_RULE",issues.getFirst().rule());}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package cn.aixunkeji.datagov.integration.regulatoryreporting;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import java.util.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static cn.aixunkeji.datagov.integration.regulatoryreporting.ReportingPlanApi.*;
|
||||
import static cn.aixunkeji.datagov.integration.regulatoryreporting.ReportingExecutionApi.*;
|
||||
|
||||
class ReportingRowsTest {
|
||||
@Test void noRoundingOrUnknownDictionaryFallback(){var decimal=new Mapping("x","s",true,new Transform("DECIMAL","2","",Map.of(),List.of()));assertEquals("1.20",ReportingMapping.apply(decimal,Map.of("s","1.2")));assertThrows(ArithmeticException.class,()->ReportingMapping.apply(decimal,Map.of("s","1.234")));var dictionary=new Mapping("x","s",true,new Transform("DICTIONARY","","",Map.of("a","1"),List.of()));assertThrows(IllegalArgumentException.class,()->ReportingMapping.apply(dictionary,Map.of("s","missing")));}
|
||||
@Test void arbitraryCodeIsNotExecutable(){assertThrows(ReportingException.class,()->ReportingMapping.validate(new Mapping("x","s",true,new Transform("JS","Runtime.exec('x')","",Map.of(),List.of()))));}
|
||||
@Test void explicitDefaultAndStrictDates(){var mapping=new Mapping("x","s",true,new Transform("DEFAULT","0","",Map.of(),List.of()));assertEquals("0",ReportingMapping.apply(mapping,Map.of()));var date=new Mapping("x","s",true,new Transform("DATE","uuuuMMdd","uuuu-MM-dd",Map.of(),List.of()));assertEquals("2024-02-29",ReportingMapping.apply(date,Map.of("s","20240229")));assertThrows(RuntimeException.class,()->ReportingMapping.apply(date,Map.of("s","20230229")));}
|
||||
@Test void errorsIdentifyFieldAndRowWithoutExposingRawKey(){var field=new ReportingStandardApi.Field("x","","STRING",true,2,null,null);var resource=new ReportingStandardApi.Resource("R","R",List.of(field),null);var binding=new Binding("R","1",1,"2","3","a".repeat(64),List.of(new Mapping("x","s",true)));var selection=new Selection("R","",List.of("id"),List.of());var result=ReportingRows.map(resource,binding,selection,List.of(Map.of("id","private-identity","s","long"),Map.of("id","private-identity","s","ok")));assertEquals(2,result.issues().size());assertEquals("x",result.issues().getFirst().field());assertEquals(1,result.issues().getFirst().row());assertFalse(result.issues().toString().contains("private-identity"));assertEquals("KEY_UNIQUE",result.issues().getLast().rule());}
|
||||
@Test void invalidXmlCharacterAndPrecisionBlock(){assertNotNull(ReportingRows.validate(new ReportingStandardApi.Field("x","","STRING",false,null,null,null),"a\u0000b"));assertNotNull(ReportingRows.validate(new ReportingStandardApi.Field("x","","DECIMAL",true,null,5,2),"1234.56"));}
|
||||
}
|
||||
+15
@@ -59,4 +59,19 @@ class ReportingServiceTest {
|
||||
service.save(ROOT, department(-1, true));
|
||||
assertThrows(ReportingException.class, () -> service.save(systemId, system("https://example.org", "TEST", "SECRET_REF", null, true)));
|
||||
}
|
||||
@Test void legacyAndInternalDepartmentsNeverBecomeRegulatorsImplicitly() {
|
||||
for (String role : new String[]{null, "UNCLASSIFIED", "INTERNAL"}) {
|
||||
states.clear();
|
||||
var c = department(-1, true);
|
||||
service.save(ROOT, new Command(-1, c.kind(), c.code(), c.name(), null, "", true, new Department("", "", "", role), null, null, null));
|
||||
assertThrows(ReportingException.class, () -> service.save(systemId, system("https://example.org", "TEST", "NONE", null, false)));
|
||||
assertFalse(states.containsKey(systemId));
|
||||
}
|
||||
}
|
||||
@Test void classificationCannotDetachExistingSystems() {
|
||||
service.save(ROOT, department(-1, true)); when(repository.children(actor, ROOT)).thenReturn(true);
|
||||
var c = department(0, true);
|
||||
assertThrows(ReportingException.class, () -> service.save(ROOT, new Command(0, c.kind(), c.code(), c.name(), null, "", true, new Department("", "", "", "INTERNAL"), null, null, null)));
|
||||
assertEquals("REGULATOR", states.get(ROOT).command().department().role());
|
||||
}
|
||||
}
|
||||
|
||||
+26
-6
@@ -61,16 +61,36 @@ class ReportingStandardServiceTest {
|
||||
assertEquals("PUBLISHED", service.publish(id, command).status());
|
||||
verifyNoInteractions(jdbc, audit);
|
||||
}
|
||||
@Test void confirmedDifferenceCanPublishWithAuditedReason() {
|
||||
@Test void confirmedReasonCannotBypassBlockingTemplateDifference() {
|
||||
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, "已核对目标模板");
|
||||
assertThrows(ReportingException.class, () -> service.publish(id, new Action(0, "已核对目标模板")));
|
||||
verifyNoInteractions(jdbc, audit);
|
||||
}
|
||||
@Test void unconfirmedImportedFieldCannotPublish() {
|
||||
var field = new Field("ID", "标识", "STRING", true, 36, null, null,
|
||||
new FieldDetails("", false, null, List.of(), "", "", "", "BLOCKING", new Source("spec.json", "$.resources[0].fields[0]", "{}", "EXACT", false)));
|
||||
var d = new Definition("STD", "标准", "1", "", "", List.of(new Resource("ROW", "资源", List.of(field), template)));
|
||||
doReturn(state("DRAFT", d)).when(service).read(actor, id, true);
|
||||
assertThrows(ReportingException.class, () -> service.publish(id, new Action(0, "")));
|
||||
verifyNoInteractions(jdbc, audit);
|
||||
}
|
||||
@Test void consistentDefinitionPublishesAndAudits() {
|
||||
doReturn(state("DRAFT", definition(template))).when(service).read(actor, id, true);
|
||||
doReturn(state("PUBLISHED", definition(template))).when(service).read(actor, id, false);
|
||||
doReturn(new Template(template, "hash", "ROW", List.of("ID"))).when(service).template(actor, template);
|
||||
assertEquals("PUBLISHED", service.publish(id, new Action(0, "")).status());
|
||||
verify(audit).audit(actor, id, "STANDARD_PUBLISH", 1, "");
|
||||
}
|
||||
@Test void confirmationDoesNotInventXmlNullability() {
|
||||
var field = new Field("ID", "标识", "STRING", false, null, null, null,
|
||||
new FieldDetails("", null, null, List.of(), "", "", "", "BLOCKING", new Source("spec.xml", "/Record/ID", "ID", "REVIEW_REQUIRED", true)));
|
||||
var d = new Definition("STD", "标准", "1", "", "", List.of(new Resource("ROW", "资源", List.of(field), template)));
|
||||
doReturn(state("DRAFT", d)).when(service).read(actor, id, true);
|
||||
assertThrows(ReportingException.class, () -> service.publish(id, new Action(0, "")));
|
||||
verifyNoInteractions(jdbc, audit);
|
||||
}
|
||||
@Test void disablingRetainsDefinitionAndRequiresReason() {
|
||||
doReturn(state("PUBLISHED", definition(template))).when(service).read(actor, id, true);
|
||||
|
||||
+8
@@ -67,6 +67,14 @@ class AnalyticsSqlCompilerTest {
|
||||
assertThrows(IllegalArgumentException.class, () -> AnalyticsSqlCompiler.compile(command(new Plan(rows().columns(), List.of(),
|
||||
List.of(), List.of(), List.of(), 1001))));
|
||||
}
|
||||
@Test void completeReadUsesSeparateBoundedRowOnlyEntryPoint(){
|
||||
var p=new Plan(List.of("department"),List.of(),List.of(),List.of(),List.of(),100000);
|
||||
assertEquals("SELECT `department` FROM `db`.`t` LIMIT 100001",AnalyticsSqlCompiler.compileForSnapshot(p,List.of("department"),"MYSQL","db","schema","t").sql());
|
||||
assertTrue(AnalyticsSqlCompiler.compileForSnapshot(p,List.of("department"),"ORACLE","db","schema","t").sql().endsWith("FETCH FIRST 100001 ROWS ONLY"));
|
||||
assertTrue(AnalyticsSqlCompiler.compileForSnapshot(p,List.of("department"),"SQLSERVER","db","schema","t").sql().contains("TOP 100001"));
|
||||
assertThrows(IllegalArgumentException.class,()->AnalyticsSqlCompiler.compile(command(p)));
|
||||
assertThrows(IllegalArgumentException.class,()->AnalyticsSqlCompiler.compileForSnapshot(new Plan(List.of(),List.of(),List.of(new Measure("amount","SUM","total")),List.of(),List.of(),100000),List.of("amount"),"MYSQL","db","schema","t"));
|
||||
}
|
||||
@Test void sortingMustUseSelectedOutput() {
|
||||
assertThrows(IllegalArgumentException.class, () -> AnalyticsSqlCompiler.compile(command(new Plan(rows().columns(), List.of(),
|
||||
List.of(), List.of(), List.of(new Sort("status", "ASC")), 10))));
|
||||
|
||||
在新工单中引用
屏蔽一个用户