diff --git a/aixun-modules/aixun-dataops/src/main/java/cn/aixunkeji/datagov/dataops/lakehouse/LakehouseTableFileReferenceDirectory.java b/aixun-modules/aixun-dataops/src/main/java/cn/aixunkeji/datagov/dataops/lakehouse/LakehouseTableFileReferenceDirectory.java index c6927b4..8ca988b 100644 --- a/aixun-modules/aixun-dataops/src/main/java/cn/aixunkeji/datagov/dataops/lakehouse/LakehouseTableFileReferenceDirectory.java +++ b/aixun-modules/aixun-dataops/src/main/java/cn/aixunkeji/datagov/dataops/lakehouse/LakehouseTableFileReferenceDirectory.java @@ -17,7 +17,7 @@ public class LakehouseTableFileReferenceDirectory { } public Resolution resolveForIngestion(long actorId, long orgId, long layerId) { - return resolve(actorId, orgId, layerId, false); + return resolve(actorId, orgId, layerId, LoginHelper.isSuperAdmin(actorId)); } private Resolution resolve(long actorId, long orgId, long layerId, boolean unrestricted) { diff --git a/aixun-modules/aixun-dataops/src/main/java/cn/aixunkeji/datagov/dataops/storage/StorageResourceService.java b/aixun-modules/aixun-dataops/src/main/java/cn/aixunkeji/datagov/dataops/storage/StorageResourceService.java index 9ddd7f8..2f5ea8d 100644 --- a/aixun-modules/aixun-dataops/src/main/java/cn/aixunkeji/datagov/dataops/storage/StorageResourceService.java +++ b/aixun-modules/aixun-dataops/src/main/java/cn/aixunkeji/datagov/dataops/storage/StorageResourceService.java @@ -83,10 +83,10 @@ public class StorageResourceService { return detail(currentActor(), resourceId); } - /** Server-derived identity only; ingestion never inherits the administrator scope bypass. */ + /** Server-derived identity only; use the same owner policy for viewing and ingestion. */ public StorageResourceDetailView detailForIngestion(long actorId, long orgId, long resourceId) { if (actorId <= 0 || orgId <= 0) throw new StorageScopeException(); - return detail(new StorageActor(actorId, orgId, false), resourceId); + return detail(new StorageActor(actorId, orgId, LoginHelper.isSuperAdmin(actorId)), resourceId); } private StorageResourceDetailView detail(StorageActor actor, long resourceId) { diff --git a/aixun-modules/aixun-dataops/src/main/java/cn/aixunkeji/datagov/dataops/storage/StorageTableFileReferenceDirectory.java b/aixun-modules/aixun-dataops/src/main/java/cn/aixunkeji/datagov/dataops/storage/StorageTableFileReferenceDirectory.java index 0f0590d..e622291 100644 --- a/aixun-modules/aixun-dataops/src/main/java/cn/aixunkeji/datagov/dataops/storage/StorageTableFileReferenceDirectory.java +++ b/aixun-modules/aixun-dataops/src/main/java/cn/aixunkeji/datagov/dataops/storage/StorageTableFileReferenceDirectory.java @@ -18,7 +18,7 @@ public class StorageTableFileReferenceDirectory { } public Resolution resolveForIngestion(long actorId, long orgId, long resourceId, long spaceId) { - return resolve(actorId, orgId, resourceId, spaceId, false); + return resolve(actorId, orgId, resourceId, spaceId, LoginHelper.isSuperAdmin(actorId)); } private Resolution resolve(long actorId, long orgId, long resourceId, long spaceId, boolean unrestricted) { @@ -54,7 +54,7 @@ public class StorageTableFileReferenceDirectory { } public ObjectResolution resolveObjectForIngestion(long actorId, long orgId, long resourceId, String externalObjectId) { - return resolveObject(actorId, orgId, resourceId, externalObjectId, false); + return resolveObject(actorId, orgId, resourceId, externalObjectId, LoginHelper.isSuperAdmin(actorId)); } private ObjectResolution resolveObject(long actorId, long orgId, long resourceId, String externalObjectId, diff --git a/aixun-modules/aixun-dataops/src/test/java/cn/aixunkeji/datagov/dataops/storage/StorageTableFileReferenceDirectoryTest.java b/aixun-modules/aixun-dataops/src/test/java/cn/aixunkeji/datagov/dataops/storage/StorageTableFileReferenceDirectoryTest.java index 831741b..e64d7f4 100644 --- a/aixun-modules/aixun-dataops/src/test/java/cn/aixunkeji/datagov/dataops/storage/StorageTableFileReferenceDirectoryTest.java +++ b/aixun-modules/aixun-dataops/src/test/java/cn/aixunkeji/datagov/dataops/storage/StorageTableFileReferenceDirectoryTest.java @@ -16,27 +16,40 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; class StorageTableFileReferenceDirectoryTest { + private static final long ADMIN=cn.aixunkeji.common.core.constant.SystemConstants.SUPER_ADMIN_USER_ID; private final StorageResourceRepository repository = mock(StorageResourceRepository.class); private final StorageTableFileReferenceDirectory directory = new StorageTableFileReferenceDirectory(repository); - @Test void ingestionAlwaysUsesStrictOrganizationEvenForAdministratorId() { + @Test void ingestionUsesSameTrustedAdministratorPolicyAsViewing() { when(repository.requireResource(any(), org.mockito.ArgumentMatchers.eq(30L))) .thenThrow(new StorageScopeException()); - assertThat(directory.resolveForIngestion(1, 20, 30, 40).status()) + assertThat(directory.resolveForIngestion(ADMIN, 20, 30, 40).status()) .isEqualTo(StorageTableFileReferenceDirectory.Status.OUTSIDE_SCOPE); - assertThat(directory.resolveObjectForIngestion(1, 20, 30, "sales").status()) + assertThat(directory.resolveObjectForIngestion(ADMIN, 20, 30, "sales").status()) .isEqualTo(StorageTableFileReferenceDirectory.Status.OUTSIDE_SCOPE); var capture = org.mockito.ArgumentCaptor.forClass(StorageActor.class); org.mockito.Mockito.verify(repository, org.mockito.Mockito.times(2)) .requireResource(capture.capture(), org.mockito.ArgumentMatchers.eq(30L)); assertThat(capture.getAllValues()).allSatisfy(actor -> { - assertThat(actor.actorId()).isEqualTo(1); + assertThat(actor.actorId()).isEqualTo(ADMIN); assertThat(actor.departmentId()).isEqualTo(20); - assertThat(actor.unrestricted()).isFalse(); + assertThat(actor.unrestricted()).isTrue(); }); } + @Test void ordinaryActorCannotUseAdministratorScopeAcrossOrganizations() { + when(repository.requireResource(any(), org.mockito.ArgumentMatchers.eq(30L))) + .thenAnswer(invocation -> { + StorageActor actor=invocation.getArgument(0); + assertThat(actor.unrestricted()).isFalse(); + assertThat(actor.departmentId()).isEqualTo(20); + throw new StorageScopeException(); + }); + assertThat(directory.resolveForIngestion(8,20,30,40).status()).isEqualTo(StorageTableFileReferenceDirectory.Status.OUTSIDE_SCOPE); + assertThat(directory.resolveObjectForIngestion(8,20,30,"sales").status()).isEqualTo(StorageTableFileReferenceDirectory.Status.OUTSIDE_SCOPE); + } + @Test void resolvesOwnerResourceSpaceAndReturnsOnlySecretReferenceMetadata() { when(repository.requireResource(any(), org.mockito.ArgumentMatchers.eq(30L))).thenReturn(new StorageResourceView( @@ -53,5 +66,7 @@ class StorageTableFileReferenceDirectoryTest { assertThat(result.status()).isEqualTo(StorageTableFileReferenceDirectory.Status.AUTHORIZED); assertThat(result.secretRef()).isEqualTo("file:///hive-password?version=1"); assertThat(result.toString()).doesNotContain("hive-password").contains("REDACTED"); + assertThat(directory.resolveForIngestion(10L,20L,30L,40L)).isEqualTo(result); + assertThat(directory.resolveForIngestion(ADMIN,99L,30L,40L).status()).isEqualTo(StorageTableFileReferenceDirectory.Status.AUTHORIZED); } } diff --git a/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/datasource/ReportingSourceRead.java b/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/datasource/ReportingSourceRead.java new file mode 100644 index 0000000..ce9591e --- /dev/null +++ b/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/datasource/ReportingSourceRead.java @@ -0,0 +1,17 @@ +package cn.aixunkeji.datagov.integration.datasource; + +import java.util.List; +import java.util.Map; +import cn.aixunkeji.datagov.dataproduct.api.reporting.ReportingDatasetDirectory; + +/** Reporting-owned source selection, never a published/governed dataset identity. */ +public final class ReportingSourceRead { + private ReportingSourceRead() { } + public record Table(String alias,String catalog,String schema,String table) { } + public record Join(String leftTable,String leftField,String rightTable,String rightField) { } + public record Field(String name,String tableAlias,String column) { } + public record Definition(long sourceId,List tables,List joins,List fields) { } + public record Fixed(Definition definition,long sourceVersion,String schemaSha256,List fields) { } + public record Query(Fixed source,List columns,List filters) { } + public record Rows(List> rows,String authorizationSha256,String observedAt,boolean complete) { } +} diff --git a/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/datasource/ReportingSourceService.java b/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/datasource/ReportingSourceService.java new file mode 100644 index 0000000..9543551 --- /dev/null +++ b/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/datasource/ReportingSourceService.java @@ -0,0 +1,177 @@ +package cn.aixunkeji.datagov.integration.datasource; + +import cn.aixunkeji.common.satoken.utils.LoginHelper; +import cn.dev33.satoken.stp.StpUtil; +import cn.aixunkeji.datagov.integration.api.DataSourceView; +import cn.aixunkeji.datagov.integration.api.datasource.DataSourceObjects; +import cn.aixunkeji.datagov.integration.m2.DataSourceRegistry; +import cn.aixunkeji.datagov.dataproduct.api.reporting.ReportingDatasetDirectory; +import org.springframework.stereotype.Service; +import jakarta.annotation.PreDestroy; +import java.sql.*; +import java.nio.charset.StandardCharsets; +import java.util.*; +import java.util.concurrent.*; +import tools.jackson.databind.json.JsonMapper; +import static cn.aixunkeji.datagov.integration.datasource.ReportingSourceRead.*; + +/** Reuses registered source credentials and browse scope. Generates only bound SELECTs. */ +@Service +public class ReportingSourceService { + private final DataSourceRegistry registry; + private final DataSourceObjectConnection credentials; + private final DataSourceBiQueryConnection connections; + private final ExecutorService workers=new ThreadPoolExecutor(0,4,30,TimeUnit.SECONDS,new SynchronousQueue<>(),Thread.ofPlatform().daemon().name("reporting-source-",0).factory(),new ThreadPoolExecutor.AbortPolicy()); + private static final JsonMapper JSON=JsonMapper.builder().build(); + public ReportingSourceService(DataSourceRegistry registry,DataSourceObjectConnection credentials,DataSourceBiQueryConnection connections){this.registry=registry;this.credentials=credentials;this.connections=connections;} + private DataSourceAccessScope actor(){ + StpUtil.checkPermission("aixun:integration:regulatory-reporting:view"); + StpUtil.checkPermission("aixun:integration:data-source:browse"); + StpUtil.checkPermission("aixun:integration:data-source:preview"); + Long user=LoginHelper.getUserId(),dept=LoginHelper.getDeptId(); + if(user==null||dept==null||user<=0||dept<=0)throw DataSourceOperationException.forbidden(); + return new DataSourceAccessScope(user,dept); + } + private DataSourceView source(DataSourceAccessScope scope,long id){ + var s=registry.find(scope,id); + if(s==null||s.orgScopeId()!=scope.orgScopeId())throw DataSourceOperationException.forbidden(); + DataSourceObjectService.requireReady(s);credentials.requireActive(s); + if("HIVE".equals(s.type()))throw invalid("直连报送暂不支持Hive;可使用原授权数据集路径"); + return s; + } + public Fixed describe(Definition d){ + validate(d);var a=actor();var before=source(a,d.sourceId()); + Fixed fixed=work(()->connections.read(before,a,c->inspect(c,before,d))); + same(before,source(a,d.sourceId()));return fixed; + } + public void require(Fixed fixed){if(fixed==null||!fixed.equals(describe(fixed.definition())))throw invalid("来源连接或表字段结构已变化,请重新绑定");} + public Rows read(Query q,boolean preview){ + if(q==null||q.source()==null)throw invalid("请选择直连来源"); + validate(q.source().definition());var a=actor();var before=source(a,q.source().definition().sourceId()); + var result=work(()->connections.read(before,a,c->{ + if(!q.source().equals(inspect(c,before,q.source().definition())))throw invalid("来源版本或结构已变化"); + var sql=compile(q,before.type(),c.getMetaData().getIdentifierQuoteString()); + List> rows=new ArrayList<>();int bytes=0,limit=preview?5:100000; + try(var statement=c.prepareStatement(sql.sql(),ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_READ_ONLY)){ + statement.setQueryTimeout(10);statement.setMaxRows(limit+1);statement.setFetchSize(100); + for(int i=0;i(); + for(int i=0;i8_000_000)throw invalid("完整取数超过8 MB,请缩小范围"); + row.put(q.columns().get(i),value); + } + rows.add(Collections.unmodifiableMap(row)); + } + } + } + return List.copyOf(rows); + })); + same(before,source(a,q.source().definition().sourceId()));require(q.source()); + return new Rows(result,proof(a,before,q),java.time.LocalDateTime.now().toString(),!preview); + } + public void authorize(Query q,String expected){ + var a=actor();require(q.source());var s=source(a,q.source().definition().sourceId()); + compile(q,s.type(),"MYSQL".equals(s.type())||"DORIS".equals(s.type())?"`":"\""); + if(expected==null||!expected.equals(proof(a,s,q)))throw DataSourceOperationException.forbidden(); + } + static String readCell(ResultSet data,int index)throws SQLException{ + int type=data.getMetaData().getColumnType(index); + if(!Set.of(Types.CHAR,Types.VARCHAR,Types.LONGVARCHAR,Types.NCHAR,Types.NVARCHAR,Types.LONGNVARCHAR,Types.CLOB,Types.NCLOB).contains(type))return data.getString(index); + // Bounded character streaming preserves the complete value; no preview-length truncation. + try(var reader=data.getCharacterStream(index)){ + if(reader==null)return null;var out=new StringBuilder();char[] buffer=new char[4096];int n; + while((n=reader.read(buffer))!=-1){if(out.length()+n>1_000_000)throw invalid("单字段超过100万字符,请整改或缩小范围");out.append(buffer,0,n);} + return out.toString(); + }catch(java.io.IOException e){throw new SQLException("REPORTING_CELL_READ_FAILED");} + } + private Fixed inspect(Connection c,DataSourceView s,Definition d)throws SQLException{ + Map> tables=new LinkedHashMap<>(); + for(var table:d.tables()){ + var request=new DataSourceObjectRequest("COLUMN",table.catalog(),table.schema(),table.table(),null,1,100,100); + var first=(DataSourceObjects.Page)DataSourceObjectJdbc.browse(c,s.type(),s.databaseName(),request); + Map fields=new LinkedHashMap<>(); + for(var f:first.rows()){var column=(DataSourceObjects.Column)f;fields.put(column.name(),column);} + if(first.total()>100){var rest=(DataSourceObjects.Page)DataSourceObjectJdbc.browse(c,s.type(),s.databaseName(),new DataSourceObjectRequest("COLUMN",table.catalog(),table.schema(),table.table(),null,2,100,100));for(var f:rest.rows()){var column=(DataSourceObjects.Column)f;fields.put(column.name(),column);}} + if(fields.size()!=first.total())throw invalid("来源字段读取不完整");tables.put(table.alias(),fields); + } + List projected=new ArrayList<>(); + for(var f:d.fields()){ + var field=allowed(tables,f.tableAlias(),f.column()); + projected.add(new ReportingDatasetDirectory.Field(f.name(),Objects.toString(field.comment(),f.name()),field.type(),Boolean.TRUE.equals(field.nullable())||!d.tables().getFirst().alias().equals(f.tableAlias()))); + } + for(var j:d.joins()){ + allowed(tables,j.leftTable(),j.leftField());allowed(tables,j.rightTable(),j.rightField()); + var right=d.tables().stream().filter(t->t.alias().equals(j.rightTable())).findFirst().orElseThrow(); + requireUniqueJoin(c.getMetaData(),s.type(),right,j.rightField()); + } + return new Fixed(d,s.version(),hash(JSON.writeValueAsString(List.of(d,tables))),List.copyOf(projected)); + } + static void requireUniqueJoin(DatabaseMetaData md,String type,Table table,String field)throws SQLException{ + Map> indexes=new HashMap<>(); + String catalog=Set.of("ORACLE","DAMENG","KINGBASE").contains(type)?null:table.catalog(); + try(var rows=md.getIndexInfo(catalog,table.schema(),table.table(),true,false)){ + while(rows.next()){ + if(!table.table().equals(rows.getString("TABLE_NAME"))||rows.getBoolean("NON_UNIQUE"))continue; + String name=rows.getString("INDEX_NAME"),column=rows.getString("COLUMN_NAME"); + if(name!=null)indexes.computeIfAbsent(name,k->new ArrayList<>()).add(column); + } + } + if(indexes.values().stream().noneMatch(columns->columns.size()==1&&field.equals(columns.getFirst())))throw invalid("关联字段缺少可确认的单列唯一约束:"+table.alias()+"."+field+";请使用唯一关联表或标准中间库"); + } + private static DataSourceObjects.Column allowed(Map> tables,String alias,String name){ + var field=tables.getOrDefault(alias,Map.of()).get(name); + if(field==null||field.masked()||field.type()==null||field.type().toUpperCase(Locale.ROOT).matches(".*(BINARY|BLOB|RAW|GEOMETRY|ARRAY|STRUCT|OBJECT).*"))throw invalid("字段不存在、受保护或不是可报送标量:"+alias+"."+name); + return field; + } + public static void validate(Definition d){ + if(d==null||d.sourceId()<=0||d.tables()==null||d.tables().isEmpty()||d.tables().size()>5||d.joins()==null||d.joins().size()!=d.tables().size()-1||d.fields()==null||d.fields().isEmpty()||d.fields().size()>200)throw invalid("直连来源定义无效(最多5表、200字段)"); + Set aliases=new HashSet<>(),names=new HashSet<>(); + for(var t:d.tables()){if(t==null||!aliases.add(id(t.alias())))throw invalid("表别名重复");id(t.table());if(t.catalog()!=null)id(t.catalog());if(t.schema()!=null)id(t.schema());} + Set linked=new HashSet<>();linked.add(d.tables().getFirst().alias()); + for(var j:d.joins()){ + if(j==null||!linked.contains(j.leftTable())||!aliases.contains(j.rightTable())||!linked.add(j.rightTable()))throw invalid("关联须从主表依次连接各来源表,不能循环"); + id(j.leftField());id(j.rightField()); + } + for(var f:d.fields())if(f==null||!names.add(id(f.name()))||!aliases.contains(f.tableAlias()))throw invalid("输出别名重复或来源表无效");else id(f.column()); + } + record Sql(String sql,List arguments) { } + static Sql compile(Query q,String type,String quote){ + if(!Set.of("`","\"").contains(quote))throw invalid("数据库标识引用方式不支持"); + var d=q.source().definition();validate(d); + Map fields=new HashMap<>();d.fields().forEach(f->fields.put(f.name(),f)); + if(q.columns()==null||q.columns().isEmpty()||new HashSet<>(q.columns()).size()!=q.columns().size()||!fields.keySet().containsAll(q.columns())||q.filters()==null||q.filters().size()>20)throw invalid("取数列或过滤无效"); + String sql="SELECT "+String.join(",",q.columns().stream().map(name->column(fields.get(name).tableAlias(),fields.get(name).column(),quote)+" AS "+quoted(name,quote)).toList())+" FROM "+table(d.tables().getFirst(),type,quote); + for(var j:d.joins())sql+=" LEFT JOIN "+table(d.tables().stream().filter(t->t.alias().equals(j.rightTable())).findFirst().orElseThrow(),type,quote)+" ON "+column(j.leftTable(),j.leftField(),quote)+"="+column(j.rightTable(),j.rightField(),quote); + List values=new ArrayList<>(),conditions=new ArrayList<>(); + for(var f:q.filters()){ + if(f==null||!fields.containsKey(f.field())||f.values()==null||f.values().size()>100||f.values().stream().anyMatch(v->v==null||v.length()>1000))throw invalid("过滤字段或值无效"); + var field=fields.get(f.field());String col=column(field.tableAlias(),field.column(),quote); + String op=Objects.toString(f.operator(),""); + if(Set.of("IS_NULL","IS_NOT_NULL").contains(op)){if(!f.values().isEmpty())throw invalid("空值过滤不接受值");conditions.add(col+(op.equals("IS_NULL")?" IS NULL":" IS NOT NULL"));} + else if(Set.of("IN","NOT_IN").contains(op)){if(f.values().isEmpty())throw invalid("集合过滤不能为空");conditions.add(col+(op.equals("IN")?" IN (":" NOT IN (")+String.join(",",Collections.nCopies(f.values().size(),"?"))+")");values.addAll(f.values());} + else {String symbol=Map.of("EQ","=","NE","<>","GT",">","GTE",">=","LT","<","LTE","<=").get(op);if(symbol==null||f.values().size()!=1)throw invalid("过滤操作或参数数量无效");conditions.add(col+symbol+"?");values.addAll(f.values());} + } + if(!conditions.isEmpty())sql+=" WHERE "+String.join(" AND ",conditions); + return new Sql(sql,List.copyOf(values)); + } + private static String table(Table t,String type,String q){ + String namespace=Set.of("MYSQL","DORIS").contains(type)?t.catalog():t.schema(); + if(namespace==null)throw invalid("请选择数据库或Schema"); + return ("DORIS".equals(type)?quoted("internal",q)+".":"")+quoted(namespace,q)+"."+quoted(t.table(),q)+" "+quoted(t.alias(),q); + } + private static String column(String table,String name,String q){return quoted(table,q)+"."+quoted(name,q);} + private static String quoted(String value,String q){return q+id(value)+q;} + private static String id(String value){if(value==null||!value.matches("[A-Za-z_][A-Za-z0-9_]{0,127}"))throw invalid("表、字段或别名格式无效");return value;} + private static String proof(DataSourceAccessScope a,DataSourceView s,Query q){return hash(JSON.writeValueAsString(List.of(a.orgScopeId(),s.version(),s.secretRef(),q)));} + private static String hash(String s){try{return HexFormat.of().formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(s.getBytes(StandardCharsets.UTF_8)));}catch(Exception e){throw new IllegalStateException(e);}} + private static void same(DataSourceView a,DataSourceView b){if(a.version()!=b.version()||!Objects.equals(a.secretRef(),b.secretRef())||!Objects.equals(a.lastTestId(),b.lastTestId()))throw invalid("来源配置或凭据已变化");} + private T work(Callable action){Future f=null;try{f=workers.submit(action);return f.get(15,TimeUnit.SECONDS);}catch(InterruptedException e){Thread.currentThread().interrupt();throw invalid("直连读取已中断");}catch(ExecutionException e){if(e.getCause() instanceof DataSourceOperationException safe)throw safe;throw invalid("直连读取失败,请核对来源权限、结构及数据类型");}catch(TimeoutException|RejectedExecutionException e){throw invalid("直连读取超时或繁忙,请缩小范围后重试");}finally{if(f!=null&&!f.isDone())f.cancel(true);}} + private static DataSourceOperationException invalid(String message){return DataSourceOperationException.validation(message);} + @PreDestroy public void close(){workers.shutdownNow();} +} diff --git a/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingApi.java b/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingApi.java index fee17a9..0e6bc4e 100644 --- a/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingApi.java +++ b/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingApi.java @@ -10,7 +10,10 @@ public final class ReportingApi { } 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) { } + boolean attachments, boolean batchSupport, boolean receiptQuery, + String reporterCode,String interfaceCode) { + public TargetSystem(String endpoint,String environment,String transport,String authentication,int timeoutSeconds,int maxRetries,String defaultVersion,String fileNameRule,boolean attachments,boolean batchSupport,boolean receiptQuery){this(endpoint,environment,transport,authentication,timeoutSeconds,maxRetries,defaultVersion,fileNameRule,attachments,batchSupport,receiptQuery,null,null);} + } public record Topic(String responsibleDepartment, String period) { } /** A null credential reference retains the current binding; an empty one removes it. */ public record Command(long version, Kind kind, String code, String name, String parentId, String description, diff --git a/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingExecutionApi.java b/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingExecutionApi.java index 37d27b5..509fc14 100644 --- a/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingExecutionApi.java +++ b/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingExecutionApi.java @@ -14,11 +14,16 @@ public final class ReportingExecutionApi { 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 templates,List selections) { } + public record Envelope(String reporterCode,String interfaceCode,String version,String timestamp,String packageCode) { } + public record Frozen(ReportingPlanApi.View plan,ReportingStandardApi.Definition standard,List templates,List selections,Envelope envelope) { + public Frozen(ReportingPlanApi.View plan,ReportingStandardApi.Definition standard,List templates,List selections){this(plan,standard,templates,selections,null);} + } 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 issues,String snapshotId,String packageId,String message,String updatedAt) { } - public record SourceProof(String resource,ReportingDatasetDirectory.Read query,String authorizationSha256,String observedAt) { } + public record SourceProof(String resource,ReportingDatasetDirectory.Read query,String authorizationSha256,String observedAt,cn.aixunkeji.datagov.integration.datasource.ReportingSourceRead.Query directQuery) { + public SourceProof(String resource,ReportingDatasetDirectory.Read query,String authorizationSha256,String observedAt){this(resource,query,authorizationSha256,observedAt,null);} + } public record ResourceRows(String resource,List> rows,List> sourceKeys) { public ResourceRows(String resource,List> rows){this(resource,rows,List.of());} } diff --git a/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingExecutionService.java b/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingExecutionService.java index 253e8f6..5ec8be8 100644 --- a/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingExecutionService.java +++ b/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingExecutionService.java @@ -26,6 +26,8 @@ class ReportingExecutionService { private final org.springframework.transaction.support.TransactionTemplate transactions; @DubboReference(version=ReportingDatasetDirectory.VERSION,group=ReportingDatasetDirectory.GROUP,check=false,retries=0,timeout=30000) private ReportingDatasetDirectory datasets; + @org.springframework.beans.factory.annotation.Autowired + private cn.aixunkeji.datagov.integration.datasource.ReportingSourceService directSources; String qualityReference(long ruleId){return quality.resolveReference(actors.current("standard"),ruleId);} @@ -72,7 +74,9 @@ class ReportingExecutionService { 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); + var target=audit.required(a,plan.definition().systemId(),false).command().system(); + var envelope=ReportingPackage.envelope(target,id,LocalDateTime.now(java.time.ZoneId.of("Asia/Shanghai"))); + var captured=new Frozen(plan,standard.definition(),templates,task.definition().selections(),envelope);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); } @@ -86,24 +90,32 @@ class ReportingExecutionService { 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); + if(binding.directSource()!=null)plans.sourceFields(binding); var columns=new LinkedHashSet();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())); + List> sourceRows; + if(binding.directSource()!=null){ + var query=new cn.aixunkeji.datagov.integration.datasource.ReportingSourceRead.Query(binding.directSource(),List.copyOf(columns),List.copyOf(filters));var data=directSources.read(query,false); + if(data==null||!data.complete()||data.authorizationSha256()==null)throw conflict("直连数据未完整读取");sourceRows=data.rows(); + proofs.add(new SourceProof(resource.code(),null,data.authorizationSha256(),data.observedAt(),query)); + }else{ + var dataset=datasets.resolve(binding.datasetId());requireVersion(binding,dataset); + 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("数据未完整读取,不能生成快照");sourceRows=data.rows(); + proofs.add(new SourceProof(resource.code(),query,data.authorizationSha256(),data.observedAt())); + } + totalBytes+=json.writeValueAsBytes(sourceRows).length;if(totalBytes>8_000_000)throw invalid("批次数据总量超过8 MB,请缩小期间或过滤范围"); + var result=ReportingRows.map(resource,binding,selection,sourceRows,fixed.envelope()==null?null:fixed.envelope().reporterCode());rows.add(result.data());issues.addAll(result.issues());if(issues.size()>2000)throw invalid("校验问题超过2000项");count+=sourceRows.size(); } - for(var proof:proofs)datasets.authorize(proof.query(),proof.authorizationSha256());requireActive(a,before,fixed); + for(var proof:proofs)if(proof.directQuery()!=null)directSources.authorize(proof.directQuery(),proof.authorizationSha256());else 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():"数据读取、校验或文件保存未完成;请核对数据访问权限、范围和文件操作");} + }catch(RuntimeException e){failure(a,id,"READING",e instanceof ReportingException||e instanceof cn.aixunkeji.datagov.integration.datasource.DataSourceOperationException?e.getMessage():"数据读取、校验或文件保存未完成;请核对数据访问权限、范围和文件操作");} return batch(a,id); } @Transactional public Batch review(String id,Action action,boolean approve){ @@ -123,7 +135,7 @@ class ReportingExecutionService { 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()); + String artifact=files.write(a,id,"PACKAGE",fixed.envelope()==null?"reporting_"+id+".zip":ReportingPackage.fileName(fixed.envelope(),fixed.envelope().interfaceCode(),"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); @@ -184,7 +196,7 @@ class ReportingExecutionService { } 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 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 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));} + Precheck precheck(String id){var b=get(id);List 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("快照不属于当前固定批次");} @@ -212,9 +224,11 @@ class ReportingExecutionService { 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 b=plan.definition().bindings().stream().filter(v->v.resourceCode().equals(s.resourceCode())).findFirst().orElseThrow(); + List sourceFields; + if(b.directSource()!=null)sourceFields=plans.sourceFields(b);else {var dataset=datasets.resolve(b.datasetId());requireVersion(b,dataset);sourceFields=dataset.fields();} + var fields=sourceFields.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("附件引用字段必须是方案中已映射的目标字段"); } diff --git a/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingFiles.java b/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingFiles.java index 9377c98..b72b45f 100644 --- a/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingFiles.java +++ b/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingFiles.java @@ -23,6 +23,8 @@ class ReportingFiles { private PrivateBusinessFileOwner files; @DubboReference(version=ReportingDatasetDirectory.VERSION,group=ReportingDatasetDirectory.GROUP,check=false,retries=0,timeout=10000) private ReportingDatasetDirectory datasets; + @org.springframework.beans.factory.annotation.Autowired + private cn.aixunkeji.datagov.integration.datasource.ReportingSourceService directSources; record Stored(String id,String batchId,String kind,Target target,Binding binding,List 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 proofs){ if(bytes.length==0||bytes.length>10*1024*1024)throw ReportingException.invalid("批次文件为空或超过10 MiB;请缩小任务期间或过滤范围"); @@ -77,7 +79,7 @@ class ReportingFiles { 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()); + for(var proof:stored.proofs())authorizeProof(proof); } private byte[] readBytes(ReportingActor.Scope a,Stored s,boolean staged){ if(staged&&s.creator()!=a.user()||s.binding()==null)throw ReportingException.forbidden(); @@ -100,9 +102,13 @@ class ReportingFiles { 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()); + for(var proof:stored.proofs())authorizeProof(proof); 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 void authorizeProof(SourceProof proof){ + if(proof.directQuery()!=null){if(proof.query()!=null)throw ReportingException.forbidden();directSources.authorize(proof.directQuery(),proof.authorizationSha256());} + else {if(proof.query()==null)throw ReportingException.forbidden();datasets.authorize(proof.query(),proof.authorizationSha256());} + } 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);}} diff --git a/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingMapping.java b/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingMapping.java index 2dc6f96..3991244 100644 --- a/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingMapping.java +++ b/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingMapping.java @@ -10,7 +10,8 @@ import static cn.aixunkeji.datagov.integration.regulatoryreporting.ReportingPlan 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(!Set.of("DIRECT","CONSTANT","REPORTER_CODE","STABLE_GUID","DEFAULT","TRIM","UPPER","LOWER","DICTIONARY","DATE","DATETIME","DECIMAL","CONCAT").contains(Objects.toString(t.kind(),"")))throw ReportingException.invalid("不支持的转换类型"); + if("STABLE_GUID".equals(t.kind())&&(t.argument()==null||t.argument().isBlank()))throw ReportingException.invalid("稳定GUID须指定长期不变的业务命名空间"); 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("表达式来源字段无效"); @@ -21,12 +22,17 @@ final class ReportingMapping { }catch(Exception e){throw ReportingException.invalid("日期格式或小数位配置无效");} } static List sources(Mapping m){ - if(m.transform()!=null&&"CONSTANT".equals(m.transform().kind()))return List.of(); + if(m.transform()!=null&&Set.of("CONSTANT","REPORTER_CODE").contains(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 row){ + return apply(m,row,null); + } + static String apply(Mapping m,Map row,String reporterCode){ String v=row.get(m.source());var t=m.transform();if(t==null||"DIRECT".equals(t.kind()))return v; + if("REPORTER_CODE".equals(t.kind())){if(reporterCode==null||!reporterCode.matches("[0-9A-HJ-NPQRTUWXY]{18}"))throw ReportingException.invalid("上报系统尚未配置单位信用代码");return reporterCode;} + if("STABLE_GUID".equals(t.kind())){if(v==null||v.isBlank())throw ReportingException.invalid("稳定GUID的业务主键为空");return UUID.nameUUIDFromBytes(tools.jackson.databind.json.JsonMapper.builder().build().writeValueAsBytes(List.of(t.argument(),v))).toString();} 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())){ diff --git a/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingPackage.java b/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingPackage.java index dd105db..b86d9c9 100644 --- a/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingPackage.java +++ b/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingPackage.java @@ -14,6 +14,15 @@ import static cn.aixunkeji.datagov.integration.regulatoryreporting.ReportingExec /** Deterministic local format production; not a claim of target-system acceptance. */ final class ReportingPackage { + static Envelope envelope(ReportingApi.TargetSystem target,String batch,java.time.LocalDateTime time){ + if(target==null||Objects.toString(target.reporterCode(),"").isBlank()&&Objects.toString(target.interfaceCode(),"").isBlank())return null; + var envelope=new Envelope(target.reporterCode(),target.interfaceCode(),target.defaultVersion(),time.format(java.time.format.DateTimeFormatter.ofPattern("uuuuMMddHHmmss")),ReportingPolicy.id(batch).replace("-","")); + fileName(envelope,envelope.interfaceCode(),"zip");return envelope; + } + static String fileName(Envelope e,String code,String extension){ + if(e==null||e.reporterCode()==null||!e.reporterCode().matches("[0-9A-HJ-NPQRTUWXY]{18}")||e.interfaceCode()==null||!e.interfaceCode().matches("[A-Za-z][A-Za-z0-9]{0,31}")||e.version()==null||!e.version().matches("[A-Za-z0-9]{1,32}")||e.timestamp()==null||!e.timestamp().matches("[0-9]{14}")||e.packageCode()==null||!e.packageCode().matches("[a-f0-9]{32}")||code==null||!code.matches("[A-Za-z][A-Za-z0-9]{0,127}")||!Set.of("xml","zip").contains(extension))throw ReportingException.invalid("请配置完整上报单位、接口代号及接口报文版本;报文版本不可使用内部试验版本字符串"); + return String.join("_",e.reporterCode(),code,e.version(),e.timestamp(),e.packageCode())+"."+extension; + } static byte[] generate(Frozen frozen,Snapshot snapshot){ return generate(frozen,snapshot,Map.of()); } @@ -30,7 +39,7 @@ final class ReportingPackage { 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(); + var entry=new ZipEntry(frozen.envelope()==null?resource.code()+".xml":fileName(frozen.envelope(),resource.code(),"xml"));entry.setTime(0);zip.putNextEntry(entry);zip.write(xml);zip.closeEntry(); } long attachmentSize=0; for(String name:new TreeSet<>(expected.keySet())){ diff --git a/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingPlanApi.java b/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingPlanApi.java index 0f80d35..8be1b4e 100644 --- a/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingPlanApi.java +++ b/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingPlanApi.java @@ -10,7 +10,10 @@ public final class ReportingPlanApi { 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 mappings) { } + String schemaVersionId, String schemaSha256, List mappings, + cn.aixunkeji.datagov.integration.datasource.ReportingSourceRead.Fixed directSource) { + public Binding(String resourceCode,String datasetId,long datasetVersion,String releaseId,String schemaVersionId,String schemaSha256,List mappings){this(resourceCode,datasetId,datasetVersion,releaseId,schemaVersionId,schemaSha256,mappings,null);} + } public record Definition(String code, String name, String versionLabel, String regulatorId, String systemId, String topicId, String standardId, long standardVersion, String adapterProfile, String description, List bindings) { } @@ -22,5 +25,7 @@ public final class ReportingPlanApi { public record Suggestion(String target, List 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 suggestions) { } + public record DirectMatchRequest(String standardId,String resourceCode,cn.aixunkeji.datagov.integration.datasource.ReportingSourceRead.Definition source) { } + public record DirectMatchResult(cn.aixunkeji.datagov.integration.datasource.ReportingSourceRead.Fixed source,List suggestions) { } public record Sample(String resource,int row,java.util.Map source,java.util.Map target,List issues) { } } diff --git a/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingPlanController.java b/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingPlanController.java index 468b26f..084f0f0 100644 --- a/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingPlanController.java +++ b/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingPlanController.java @@ -36,6 +36,8 @@ class ReportingPlanController { @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 match(@RequestBody MatchRequest request){return R.ok(service.match(request));} + @PostMapping("/direct-match") @SaCheckPermission(ReportingActor.PREFIX+"edit") + public R matchDirect(@RequestBody DirectMatchRequest request){return R.ok(service.matchDirect(request));} @PostMapping("/sample") @SaCheckPermission(ReportingActor.PREFIX+"edit") public R> sample(@RequestBody Definition request){return R.ok(service.sample(request));} } diff --git a/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingPlanService.java b/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingPlanService.java index f8c465a..77fd540 100644 --- a/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingPlanService.java +++ b/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingPlanService.java @@ -20,6 +20,8 @@ class ReportingPlanService { private final ReportingStandardService standards; @DubboReference(version=ReportingDatasetDirectory.VERSION,group=ReportingDatasetDirectory.GROUP,check=false,timeout=10000,retries=0) private ReportingDatasetDirectory datasets; + @org.springframework.beans.factory.annotation.Autowired + private cn.aixunkeji.datagov.integration.datasource.ReportingSourceService directSources; ReportingDatasetDirectory.Page datasets(String keyword,int page,int size) { actors.current("view");ReportingService.paging(page,size); @@ -27,9 +29,11 @@ class ReportingPlanService { } ReportingApi.Page 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); + String where=" WHERE organization_id=?"; List args=new ArrayList<>();args.add(a.organization()); + if(!k.isBlank()){where+=" AND (INSTR(LOWER(plan_name),LOWER(?))>0 OR INSTR(LOWER(plan_code),LOWER(?))>0)";args.add(k);args.add(k);} + long total=jdbc.queryForObject("SELECT COUNT(*) FROM dg_reporting_plan"+where,Long.class,args.toArray()); + List pageArgs=new ArrayList<>(args);pageArgs.add(size);pageArgs.add((page-1)*size); + 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),pageArgs.toArray()); 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);} @@ -37,8 +41,10 @@ class ReportingPlanService { 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); + var bindings=new ArrayList<>(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)); + bindings.addAll(jdbc.query("SELECT binding_json FROM dg_reporting_plan_source WHERE organization_id=? AND plan_id=? ORDER BY resource_code",(b,i)->json.readValue(b.getString(1),Binding.class),a.organization(),id)); + bindings.sort(Comparator.comparing(Binding::resourceCode)); 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); } @@ -57,16 +63,15 @@ class ReportingPlanService { // 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()); - } + for(var b:d.bindings()) sourceFields(b); 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(?,?,?,?,?,?,?,?,?)", + jdbc.update("DELETE FROM dg_reporting_plan_source WHERE organization_id=? AND plan_id=?",a.organization(),id); + for(var b:d.bindings())if(b.directSource()!=null)jdbc.update("INSERT INTO dg_reporting_plan_source(organization_id,plan_id,resource_code,binding_json) VALUES(?,?,?,?)",a.organization(),id,b.resourceCode(),json.writeValueAsString(b)); + else 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); @@ -79,20 +84,19 @@ class ReportingPlanService { Set 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;} + if(binding==null){issues.add(new Issue(resource.code(),"BLOCKING","未绑定取数来源"));continue;} + List fields; + try{fields=sourceFields(binding);}catch(RuntimeException e){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","转换未确认或来源字段无效")); + if(!mapping.confirmed()||!fields.stream().map(ReportingDatasetDirectory.Field::name).toList().containsAll(ReportingMapping.sources(mapping))||ReportingMapping.sources(mapping).isEmpty()&&!Set.of("CONSTANT","REPORTER_CODE").contains(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); + var source=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","源类型、长度、精度或空值与目标不兼容,需要配置转换规则")); + else if(binding.directSource()==null&&!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","映射包含标准以外的字段")); @@ -131,23 +135,36 @@ class ReportingPlanService { var dataset=datasets.resolve(r.datasetId()); return new MatchResult(dataset,suggest(resource.fields(),dataset.fields())); } + DirectMatchResult matchDirect(DirectMatchRequest 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(); + if(!"PUBLISHED".equals(standard.status()))throw conflict("请选择已发布标准"); + var resource=standard.definition().resources().stream().filter(v->v.code().equals(r.resourceCode())).findFirst().orElseThrow(()->invalid("资源不属于标准")); + var source=directSources.describe(r.source());return new DirectMatchResult(source,suggest(resource.fields(),source.fields())); + } + List sourceFields(Binding b){ + if(b.directSource()!=null){directSources.require(b.directSource());return b.directSource().fields();} + var dataset=datasets.resolve(b.datasetId());if(!sameVersion(b,dataset))throw conflict("数据集版本已变化,请重新绑定");return dataset.fields(); + } List 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 samples=new ArrayList<>(); for(var b:d.bindings()){ - var dataset=datasets.resolve(b.datasetId());if(!sameVersion(b,dataset))throw conflict("数据集版本已变化"); + var fields=sourceFields(b); var resource=standard.definition().resources().stream().filter(r->r.code().equals(b.resourceCode())).findFirst().orElseThrow(()->invalid("资源不属于标准")); - var columns=new LinkedHashSet();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 columns=new LinkedHashSet();b.mappings().forEach(m->columns.addAll(ReportingMapping.sources(m)));if(columns.isEmpty())columns.add(fields.getFirst().name()); + List> sampleRows; + if(b.directSource()!=null)sampleRows=directSources.read(new cn.aixunkeji.datagov.integration.datasource.ReportingSourceRead.Query(b.directSource(),List.copyOf(columns),List.of()),true).rows(); + else {var preview=datasets.preview(new ReportingDatasetDirectory.Read(datasets.resolve(b.datasetId()),List.copyOf(columns),List.of())); + if(preview==null||preview.complete()||preview.rows().size()>5)throw conflict("样例响应无效,不能作为快照使用");sampleRows=preview.rows();} + int row=0;for(var values:sampleRows){ var target=new LinkedHashMap();List 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","转换失败或字典未命中"));} + else try{value=ReportingMapping.apply(mapping,values,configs.required(a,d.systemId(),false).command().system().reporterCode());}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))); @@ -186,7 +203,14 @@ class ReportingPlanService { if(!Set.of("SASAC_SCIENCE_B","SASAC_TREASURY_B").contains(Objects.toString(d.adapterProfile(),"")))throw invalid("请选择独立的报送适配配置"); Set 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("资源或数据集版本引用无效"); + if(b==null||b.resourceCode()==null||!b.resourceCode().matches("[A-Za-z_][A-Za-z0-9_.-]{0,127}")||!resources.add(b.resourceCode())||b.mappings()==null||b.mappings().size()>500)throw invalid("资源引用无效"); + if(b.directSource()==null){ + if(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}"))throw invalid("数据集版本引用无效"); + }else{ + if(b.datasetId()!=null||b.releaseId()!=null||b.schemaVersionId()!=null||b.schemaSha256()!=null||b.datasetVersion()!=0)throw invalid("直连来源不能冒用数据集版本"); + cn.aixunkeji.datagov.integration.datasource.ReportingSourceService.validate(b.directSource().definition()); + if(b.directSource().sourceVersion()<0||b.directSource().schemaSha256()==null||!b.directSource().schemaSha256().matches("[a-f0-9]{64}")||b.directSource().fields()==null||b.directSource().fields().size()>200)throw invalid("直连来源缺少已核对的结构版本"); + } Set 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); diff --git a/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingPolicy.java b/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingPolicy.java index 3b51c41..780cd95 100644 --- a/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingPolicy.java +++ b/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingPolicy.java @@ -52,7 +52,10 @@ final class ReportingPolicy { } catch (IllegalArgumentException e) { throw invalid("接收端须为 HTTP(S) 地址,不能包含用户名、密码、查询参数或片段"); } } system = new TargetSystem(endpoint, s.environment(), s.transport(), s.authentication(), s.timeoutSeconds(), s.maxRetries(), - text(s.defaultVersion(), 64, false, "默认版本"), text(s.fileNameRule(), 200, false, "命名规则"), s.attachments(), s.batchSupport(), s.receiptQuery()); + text(s.defaultVersion(), 64, false, "接口报文版本"), text(s.fileNameRule(), 200, false, "命名规则"), s.attachments(), s.batchSupport(), s.receiptQuery(), + text(s.reporterCode(),18,false,"上报单位信用代码"),text(s.interfaceCode(),32,false,"接口代号")); + if(!system.reporterCode().isEmpty()&&!system.reporterCode().matches("[0-9A-HJ-NPQRTUWXY]{18}"))throw invalid("上报单位信用代码格式无效"); + if(!system.interfaceCode().isEmpty()&&!system.interfaceCode().matches("[A-Za-z][A-Za-z0-9]{0,31}"))throw invalid("接口代号格式无效"); } else { if (c.topic() == null || c.department() != null || c.system() != null) throw invalid("主题配置无效"); var t = c.topic(); diff --git a/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingRows.java b/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingRows.java index ff6d7ac..3899a2b 100644 --- a/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingRows.java +++ b/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingRows.java @@ -9,7 +9,10 @@ final class ReportingRows { private static final tools.jackson.databind.json.JsonMapper JSON=tools.jackson.databind.json.JsonMapper.builder().build(); record Result(ResourceRows data,List issues) { } static Result map(ReportingStandardApi.Resource resource,ReportingPlanApi.Binding binding,Selection selection,List> rows){ - List issues=new ArrayList<>();List> mapped=new ArrayList<>(),sourceKeys=new ArrayList<>();Set keys=new HashSet<>();int index=0; + return map(resource,binding,selection,rows,null); + } + static Result map(ReportingStandardApi.Resource resource,ReportingPlanApi.Binding binding,Selection selection,List> rows,String reporterCode){ + List issues=new ArrayList<>();List> mapped=new ArrayList<>(),sourceKeys=new ArrayList<>();Map keys=new HashMap<>();Set duplicateKeys=new HashSet<>();int index=0; for(var source:rows){ index++;String key=selection.keyFields().stream().map(f->Objects.toString(source.get(f),"")).reduce((a,b)->a+" | "+b).orElse(""); // Error locations retain a stable key fingerprint, never leak masked values in logs/list pages. @@ -18,12 +21,13 @@ final class ReportingRows { var keyParts=selection.keyFields().stream().map(source::get).toList(); Map 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","业务主键重复"); + Integer first=keys.putIfAbsent(distinctKey,index); + if(first!=null){if(duplicateKeys.add(distinctKey))add(issues,resource.code(),first,keyRef,"","KEY_UNIQUE","业务主键重复");add(issues,resource.code(),index,keyRef,"","KEY_UNIQUE","业务主键重复");} Map 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);} + try{value=ReportingMapping.apply(mapping,source,reporterCode);} catch(RuntimeException e){add(issues,resource.code(),index,keyRef,f.name(),"TRANSFORM","转换失败或字典未命中;请核对来源及转换配置");} target.put(f.name(),value); String error=validate(f,value); @@ -31,13 +35,14 @@ final class ReportingRows { } mapped.add(Collections.unmodifiableMap(target)); } + ReportingSnapshotRules.apply(resource,mapped,issues); 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 "字段长度超出标准"; + if(f.maxLength()!=null&&v.codePointCount(0,v.length())>f.maxLength())return "字段长度超出标准:实际"+v.codePointCount(0,v.length())+"字,上限"+f.maxLength()+"字;请整改源数据,不自动截断"; try{ switch(f.type()){ case "INTEGER"->{if(!v.matches("-?\\d+"))throw new IllegalArgumentException();new BigInteger(v);} @@ -55,7 +60,7 @@ final class ReportingRows { static void rules(ReportingStandardApi.Definition standard,List 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()) + if(d.validationRule()!=null&&!d.validationRule().isBlank()&&ReportingQuality.reference(d.validationRule())==null&&!ReportingSnapshotRules.executable(d.validationRule())||d.fillingRule()!=null&&!d.fillingRule().isBlank()&&!ReportingSnapshotRules.executable(d.fillingRule())||d.dictionary()!=null&&!d.dictionary().isBlank()&&!ReportingSnapshotRules.executable(d.dictionary())) add(issues,r.code(),0,"",f.name(),"UNBOUND_BUSINESS_RULE","存在说明型规则或外部字典,尚未绑定可执行版本,不能按校验通过处理"); } } diff --git a/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingSnapshotRules.java b/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingSnapshotRules.java new file mode 100644 index 0000000..5a7ca51 --- /dev/null +++ b/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingSnapshotRules.java @@ -0,0 +1,54 @@ +package cn.aixunkeji.datagov.integration.regulatoryreporting; + +import java.util.*; +import java.time.LocalDate; +import tools.jackson.databind.json.JsonMapper; +import static cn.aixunkeji.datagov.integration.regulatoryreporting.ReportingExecutionApi.*; + +/** Explicit, closed rules on the frozen candidate values. Never executes natural-language text. */ +final class ReportingSnapshotRules { + record Rule(String kind,String field,List values) { } + private static final String PREFIX="REPORTING:"; + static List parse(String value){ + if(value==null||!value.startsWith(PREFIX))return null; + try{ + var rules=Arrays.asList(JsonMapper.builder().build().readValue(value.substring(PREFIX.length()),Rule[].class)); + if(rules.isEmpty()||rules.size()>10)throw new IllegalArgumentException(); + for(var r:rules){ + if(r==null||!Set.of("UNIQUE","DATE_GTE","REQUIRED_IF","CREDIT_CODE","UUID").contains(Objects.toString(r.kind(),"")))throw new IllegalArgumentException(); + if(Set.of("DATE_GTE","REQUIRED_IF").contains(r.kind())&&(r.field()==null||!r.field().matches("[A-Za-z_][A-Za-z0-9_.-]{0,127}")))throw new IllegalArgumentException(); + if("REQUIRED_IF".equals(r.kind())&&(r.values()==null||r.values().isEmpty()||r.values().size()>100||r.values().stream().anyMatch(v->v==null||v.isBlank()||v.length()>100)))throw new IllegalArgumentException(); + } + return rules; + }catch(RuntimeException e){throw ReportingException.invalid("报送快照规则格式无效,请重新配置");} + } + static void apply(ReportingStandardApi.Resource resource,List> rows,List issues){ + var names=resource.fields().stream().map(ReportingStandardApi.Field::name).toList(); + for(var field:resource.fields())if(field.details()!=null){ + var details=field.details(); + for(String value:List.of(Objects.toString(details.validationRule(),""),Objects.toString(details.fillingRule(),""),Objects.toString(details.dictionary(),""))){ + List rules; + try{rules=parse(value);}catch(ReportingException e){add(issues,resource.code(),0,field.name(),"RULE_CONFIGURATION",e.getMessage());continue;} + if(rules==null)continue; + for(var rule:rules){ + if(Set.of("DATE_GTE","REQUIRED_IF").contains(rule.kind())&&!names.contains(rule.field())){add(issues,resource.code(),0,field.name(),"RULE_CONFIGURATION","规则引用字段不属于当前资源:"+rule.field());continue;} + Map> groups=new HashMap<>(); + for(int i=0;inew ArrayList<>()).add(i+1);continue;} + if("REQUIRED_IF".equals(rule.kind())){if(rule.values().contains(Objects.toString(other,""))&&(current==null||current.isBlank()))error="条件必填:"+rule.field()+"命中已配置值,本字段不能为空";} + else if(current!=null&&!current.isBlank()){ + if("CREDIT_CODE".equals(rule.kind())&&!current.matches("[0-9A-HJ-NPQRTUWXY]{18}"))error="统一社会信用代码须为18位允许字符"; + if("UUID".equals(rule.kind()))try{if(current.length()!=36||!UUID.fromString(current).toString().equalsIgnoreCase(current))throw new IllegalArgumentException();}catch(RuntimeException e){error="须为36位规范GUID;同一业务记录修改时保持稳定";} + if("DATE_GTE".equals(rule.kind()))try{if(other==null||LocalDate.parse(current).isBefore(LocalDate.parse(other)))error="日期不得早于"+rule.field();}catch(RuntimeException e){error="日期比较字段缺失或格式无效:"+rule.field();} + } + if(error!=null)add(issues,resource.code(),i+1,field.name(),rule.kind(),error); + } + for(var group:groups.values())if(group.size()>1)for(int row:group)add(issues,resource.code(),row,field.name(),"UNIQUE","本批次业务编码重复,共"+group.size()+"条;不得重复新增"); + } + } + } + } + static boolean executable(String text){try{return parse(text)!=null;}catch(ReportingException e){return false;}} + private static void add(List issues,String resource,int row,String field,String rule,String message){if(issues.size()>=2000)throw ReportingException.invalid("校验问题超过2000项,请整改后重建批次");issues.add(new Issue(resource,row,"",field,rule,"BLOCKING",message));} +} diff --git a/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingStandardController.java b/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingStandardController.java index 7d09082..307e4fd 100644 --- a/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingStandardController.java +++ b/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingStandardController.java @@ -13,8 +13,8 @@ import static cn.aixunkeji.datagov.integration.regulatoryreporting.ReportingStan class ReportingStandardController { private final ReportingStandardService service; @GetMapping("/standards") @SaCheckPermission(ReportingActor.PREFIX + "view") - public R> list(@RequestParam(defaultValue = "") String keyword, @RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "20") int pageSize) { - return R.ok(service.list(keyword, pageNum, pageSize)); + public R> list(@RequestParam(defaultValue = "") String keyword, @RequestParam(required = false) String status, @RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "20") int pageSize) { + return R.ok(service.list(keyword, status, pageNum, pageSize)); } @GetMapping("/standards/{id}") @SaCheckPermission(ReportingActor.PREFIX + "view") public R get(@PathVariable String id) { return R.ok(service.get(id)); } diff --git a/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingStandardService.java b/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingStandardService.java index 4cbe9b3..0351bd9 100644 --- a/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingStandardService.java +++ b/aixun-modules/aixun-integration/src/main/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingStandardService.java @@ -18,12 +18,24 @@ class ReportingStandardService { record Stored(String id, long version, String status, Definition definition, String commandHash, String confirmation, String updatedAt) { } ReportingApi.Page list(String keyword, int page, int size) { + return list(keyword, null, page, size); + } + ReportingApi.Page list(String keyword, String status, int page, int size) { var a = actors.current("view"); ReportingService.paging(page, size); String key = ReportingPolicy.text(keyword, 100, false, "关键词"); - String where = " WHERE organization_id=? AND (INSTR(LOWER(standard_name),LOWER(?))>0 OR INSTR(LOWER(standard_code),LOWER(?))>0)"; - long total = jdbc.queryForObject("SELECT COUNT(*) FROM dg_reporting_standard" + where, Long.class, a.organization(), key, key); + String state = ReportingPolicy.text(status, 20, false, "标准状态"); + if (!state.isEmpty() && !Set.of("DRAFT", "PUBLISHED", "DISABLED").contains(state)) throw invalid("标准状态无效"); + String where = " WHERE organization_id=?"; + List args = new ArrayList<>(); args.add(a.organization()); + if (!key.isBlank()) { + where += " AND (INSTR(LOWER(standard_name),LOWER(?))>0 OR INSTR(LOWER(standard_code),LOWER(?))>0)"; + args.add(key); args.add(key); + } + if (!state.isEmpty()) { where += " AND standard_status=?"; args.add(state); } + long total = jdbc.queryForObject("SELECT COUNT(*) FROM dg_reporting_standard" + where, Long.class, args.toArray()); + List pageArgs = new ArrayList<>(args); pageArgs.add(size); pageArgs.add((page - 1) * size); var rows = jdbc.query("SELECT standard_id FROM dg_reporting_standard" + where + " ORDER BY update_time DESC,standard_id LIMIT ? OFFSET ?", - (r, n) -> r.getString(1), a.organization(), key, key, size, (page - 1) * size); + (r, n) -> r.getString(1), pageArgs.toArray()); return new ReportingApi.Page<>(rows.stream().map(id -> view(a, read(a, id, false))).toList(), total); } View get(String id) { var a = actors.current("view"); return view(a, read(a, ReportingPolicy.id(id), false)); } @@ -175,6 +187,9 @@ class ReportingStandardService { ReportingPolicy.text(d.description(), 4000, false, "字段描述"); ReportingPolicy.text(d.fillingRule(), 4000, false, "填写规则"); ReportingPolicy.text(d.validationRule(), 4000, false, "校验规则"); + ReportingSnapshotRules.parse(d.validationRule()); + ReportingSnapshotRules.parse(d.fillingRule()); + ReportingSnapshotRules.parse(d.dictionary()); ReportingPolicy.text(d.dictionary(), 500, false, "字典引用"); ReportingPolicy.text(d.defaultValue(), 2000, false, "默认值"); if (f.required() && Boolean.TRUE.equals(d.nullable())) throw invalid("必填字段不能声明允许空值:" + f.name()); diff --git a/aixun-modules/aixun-integration/src/test/java/cn/aixunkeji/datagov/integration/datasource/ReportingSourceServiceTest.java b/aixun-modules/aixun-integration/src/test/java/cn/aixunkeji/datagov/integration/datasource/ReportingSourceServiceTest.java new file mode 100644 index 0000000..9730ffe --- /dev/null +++ b/aixun-modules/aixun-integration/src/test/java/cn/aixunkeji/datagov/integration/datasource/ReportingSourceServiceTest.java @@ -0,0 +1,49 @@ +package cn.aixunkeji.datagov.integration.datasource; + +import java.util.*; +import java.sql.*; +import java.io.StringReader; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; +import static cn.aixunkeji.datagov.integration.datasource.ReportingSourceRead.*; +import cn.aixunkeji.datagov.dataproduct.api.reporting.ReportingDatasetDirectory.Filter; + +class ReportingSourceServiceTest { + Definition definition(){return new Definition(7,List.of(new Table("a","business",null,"scenes"),new Table("b","business",null,"enterprise")),List.of(new Join("a","enterprise_id","b","id")),List.of(new Field("code","a","biz_code"),new Field("credit","b","credit_code")));} + Fixed fixed(){return new Fixed(definition(),3,"a".repeat(64),List.of());} + @Test void boundParametersAndLeftJoinNeverRewriteOrDropMissingEnterprise(){ + var q=new Query(fixed(),List.of("code","credit"),List.of(new Filter("code","IN",List.of("AIYY20260009","' OR 1=1 --")))); + var sql=ReportingSourceService.compile(q,"MYSQL","`"); + assertTrue(sql.sql().contains("LEFT JOIN `business`.`enterprise` `b` ON `a`.`enterprise_id`=`b`.`id`")); + assertTrue(sql.sql().endsWith("WHERE `a`.`biz_code` IN (?,?)")); + assertFalse(sql.sql().contains("AIYY"));assertFalse(sql.sql().contains("1=1")); + assertEquals(q.filters().getFirst().values(),sql.arguments()); + } + @Test void invalidIdentifiersCyclesFieldsAndFilterArityAreRejected(){ + assertThrows(DataSourceOperationException.class,()->ReportingSourceService.validate(new Definition(7,List.of(new Table("t","db",null,"x;DELETE")),List.of(),List.of(new Field("id","t","id"))))); + assertThrows(DataSourceOperationException.class,()->ReportingSourceService.validate(new Definition(7,definition().tables(),List.of(new Join("b","id","a","id")),definition().fields()))); + assertThrows(DataSourceOperationException.class,()->ReportingSourceService.compile(new Query(fixed(),List.of("private_password"),List.of()),"MYSQL","`")); + assertThrows(DataSourceOperationException.class,()->ReportingSourceService.compile(new Query(fixed(),List.of("code"),List.of(new Filter("code","EQ",List.of()))),"MYSQL","`")); + assertThrows(DataSourceOperationException.class,()->ReportingSourceService.compile(new Query(fixed(),List.of("code"),List.of(new Filter("code","IS_NULL",List.of("x")))),"MYSQL","`")); + } + @Test void completeTextIsNotPreviewTruncatedAndHugeCellsFail()throws Exception{ + var r=mock(ResultSet.class);var md=mock(ResultSetMetaData.class);when(r.getMetaData()).thenReturn(md);when(md.getColumnType(1)).thenReturn(Types.LONGVARCHAR); + when(r.getCharacterStream(1)).thenReturn(new StringReader("成".repeat(262))); + assertEquals(262,ReportingSourceService.readCell(r,1).length()); + when(r.getCharacterStream(1)).thenReturn(new StringReader("x".repeat(1_000_001))); + assertThrows(DataSourceOperationException.class,()->ReportingSourceService.readCell(r,1)); + } + @Test void associationRequiresSingleColumnUniqueIndex()throws Exception{ + var md=mock(DatabaseMetaData.class);var rs=mock(ResultSet.class); + when(md.getIndexInfo("business",null,"enterprise",true,false)).thenReturn(rs); + when(rs.next()).thenReturn(true,false);when(rs.getString("TABLE_NAME")).thenReturn("enterprise");when(rs.getString("INDEX_NAME")).thenReturn("pk");when(rs.getString("COLUMN_NAME")).thenReturn("id"); + assertDoesNotThrow(()->ReportingSourceService.requireUniqueJoin(md,"MYSQL",definition().tables().get(1),"id")); + when(rs.next()).thenReturn(false);assertThrows(DataSourceOperationException.class,()->ReportingSourceService.requireUniqueJoin(md,"MYSQL",definition().tables().get(1),"id")); + } + @Test void unauthenticatedAccessCannotReachSourceConnection(){ + var registry=mock(cn.aixunkeji.datagov.integration.m2.DataSourceRegistry.class);var credentials=mock(DataSourceObjectConnection.class);var connections=mock(DataSourceBiQueryConnection.class); + var service=new ReportingSourceService(registry,credentials,connections); + try{assertThrows(RuntimeException.class,()->service.describe(definition()));verifyNoInteractions(registry,credentials,connections);}finally{service.close();} + } +} diff --git a/aixun-modules/aixun-integration/src/test/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingDamengListTest.java b/aixun-modules/aixun-integration/src/test/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingDamengListTest.java new file mode 100644 index 0000000..7f0e6cb --- /dev/null +++ b/aixun-modules/aixun-integration/src/test/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingDamengListTest.java @@ -0,0 +1,59 @@ +package cn.aixunkeji.datagov.integration.regulatoryreporting; + +import java.util.*; +import java.sql.*; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.RowMapper; +import org.springframework.jdbc.datasource.SingleConnectionDataSource; +import tools.jackson.databind.json.JsonMapper; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +/** Real Dameng, read-only inline fixtures: no DDL, DML or platform migration. */ +@EnabledIfEnvironmentVariable(named="DATAGOV_DM_CONFIG",matches=".+") +class ReportingDamengListTest { + @Test void actualServiceFiltersExecuteOnDamengWithoutChangingBusinessData() throws Exception { + Class.forName("dm.jdbc.driver.DmDriver"); + var settings=new Properties();settings.setProperty("user",System.getenv("DATAGOV_DM_USERNAME"));settings.setProperty("password",System.getenv("DATAGOV_DM_PASSWORD")); + settings.setProperty("connectTimeout","5000");settings.setProperty("socketTimeout","15000"); + try(var connection=DriverManager.getConnection("jdbc:dm://"+System.getenv("DATAGOV_DM_HOST")+":"+System.getenv("DATAGOV_DM_PORT"),settings)){ + connection.setReadOnly(true); + assertTrue(connection.getMetaData().getDatabaseProductName().toLowerCase(Locale.ROOT).contains("dm")); + JdbcTemplate actual=new JdbcTemplate(new SingleConnectionDataSource(connection,true)); + JdbcTemplate fixtures=new JdbcTemplate(){ + String prefix(String sql){ + boolean std=sql.contains("dg_reporting_standard");String table=std?"dg_reporting_standard":"dg_reporting_plan", name=std?"standard":"plan"; + StringBuilder data=new StringBuilder("WITH "+table+" (organization_id,"+name+"_id,"+name+"_code,"+name+"_name,standard_status,update_time) AS ("); + for(int i=1;i<=105;i++){if(i>1)data.append(" UNION ALL ");data.append("SELECT 9,'").append(String.format("%03d",i)).append("','KCSZ_").append(i).append("','标准名称','PUBLISHED',TIMESTAMP '2026-12-01 00:00:00' FROM DUAL");} + data.append(" UNION ALL SELECT 9,'106','DRAFT','草稿','DRAFT',TIMESTAMP '2026-12-01 00:00:00' FROM DUAL") + .append(" UNION ALL SELECT 99,'107','KCSZ_OTHER','跨组织','PUBLISHED',TIMESTAMP '2026-12-01 00:00:00' FROM DUAL") + .append(" UNION ALL SELECT 9,'108','PCT%','百分号','DISABLED',TIMESTAMP '2026-12-01 00:00:00' FROM DUAL)"); + return data+sql; + } + @Override public T queryForObject(String sql,Class type,Object... args){return actual.queryForObject(prefix(sql),type,args);} + @Override public List query(String sql,RowMapper mapper,Object... args){return actual.query(prefix(sql),mapper,args);} + }; + var actor=new ReportingActor.Scope(7,9);var actors=mock(ReportingActor.class);when(actors.current("view")).thenReturn(actor); + var json=JsonMapper.builder().build();var audit=mock(ReportingRepository.class); + var standards=spy(new ReportingStandardService(fixtures,json,actors,audit)); + doAnswer(i->new ReportingStandardService.Stored(i.getArgument(1),0,"PUBLISHED",new ReportingStandardApi.Definition("S","标准","1000","","",List.of()),"","","now")) + .when(standards).read(eq(actor),anyString(),eq(false)); + var plans=spy(new ReportingPlanService(fixtures,json,actors,audit,standards)); + doAnswer(i->new ReportingPlanApi.View(i.getArgument(1),0,"DRAFT",null,"now")).when(plans).read(eq(actor),anyString(),eq(false)); + for(String key:new String[]{null,""," ","\u3000"}){ + assertEquals(107,standards.list(key,1,100).total());assertEquals(100,standards.list(key,1,100).rows().size()); + assertEquals(107,plans.list(key,1,100).total());assertEquals(7,plans.list(key,2,100).rows().size()); + } + assertEquals(105,standards.list("","PUBLISHED",3,50).total()); + assertEquals(List.of("101","102","103","104","105"),standards.list("","PUBLISHED",3,50).rows().stream().map(ReportingStandardApi.View::id).toList()); + for(String key:List.of("'","absent")){assertEquals(0,standards.list(key,1,20).total());assertEquals(0,plans.list(key,1,20).total());} + assertEquals(1,standards.list("%",1,20).total());assertEquals(105,standards.list("_",1,20).total()); + assertEquals(105,plans.list("标准名称",1,20).total());assertEquals(0,plans.list("KCSZ_OTHER",1,20).total()); + assertEquals(0,standards.list("","PUBLISHED",4,50).rows().size()); + // Reproduce the previous empty-key predicate, including DM's empty-string/null behavior. + assertEquals(0,actual.queryForObject("SELECT COUNT(*) FROM DUAL WHERE INSTR('KCSZ',LOWER(?))>0",Integer.class,"")); + } finally {settings.clear();} + } +} diff --git a/aixun-modules/aixun-integration/src/test/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingListQueryTest.java b/aixun-modules/aixun-integration/src/test/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingListQueryTest.java new file mode 100644 index 0000000..5dfa5c7 --- /dev/null +++ b/aixun-modules/aixun-integration/src/test/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingListQueryTest.java @@ -0,0 +1,53 @@ +package cn.aixunkeji.datagov.integration.regulatoryreporting; + +import java.util.*; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.RowMapper; +import tools.jackson.databind.json.JsonMapper; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +class ReportingListQueryTest { + static class Capture extends JdbcTemplate { + String countSql, pageSql; Object[] countArgs, pageArgs; + @Override public T queryForObject(String sql, Class type, Object... args) { + countSql=sql; countArgs=args.clone(); return type.cast(0L); + } + @Override public List query(String sql, RowMapper mapper, Object... args) { + pageSql=sql; pageArgs=args.clone(); return List.of(); + } + } + final Capture jdbc=new Capture(); + final ReportingActor actors=mock(ReportingActor.class); + final ReportingRepository configs=mock(ReportingRepository.class); + final ReportingStandardService standards=new ReportingStandardService(jdbc,JsonMapper.builder().build(),actors,configs); + final ReportingPlanService plans=new ReportingPlanService(jdbc,JsonMapper.builder().build(),actors,configs,standards); + ReportingListQueryTest(){when(actors.current("view")).thenReturn(new ReportingActor.Scope(7,9));} + @Test void absentEmptyAndWhitespaceSkipSearchForBothLists(){ + for(String keyword:new String[]{null,""," ","\u3000"})for(boolean standard:new boolean[]{true,false}){ + if(standard)standards.list(keyword,2,20);else plans.list(keyword,2,20); + assertFalse(jdbc.countSql.contains("INSTR")); assertFalse(jdbc.pageSql.contains("INSTR")); + assertArrayEquals(new Object[]{9L},jdbc.countArgs); + assertArrayEquals(new Object[]{9L,20,20},jdbc.pageArgs); + assertEquals(jdbc.countSql.substring(jdbc.countSql.indexOf(" WHERE")),jdbc.pageSql.substring(jdbc.pageSql.indexOf(" WHERE"),jdbc.pageSql.indexOf(" ORDER BY"))); + } + } + @Test void specialCharactersRemainBoundLiteralSearchAndStatusFiltersCount(){ + for(String key:List.of("KCSZ_AI","'","%","_")){ + standards.list(key,"PUBLISHED",3,50); + assertTrue(jdbc.countSql.contains("INSTR"));assertFalse(jdbc.countSql.contains("LIKE")); + assertArrayEquals(new Object[]{9L,key,key,"PUBLISHED"},jdbc.countArgs); + assertArrayEquals(new Object[]{9L,key,key,"PUBLISHED",50,100},jdbc.pageArgs); + plans.list(key,1,20);assertArrayEquals(new Object[]{9L,key,key},jdbc.countArgs); + } + } + @Test void deniedScopeInvalidPagingAndStateFailBeforeSql(){ + assertThrows(ReportingException.class,()->standards.list("","UNKNOWN",1,20)); + assertThrows(ReportingException.class,()->plans.list("",0,20)); + when(actors.current("view")).thenThrow(ReportingException.forbidden()); + assertThrows(ReportingException.class,()->standards.list("",1,20)); + assertThrows(ReportingException.class,()->plans.list("",1,20)); + assertNull(jdbc.countSql); + } +} diff --git a/aixun-modules/aixun-integration/src/test/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingRowsTest.java b/aixun-modules/aixun-integration/src/test/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingRowsTest.java index 14b62af..db964a4 100644 --- a/aixun-modules/aixun-integration/src/test/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingRowsTest.java +++ b/aixun-modules/aixun-integration/src/test/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingRowsTest.java @@ -10,6 +10,6 @@ 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 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(3,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"));} } diff --git a/aixun-modules/aixun-integration/src/test/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingSnapshotRulesTest.java b/aixun-modules/aixun-integration/src/test/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingSnapshotRulesTest.java new file mode 100644 index 0000000..046e3eb --- /dev/null +++ b/aixun-modules/aixun-integration/src/test/java/cn/aixunkeji/datagov/integration/regulatoryreporting/ReportingSnapshotRulesTest.java @@ -0,0 +1,44 @@ +package cn.aixunkeji.datagov.integration.regulatoryreporting; + +import java.util.*; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; +import static cn.aixunkeji.datagov.integration.regulatoryreporting.ReportingStandardApi.*; +import static cn.aixunkeji.datagov.integration.regulatoryreporting.ReportingExecutionApi.*; + +class ReportingSnapshotRulesTest { + @Test void stableGuidAndReporterCodeAreExplicitAndDoNotUseStandardVersion(){ + var mapping=new ReportingPlanApi.Mapping("EXT_GUID","id",true,new ReportingPlanApi.Transform("STABLE_GUID","KCSZ:APATTACHEDRJ","",Map.of(),List.of())); + String first=ReportingMapping.apply(mapping,Map.of("id","AIYY20260009")); + assertEquals(36,first.length());assertEquals(first,ReportingMapping.apply(mapping,Map.of("id","AIYY20260009")));assertNotEquals(first,ReportingMapping.apply(mapping,Map.of("id","AIYY20260010"))); + var reporter=new ReportingPlanApi.Mapping("EXT_REPORTSOCIALCODE","",true,new ReportingPlanApi.Transform("REPORTER_CODE","","",Map.of(),List.of())); + assertThrows(ReportingException.class,()->ReportingMapping.apply(reporter,Map.of())); + assertEquals("91360000MA38QP624B",ReportingMapping.apply(reporter,Map.of(),"91360000MA38QP624B")); + } + @Test void wireVersionAndPackageIdentityRemainSeparateFromInternalStandardLabel(){ + var target=new ReportingApi.TargetSystem("","TEST","HTTP_POST","NONE",30,0,"1000","",false,false,false,"91360000MA38QP624B","KCSZ"); + var envelope=ReportingPackage.envelope(target,"ab942321-8e6d-446f-9fc3-1e4d53c6a656",java.time.LocalDateTime.of(2026,12,1,14,6,38)); + assertEquals("91360000MA38QP624B_KCSZ_1000_20261201140638_ab9423218e6d446f9fc31e4d53c6a656.zip",ReportingPackage.fileName(envelope,"KCSZ","zip")); + assertTrue(ReportingPackage.fileName(envelope,"APATTACHEDRJ","xml").contains("_APATTACHEDRJ_1000_")); + assertThrows(ReportingException.class,()->ReportingPackage.fileName(new Envelope(envelope.reporterCode(),"KCSZ","1000-test-20261201",envelope.timestamp(),envelope.packageCode()),"KCSZ","zip")); + } + Field field(String name,String rules){return new Field(name,"","STRING",false,255,null,null,new FieldDetails("",true,null,List.of(),"","",rules,"BLOCKING",null));} + @Test void everyDuplicateIsReportedAndDateConditionalRulesUseSnapshot(){ + var resource=new Resource("R","R",List.of(field("code","REPORTING:[{\"kind\":\"UNIQUE\"}]"),field("start",""),field("end","REPORTING:[{\"kind\":\"DATE_GTE\",\"field\":\"start\"}]"),field("kind",""),field("name","REPORTING:[{\"kind\":\"REQUIRED_IF\",\"field\":\"kind\",\"values\":[\"3\"]}]")),null); + var issues=new ArrayList();ReportingSnapshotRules.apply(resource,List.of(Map.of("code","same","start","2026-01-02","end","2026-01-01","kind","3","name",""),Map.of("code","same","start","2026-01-01","end","2026-01-02","kind","1","name","")),issues); + assertEquals(4,issues.size());assertEquals(Set.of(1,2),issues.stream().filter(i->i.rule().equals("UNIQUE")).map(Issue::row).collect(java.util.stream.Collectors.toSet())); + assertEquals(1,issues.stream().filter(i->i.rule().equals("REQUIRED_IF")).count()); + } + @Test void rulesCannotExecuteTextOrArbitraryOperators(){assertNull(ReportingSnapshotRules.parse("UNIQUE"));assertThrows(ReportingException.class,()->ReportingSnapshotRules.parse("REPORTING:[{\"kind\":\"SQL\"}]"));assertFalse(ReportingSnapshotRules.executable("REPORTING:invalid"));} + @Test void overlongRealCandidateIsPreservedWithExactCounts(){ + var f=field("ACHIEVED_EFFECT","");String value="成".repeat(262);var error=ReportingRows.validate(f,value); + assertTrue(error.contains("262"));assertTrue(error.contains("255"));assertEquals(262,value.length()); + } + @Test void tenSelectedRowsKeepNinePassingAndOneFailure(){ + var f=field("ACHIEVED_EFFECT","");var resource=new Resource("R","R",List.of(f),null); + var binding=new ReportingPlanApi.Binding("R","1",1,"2","3","a".repeat(64),List.of(new ReportingPlanApi.Mapping(f.name(),"effect",true))); + var rows=new ArrayList>();for(int i=0;i<10;i++)rows.add(Map.of("id",Integer.toString(i),"effect",i==9?"成".repeat(262):"合格")); + var result=ReportingRows.map(resource,binding,new Selection("R","",List.of("id"),List.of()),rows); + assertEquals(10,result.data().rows().size());assertEquals(1,result.issues().size());assertEquals(10,result.issues().getFirst().row());assertEquals(262,result.data().rows().getLast().get(f.name()).length()); + } +} diff --git a/aixun-ui/src/api/datagov/regulatory-reporting/index.ts b/aixun-ui/src/api/datagov/regulatory-reporting/index.ts index 7639aa1..5e92964 100644 --- a/aixun-ui/src/api/datagov/regulatory-reporting/index.ts +++ b/aixun-ui/src/api/datagov/regulatory-reporting/index.ts @@ -7,6 +7,7 @@ export interface TargetSystem { endpoint: string; environment: 'DEVELOPMENT' | 'TEST' | 'PRODUCTION'; transport: 'HTTP_POST'; authentication: 'NONE' | 'SECRET_REF'; timeoutSeconds: number; maxRetries: number; defaultVersion: string; fileNameRule: string; attachments: boolean; batchSupport: boolean; receiptQuery: boolean; + reporterCode?: string; interfaceCode?: string; } export interface Topic { responsibleDepartment: string; period: string } export interface ConfigCommand { diff --git a/aixun-ui/src/api/datagov/regulatory-reporting/plans.ts b/aixun-ui/src/api/datagov/regulatory-reporting/plans.ts index 944e008..e473625 100644 --- a/aixun-ui/src/api/datagov/regulatory-reporting/plans.ts +++ b/aixun-ui/src/api/datagov/regulatory-reporting/plans.ts @@ -5,7 +5,10 @@ export interface DatasetField { name: string; label: string; type: string; nulla export interface Dataset { id: string; code: string; name: string; version: number; releaseId: string; schemaVersionId: string; schemaSha256: string; fields: DatasetField[] } export interface Transform { kind: string; argument: string; outputFormat: string; values: Record; sources: string[] } export interface Mapping { target: string; source: string; confirmed: boolean; transform?: Transform } -export interface Binding { resourceCode: string; datasetId: string; datasetVersion: number; releaseId: string; schemaVersionId: string; schemaSha256: string; mappings: Mapping[] } +export interface DirectTable { alias: string; catalog: string | null; schema: string | null; table: string } +export interface DirectDefinition { sourceId: string; tables: DirectTable[]; joins: { leftTable: string; leftField: string; rightTable: string; rightField: string }[]; fields: { name: string; tableAlias: string; column: string }[] } +export interface DirectSource { definition: DirectDefinition; sourceVersion: number; schemaSha256: string; fields: DatasetField[] } +export interface Binding { resourceCode: string; datasetId: string | null; datasetVersion: number; releaseId: string | null; schemaVersionId: string | null; schemaSha256: string | null; mappings: Mapping[]; directSource?: DirectSource | null } export interface PlanDefinition { code: string; name: string; versionLabel: string; regulatorId: string; systemId: string; topicId: string; standardId: string; standardVersion: number; adapterProfile: string; description: string; bindings: Binding[] } export interface Plan { id: string; version: number; state: string; definition: PlanDefinition; updatedAt: string } export interface PlanCheck { configurationValid: boolean; executable: boolean; issues: { location: string; severity: string; message: string }[] } @@ -21,4 +24,5 @@ export const savePlan = (id: string, version: number, definition: PlanDefinition export const checkPlan = (definition: PlanDefinition): AxiosPromise => request({ url: `${base}/check`, method: 'post', data: definition }); export const listDatasets = (params: { keyword: string; pageNum: number; pageSize: number }): AxiosPromise> => request({ url: `${base}/datasets`, params }); export const matchFields = (standardId: string, resourceCode: string, datasetId: string): AxiosPromise<{ dataset: Dataset; suggestions: Suggestion[] }> => request({ url: `${base}/match`, method: 'post', data: { standardId, resourceCode, datasetId } }); +export const matchDirect = (standardId: string, resourceCode: string, source: DirectDefinition): AxiosPromise<{ source: DirectSource; suggestions: Suggestion[] }> => request({ url: `${base}/direct-match`, method: 'post', data: { standardId, resourceCode, source }, timeout: 60000 }); export const blankPlan = (): PlanDefinition => ({ code: '', name: '', versionLabel: '', regulatorId: '', systemId: '', topicId: '', standardId: '', standardVersion: 0, adapterProfile: 'SASAC_SCIENCE_B', description: '', bindings: [] }); diff --git a/aixun-ui/src/api/datagov/regulatory-reporting/standards.ts b/aixun-ui/src/api/datagov/regulatory-reporting/standards.ts index e56c517..2eb37bc 100644 --- a/aixun-ui/src/api/datagov/regulatory-reporting/standards.ts +++ b/aixun-ui/src/api/datagov/regulatory-reporting/standards.ts @@ -12,7 +12,7 @@ export interface TargetTemplate { id: string; sha256: string; recordElement: str export interface ImportIssue { file: string; location: string; severity: string; message: string } export interface ImportPreview { resources: StandardResource[]; issues: ImportIssue[]; fields: number; required: number; nullable: number; notes: { file: string; location: string; text: string; confirmationRequired: boolean }[] } const base = '/api/integration/v1/regulatory-reporting'; -export const listStandards = (params: { keyword: string; pageNum: number; pageSize: number }): AxiosPromise> => request({ url: `${base}/standards`, params }); +export const listStandards = (params: { keyword: string; status?: StandardView['status']; pageNum: number; pageSize: number }): AxiosPromise> => request({ url: `${base}/standards`, params }); export const getStandard = (id: string): AxiosPromise => request({ url: `${base}/standards/${id}` }); export const getStandardAudit = (id: string, pageNum: number, pageSize: number): AxiosPromise> => request({ url: `${base}/standards/${id}/audit`, params: { pageNum, pageSize } }); export const saveStandard = (id: string, version: number, definition: StandardDefinition): AxiosPromise => request({ url: `${base}/standards/${id}`, method: 'put', data: { version, definition }, headers: { repeatSubmit: false } }); diff --git a/aixun-ui/src/views/datagov/regulatory-reporting/ConfigPage.vue b/aixun-ui/src/views/datagov/regulatory-reporting/ConfigPage.vue index 636e5b3..eeafce7 100644 --- a/aixun-ui/src/views/datagov/regulatory-reporting/ConfigPage.vue +++ b/aixun-ui/src/views/datagov/regulatory-reporting/ConfigPage.vue @@ -57,7 +57,9 @@ - + + + 支持附件支持批量支持回执查询 diff --git a/aixun-ui/src/views/datagov/regulatory-reporting/overview/DirectSourcePicker.vue b/aixun-ui/src/views/datagov/regulatory-reporting/overview/DirectSourcePicker.vue new file mode 100644 index 0000000..59c671e --- /dev/null +++ b/aixun-ui/src/views/datagov/regulatory-reporting/overview/DirectSourcePicker.vue @@ -0,0 +1,65 @@ + + diff --git a/aixun-ui/src/views/datagov/regulatory-reporting/overview/ExecutionPanel.vue b/aixun-ui/src/views/datagov/regulatory-reporting/overview/ExecutionPanel.vue index 903287d..0badcd1 100644 --- a/aixun-ui/src/views/datagov/regulatory-reporting/overview/ExecutionPanel.vue +++ b/aixun-ui/src/views/datagov/regulatory-reporting/overview/ExecutionPanel.vue @@ -14,7 +14,7 @@

选择目标标准中保存附件引用的字段。每个非空值应为32位大写MD5_原文件名,可带unStruct/前缀;每个字段对应一个附件。

- + 添加过滤 @@ -26,9 +26,9 @@ -