修改问题

这个提交包含在:
apple
2026-12-01 15:34:17 +08:00
父节点 4d8c05e765
当前提交 32a3242a46
共修改 38 个文件,包含 892 行新增和 94 行删除
@@ -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) {
@@ -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) {
@@ -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,
@@ -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);
}
}
@@ -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<Table> tables,List<Join> joins,List<Field> fields) { }
public record Fixed(Definition definition,long sourceVersion,String schemaSha256,List<ReportingDatasetDirectory.Field> fields) { }
public record Query(Fixed source,List<String> columns,List<ReportingDatasetDirectory.Filter> filters) { }
public record Rows(List<Map<String,String>> rows,String authorizationSha256,String observedAt,boolean complete) { }
}
@@ -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<Map<String,String>> 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<sql.arguments().size();i++)statement.setString(i+1,sql.arguments().get(i));
try(var data=statement.executeQuery()){
if(data.getMetaData().getColumnCount()!=q.columns().size())throw invalid("取数结果结构变化");
while(data.next()){
if(rows.size()==limit){if(preview)break;throw invalid("完整取数超过100000条,请缩小过滤范围;未保存截断快照");}
var row=new LinkedHashMap<String,String>();
for(int i=0;i<q.columns().size();i++){
String value=readCell(data,i+1);
bytes+=value==null?4:value.getBytes(StandardCharsets.UTF_8).length;
if(bytes>8_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<String,Map<String,DataSourceObjects.Column>> 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<String,DataSourceObjects.Column> 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<ReportingDatasetDirectory.Field> 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<String,List<String>> 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<String,Map<String,DataSourceObjects.Column>> 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<String> 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<String> 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<String> 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<String,Field> 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<String> 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>T work(Callable<T> action){Future<T> 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();}
}
@@ -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,
@@ -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<ReportingStandardApi.Template> templates,List<Selection> selections) { }
public record Envelope(String reporterCode,String interfaceCode,String version,String timestamp,String packageCode) { }
public record Frozen(ReportingPlanApi.View plan,ReportingStandardApi.Definition standard,List<ReportingStandardApi.Template> templates,List<Selection> selections,Envelope envelope) {
public Frozen(ReportingPlanApi.View plan,ReportingStandardApi.Definition standard,List<ReportingStandardApi.Template> templates,List<Selection> 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<Issue> 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<Map<String,String>> rows,List<Map<String,String>> sourceKeys) {
public ResourceRows(String resource,List<Map<String,String>> rows){this(resource,rows,List.of());}
}
@@ -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<String>();binding.mappings().forEach(m->columns.addAll(ReportingMapping.sources(m)));columns.addAll(selection.keyFields());
var filters=new ArrayList<>(selection.filters());
if(!selection.periodField().isBlank()){filters.add(new ReportingDatasetDirectory.Filter(selection.periodField(),"GTE",List.of(before.startDate())));filters.add(new ReportingDatasetDirectory.Filter(selection.periodField(),"LT",List.of(before.endDate())));}
var query=new ReportingDatasetDirectory.Read(dataset,List.copyOf(columns),List.copyOf(filters));var data=datasets.read(query);
if(data==null||!data.complete()||!dataset.equals(data.dataset())||!query.columns().equals(data.columns())||data.authorizationSha256()==null||data.rows().size()>100000)throw conflict("数据未完整读取,不能生成快照");
totalBytes+=json.writeValueAsBytes(data.rows()).length;if(totalBytes>8_000_000)throw invalid("批次数据总量超过8 MB,请缩小期间或过滤范围");
var result=ReportingRows.map(resource,binding,selection,data.rows());rows.add(result.data());issues.addAll(result.issues());if(issues.size()>2000)throw invalid("校验问题超过2000项");count+=data.rows().size();
proofs.add(new SourceProof(resource.code(),query,data.authorizationSha256(),data.observedAt()));
List<Map<String,String>> 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<ReportingApi.Audit> history(String id,int page,int size){var a=actors.current("view");batch(a,id);ReportingService.paging(page,size);return audit.objectHistory(a,id,page,size);}
Precheck precheck(String id){var b=get(id);List<String> blockers=new ArrayList<>();if(!"FILE_READY".equals(b.state())||b.packageId()==null)blockers.add("未生成已审核批次的正式文件");blockers.add("缺少对应B接口版本的地址、认证、签名和回执契约,外部提交尚不可用");return new Precheck("FILE_READY".equals(b.state()),false,List.copyOf(blockers));}
Precheck precheck(String id){var b=get(id);List<String> blockers=new ArrayList<>();if(!"FILE_READY".equals(b.state())||b.packageId()==null)blockers.add("未生成已审核批次的正式文件");blockers.add("B接口提交尚未接入;需补齐接口规范原文、参数编码确认、受管调用凭据及测试接收配置。文件生成不代表已受理或已入库");return new Precheck("FILE_READY".equals(b.state()),false,List.copyOf(blockers));}
private void requireActive(ReportingActor.Scope a,Batch b,Frozen frozen){var task=task(a,b.taskId(),false);var plan=plans.read(a,frozen.plan().id(),false);if(!task.enabled()||plan==null||!"FROZEN".equals(plan.state())||plan.version()!=frozen.plan().version()||!plans.check(plan.definition()).configurationValid())throw conflict("任务、方案或引用已停用或变化");}
private String definitionHash(ReportingActor.Scope a,String id){return jdbc.queryForObject("SELECT frozen_sha256 FROM dg_reporting_batch WHERE organization_id=? AND batch_id=?",String.class,a.organization(),id);}
private void verifySnapshot(ReportingActor.Scope a,Batch b,Snapshot s){if(!b.id().equals(s.batchId())||!b.startDate().equals(s.startDate())||!b.endDate().equals(s.endDate())||!definitionHash(a,b.id()).equals(s.definitionSha256()))throw conflict("快照不属于当前固定批次");}
@@ -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<ReportingDatasetDirectory.Field> 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("附件引用字段必须是方案中已映射的目标字段");
}
@@ -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<SourceProof> proofs,String operation,String state,long creator,String createdAt) { }
String write(ReportingActor.Scope a,String batch,String kind,String name,String mime,byte[] bytes,List<SourceProof> proofs){
if(bytes.length==0||bytes.length>10*1024*1024)throw ReportingException.invalid("批次文件为空或超过10 MiB;请缩小任务期间或过滤范围");
@@ -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);}}
@@ -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<String> 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<String,String> row){
return apply(m,row,null);
}
static String apply(Mapping m,Map<String,String> 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())){
@@ -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())){
@@ -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<Mapping> mappings) { }
String schemaVersionId, String schemaSha256, List<Mapping> mappings,
cn.aixunkeji.datagov.integration.datasource.ReportingSourceRead.Fixed directSource) {
public Binding(String resourceCode,String datasetId,long datasetVersion,String releaseId,String schemaVersionId,String schemaSha256,List<Mapping> 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<Binding> bindings) { }
@@ -22,5 +25,7 @@ public final class ReportingPlanApi {
public record Suggestion(String target, List<String> candidates, String method, String confidence, boolean compatible, String reason) { }
public record MatchRequest(String standardId, String resourceCode, String datasetId) { }
public record MatchResult(ReportingDatasetDirectory.Dataset dataset, List<Suggestion> suggestions) { }
public record 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<Suggestion> suggestions) { }
public record Sample(String resource,int row,java.util.Map<String,String> source,java.util.Map<String,String> target,List<Issue> issues) { }
}
@@ -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<MatchResult> match(@RequestBody MatchRequest request){return R.ok(service.match(request));}
@PostMapping("/direct-match") @SaCheckPermission(ReportingActor.PREFIX+"edit")
public R<DirectMatchResult> matchDirect(@RequestBody DirectMatchRequest request){return R.ok(service.matchDirect(request));}
@PostMapping("/sample") @SaCheckPermission(ReportingActor.PREFIX+"edit")
public R<java.util.List<Sample>> sample(@RequestBody Definition request){return R.ok(service.sample(request));}
}
@@ -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<View> list(String keyword,int page,int size) {
var a=actors.current("view");ReportingService.paging(page,size);String k=ReportingPolicy.text(keyword,100,false,"关键词");
String where=" WHERE organization_id=? AND (INSTR(LOWER(plan_name),LOWER(?))>0 OR INSTR(LOWER(plan_code),LOWER(?))>0)";
long total=jdbc.queryForObject("SELECT COUNT(*) FROM dg_reporting_plan"+where,Long.class,a.organization(),k,k);
var ids=jdbc.query("SELECT plan_id FROM dg_reporting_plan"+where+" ORDER BY update_time DESC,plan_id LIMIT ? OFFSET ?",(r,n)->r.getString(1),a.organization(),k,k,size,(page-1)*size);
String where=" WHERE organization_id=?"; List<Object> 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<Object> 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<String> expected=new HashSet<>();
for(var resource:standard.definition().resources()) {
expected.add(resource.code());var binding=d.bindings().stream().filter(b->b.resourceCode().equals(resource.code())).findFirst().orElse(null);
if(binding==null){issues.add(new Issue(resource.code(),"BLOCKING","未绑定数据集"));continue;}
ReportingDatasetDirectory.Dataset dataset;
try{dataset=datasets.resolve(binding.datasetId());}catch(RuntimeException e){issues.add(new Issue(resource.code(),"BLOCKING","数据集不存在、无访问权限或当前不可读取"));continue;}
if(!sameVersion(binding,dataset)){issues.add(new Issue(resource.code(),"BLOCKING","数据集版本已变化,需重新绑定"));continue;}
if(binding==null){issues.add(new Issue(resource.code(),"BLOCKING","未绑定取数来源"));continue;}
List<ReportingDatasetDirectory.Field> 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<ReportingDatasetDirectory.Field> 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> sample(Definition raw){
var a=actors.current("edit");var d=normalize(raw);var standard=dependencies(a,d);
if(!"PUBLISHED".equals(standard.status())||standard.version()!=d.standardVersion())throw conflict("标准版本已变化");
if(d.bindings().size()>10)throw invalid("单次试算最多10张资源表,请按资源拆分试算");
List<Sample> samples=new ArrayList<>();
for(var b:d.bindings()){
var dataset=datasets.resolve(b.datasetId());if(!sameVersion(b,dataset))throw conflict("数据集版本已变化");
var fields=sourceFields(b);
var resource=standard.definition().resources().stream().filter(r->r.code().equals(b.resourceCode())).findFirst().orElseThrow(()->invalid("资源不属于标准"));
var columns=new LinkedHashSet<String>();b.mappings().forEach(m->columns.addAll(ReportingMapping.sources(m)));if(columns.isEmpty())columns.add(dataset.fields().getFirst().name());
var preview=datasets.preview(new ReportingDatasetDirectory.Read(dataset,List.copyOf(columns),List.of()));
if(preview==null||preview.complete()||preview.rows().size()>5)throw conflict("样例响应无效,不能作为快照使用");
int row=0;for(var values:preview.rows()){
var columns=new LinkedHashSet<String>();b.mappings().forEach(m->columns.addAll(ReportingMapping.sources(m)));if(columns.isEmpty())columns.add(fields.getFirst().name());
List<Map<String,String>> 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<String,String>();List<Issue> issues=new ArrayList<>();
for(var f:resource.fields()){
var mapping=b.mappings().stream().filter(m->m.target().equals(f.name())).findFirst().orElse(null);String value=null;
if(mapping==null)issues.add(new Issue(f.name(),"BLOCKING","缺少映射"));
else try{value=ReportingMapping.apply(mapping,values);}catch(RuntimeException e){issues.add(new Issue(f.name(),"BLOCKING","转换失败或字典未命中"));}
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<String> resources=new HashSet<>();int count=0;
for(var b:d.bindings()){
if(b==null||b.resourceCode()==null||!b.resourceCode().matches("[A-Za-z_][A-Za-z0-9_.-]{0,127}")||!resources.add(b.resourceCode())||b.datasetId()==null||!b.datasetId().matches("[1-9][0-9]{0,18}")||b.datasetVersion()<0||b.releaseId()==null||!b.releaseId().matches("[1-9][0-9]{0,18}")||b.schemaVersionId()==null||!b.schemaVersionId().matches("[1-9][0-9]{0,18}")||b.schemaSha256()==null||!b.schemaSha256().matches("[a-f0-9]{64}")||b.mappings()==null||b.mappings().size()>500)throw invalid("资源或数据集版本引用无效");
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<String> targets=new HashSet<>();for(var m:b.mappings())if(m==null||m.target()==null||!m.target().matches("[A-Za-z_][A-Za-z0-9_.-]{0,127}")||!targets.add(m.target())||m.source()==null||!m.source().isEmpty()&&!m.source().matches("[A-Za-z_][A-Za-z0-9_.-]{0,127}"))throw invalid("映射字段无效或重复");
count+=b.mappings().size();
b.mappings().forEach(ReportingMapping::validate);
@@ -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();
@@ -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<Issue> issues) { }
static Result map(ReportingStandardApi.Resource resource,ReportingPlanApi.Binding binding,Selection selection,List<Map<String,String>> rows){
List<Issue> issues=new ArrayList<>();List<Map<String,String>> mapped=new ArrayList<>(),sourceKeys=new ArrayList<>();Set<String> keys=new HashSet<>();int index=0;
return map(resource,binding,selection,rows,null);
}
static Result map(ReportingStandardApi.Resource resource,ReportingPlanApi.Binding binding,Selection selection,List<Map<String,String>> rows,String reporterCode){
List<Issue> issues=new ArrayList<>();List<Map<String,String>> mapped=new ArrayList<>(),sourceKeys=new ArrayList<>();Map<String,Integer> keys=new HashMap<>();Set<String> duplicateKeys=new HashSet<>();int index=0;
for(var source:rows){
index++;String key=selection.keyFields().stream().map(f->Objects.toString(source.get(f),"<NULL>")).reduce((a,b)->a+" | "+b).orElse("");
// Error locations retain a stable key fingerprint, never leak masked values in logs/list pages.
@@ -18,12 +21,13 @@ final class ReportingRows {
var keyParts=selection.keyFields().stream().map(source::get).toList();
Map<String,String> originalKey=new LinkedHashMap<>();selection.keyFields().forEach(f->originalKey.put(f,source.get(f)));sourceKeys.add(Collections.unmodifiableMap(originalKey));
String distinctKey=JSON.writeValueAsString(keyParts);
if(!keys.add(distinctKey))add(issues,resource.code(),index,keyRef,"","KEY_UNIQUE","业务主键重复");
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<String,String> target=new LinkedHashMap<>();
for(var f:resource.fields()){
var mapping=binding.mappings().stream().filter(m->m.target().equals(f.name())).findFirst().orElseThrow(()->ReportingException.invalid("缺少目标字段映射"));
String value=null;
try{value=ReportingMapping.apply(mapping,source);}
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<Issue> issues){
for(var r:standard.resources())for(var f:r.fields())if(f.details()!=null){
var d=f.details();
if(d.validationRule()!=null&&!d.validationRule().isBlank()&&ReportingQuality.reference(d.validationRule())==null||d.fillingRule()!=null&&!d.fillingRule().isBlank()||d.dictionary()!=null&&!d.dictionary().isBlank())
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","存在说明型规则或外部字典,尚未绑定可执行版本,不能按校验通过处理");
}
}
@@ -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<String> values) { }
private static final String PREFIX="REPORTING:";
static List<Rule> 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<Map<String,String>> rows,List<Issue> 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<Rule> 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<String,List<Integer>> groups=new HashMap<>();
for(int i=0;i<rows.size();i++){
var row=rows.get(i);String current=row.get(field.name()),other=rule.field()==null?null:row.get(rule.field()),error=null;
if("UNIQUE".equals(rule.kind())){if(current!=null&&!current.isBlank())groups.computeIfAbsent(current,k->new 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<Issue> 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));}
}
@@ -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<ReportingApi.Page<View>> list(@RequestParam(defaultValue = "") String keyword, @RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "20") int pageSize) {
return R.ok(service.list(keyword, pageNum, pageSize));
public R<ReportingApi.Page<View>> 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<View> get(@PathVariable String id) { return R.ok(service.get(id)); }
@@ -18,12 +18,24 @@ class ReportingStandardService {
record Stored(String id, long version, String status, Definition definition, String commandHash, String confirmation, String updatedAt) { }
ReportingApi.Page<View> list(String keyword, int page, int size) {
return list(keyword, null, page, size);
}
ReportingApi.Page<View> 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<Object> 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<Object> 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());
@@ -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();}
}
}
@@ -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> T queryForObject(String sql,Class<T> type,Object... args){return actual.queryForObject(prefix(sql),type,args);}
@Override public <T> List<T> query(String sql,RowMapper<T> 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();}
}
}
@@ -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> T queryForObject(String sql, Class<T> type, Object... args) {
countSql=sql; countArgs=args.clone(); return type.cast(0L);
}
@Override public <T> List<T> query(String sql, RowMapper<T> 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);
}
}
@@ -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"));}
}
@@ -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<Issue>();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<Map<String,String>>();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());
}
}
@@ -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 {
@@ -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<string, string>; 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<PlanCheck> => request({ url: `${base}/check`, method: 'post', data: definition });
export const listDatasets = (params: { keyword: string; pageNum: number; pageSize: number }): AxiosPromise<Page<Dataset>> => 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: [] });
@@ -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<Page<StandardView>> => request({ url: `${base}/standards`, params });
export const listStandards = (params: { keyword: string; status?: StandardView['status']; pageNum: number; pageSize: number }): AxiosPromise<Page<StandardView>> => request({ url: `${base}/standards`, params });
export const getStandard = (id: string): AxiosPromise<StandardView> => request({ url: `${base}/standards/${id}` });
export const getStandardAudit = (id: string, pageNum: number, pageSize: number): AxiosPromise<Page<Audit>> => request({ url: `${base}/standards/${id}/audit`, params: { pageNum, pageSize } });
export const saveStandard = (id: string, version: number, definition: StandardDefinition): AxiosPromise<StandardView> => request({ url: `${base}/standards/${id}`, method: 'put', data: { version, definition }, headers: { repeatSubmit: false } });
@@ -57,7 +57,9 @@
</el-col>
<el-col :span="12"><el-form-item label="超时(秒)"><el-input-number v-model="form.system.timeoutSeconds" :min="1" :max="120" /></el-form-item></el-col>
<el-col :span="12"><el-form-item label="重试上限"><el-input-number v-model="form.system.maxRetries" :min="0" :max="5" /></el-form-item></el-col>
<el-col :span="12"><el-form-item label="默认版本"><el-input v-model="form.system.defaultVersion" maxlength="64" /></el-form-item></el-col>
<el-col :span="12"><el-form-item label="接口报文版本"><el-input v-model="form.system.defaultVersion" maxlength="64" placeholder="如1000,与标准内部版本分开" /></el-form-item></el-col>
<el-col :span="12"><el-form-item label="上报单位信用代码"><el-input v-model="form.system.reporterCode" maxlength="18" /></el-form-item></el-col>
<el-col :span="12"><el-form-item label="接口代号"><el-input v-model="form.system.interfaceCode" maxlength="32" placeholder="如KCSZ" /></el-form-item></el-col>
<el-col :span="12"><el-form-item label="文件命名规则"><el-input v-model="form.system.fileNameRule" maxlength="200" /></el-form-item></el-col>
<el-col :span="24"><el-form-item label="目标能力"><el-checkbox v-model="form.system.attachments">支持附件</el-checkbox><el-checkbox v-model="form.system.batchSupport">支持批量</el-checkbox><el-checkbox v-model="form.system.receiptQuery">支持回执查询</el-checkbox></el-form-item></el-col>
</template>
@@ -0,0 +1,65 @@
<template>
<div class="w-full">
<el-button :disabled="disabled" @click="open">{{ current ? '调整直连来源' : '选择业务库 / 中间库' }}</el-button>
<el-drawer v-model="visible" title="业务数据库或标准中间库直连" size="min(1000px, 96vw)" append-to-body :close-on-click-modal="false">
<el-alert title="选择已有数据源及表;关联保留主表记录,关联缺失或多义结果由批次校验阻断。取数条件在任务中设置,源数据不会被修改。" type="info" :closable="false" class="mb-3" />
<el-alert v-if="error" :title="error" type="error" :closable="false" class="mb-3" />
<el-form label-width="100px" :disabled="busy || disabled">
<el-form-item label="已有数据源"><el-select v-model="definition.sourceId" filterable @change="sourceChanged"><el-option v-for="source in sources" :key="String(source.id)" :label="`${source.name} (${source.type})`" :value="String(source.id)" /></el-select></el-form-item>
<el-card v-for="(table, index) in definition.tables" :key="table.alias" class="mb-3" shadow="never">
<template #header>{{ index === 0 ? '主表' : '关联表' }} · {{ table.alias }}</template>
<el-form-item label="数据库"><el-select v-model="table.catalog" @change="catalogChanged(index)"><el-option v-for="name in catalogs" :key="name" :label="name" :value="name" /></el-select></el-form-item>
<el-form-item v-if="schemaOptions[table.alias]?.length" label="Schema"><el-select v-model="table.schema" @change="loadTables(index)"><el-option v-for="name in schemaOptions[table.alias]" :key="name" :label="name" :value="name" /></el-select></el-form-item>
<el-form-item label="表 / 视图"><el-select v-model="table.table" filterable @change="loadColumns(index)"><el-option v-for="item in tableOptions[table.alias] || []" :key="item.name" :value="item.name" :label="item.name" /></el-select></el-form-item>
<template v-if="index > 0 && definition.joins[index - 1]">
<el-form-item label="左侧表"><el-select v-model="definition.joins[index - 1].leftTable" @change="definition.joins[index - 1].leftField = ''"><el-option v-for="left in definition.tables.slice(0, index)" :key="left.alias" :value="left.alias" :label="`${left.alias} ${left.table}`" /></el-select></el-form-item>
<el-form-item label="左关联字段"><el-select v-model="definition.joins[index - 1].leftField" filterable><el-option v-for="field in columns[definition.joins[index - 1].leftTable] || []" :key="field.name" :value="field.name" :label="field.name" :disabled="field.masked" /></el-select></el-form-item>
<el-form-item label="本表关联字段"><el-select v-model="definition.joins[index - 1].rightField" filterable><el-option v-for="field in columns[table.alias] || []" :key="field.name" :value="field.name" :label="field.name" :disabled="field.masked" /></el-select></el-form-item>
</template>
<el-form-item label="输出字段"><el-select :model-value="definition.fields.filter(f => f.tableAlias === table.alias).map(f => f.column)" multiple filterable @update:model-value="selectColumns(table.alias, $event)"><el-option v-for="field in columns[table.alias] || []" :key="field.name" :value="field.name" :label="`${field.name} · ${field.type}`" :disabled="field.masked" /></el-select></el-form-item>
<el-button v-if="index > 0 && index === definition.tables.length - 1" link type="danger" @click="removeLast">移除此关联表</el-button>
</el-card>
<el-button :disabled="!definition.sourceId || definition.tables.length >= 5" @click="addTable">添加关联表</el-button>
<el-table :data="definition.fields" class="mt-3" border><el-table-column label="来源"><template #default="{ row }">{{ row.tableAlias }}.{{ row.column }}</template></el-table-column><el-table-column label="输出字段别名"><template #default="{ row }"><el-input v-model="row.name" maxlength="128" /></template></el-table-column></el-table>
</el-form>
<template #footer><el-button @click="visible = false">取消</el-button><el-button type="primary" :loading="busy" :disabled="disabled || !definition.fields.length" @click="confirm">核对来源并绑定</el-button></template>
</el-drawer>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { listDataSources, browseSourceObjects } from '@/api/datagov/data-sources';
import type { DataSourceVO, SourceObjectQuery } from '@/api/datagov/data-sources/types';
import { matchDirect } from '@/api/datagov/regulatory-reporting/plans';
import type { DirectDefinition, DirectSource, Suggestion } from '@/api/datagov/regulatory-reporting/plans';
const props = defineProps<{ standardId: string; resourceCode: string; disabled: boolean; current?: DirectSource | null }>();
const emit = defineEmits<{ bound: [value: { source: DirectSource; suggestions: Suggestion[] }] }>();
const visible = ref(false), busy = ref(false), error = ref(''), sources = ref<DataSourceVO[]>([]), catalogs = ref<string[]>([]);
type Entry = { name: string; schema?: string; type?: string; masked?: boolean };
const schemaOptions = ref<Record<string, string[]>>({}), tableOptions = ref<Record<string, Entry[]>>({}), columns = ref<Record<string, Entry[]>>({});
const blank = (): DirectDefinition => ({ sourceId: '', tables: [{ alias: 't1', catalog: null, schema: null, table: '' }], joins: [], fields: [] });
const definition = ref<DirectDefinition>(blank());
async function run(action: () => Promise<void>) { if (busy.value) return; busy.value = true; error.value = ''; try { await action(); } catch (e) { error.value = e instanceof Error ? e.message : '来源读取失败,请核对权限或连接状态'; } finally { busy.value = false; } }
async function browse(query: Omit<SourceObjectQuery, 'pageNum' | 'pageSize'>): Promise<Entry[]> {
const rows: Entry[] = [];
for (let pageNum = 1; pageNum <= 20; pageNum++) {
const page = (await browseSourceObjects<Entry>(definition.value.sourceId, { ...query, pageNum, pageSize: 100 })).data;
rows.push(...page.rows); if (rows.length >= page.total) return rows;
if (!page.rows.length) throw new Error('来源对象分页读取不完整');
}
throw new Error('来源对象超过2000项,请缩小数据库范围');
}
function queryFor(index: number, level: SourceObjectQuery['level']): Omit<SourceObjectQuery, 'pageNum' | 'pageSize'> {
const t = definition.value.tables[index]; return { level, ...(t.catalog ? { catalog: t.catalog } : {}), ...(t.schema ? { schema: t.schema } : {}), ...(level === 'COLUMN' ? { table: t.table } : {}) };
}
async function open() { visible.value = true; definition.value = props.current ? JSON.parse(JSON.stringify(props.current.definition)) : blank(); columns.value = {}; tableOptions.value = {}; schemaOptions.value = {}; await run(async () => { sources.value = (await listDataSources()).data.filter(s => !['HIVE', 'MARIADB'].includes(s.type)); if (definition.value.sourceId) { catalogs.value = (await browse({ level: 'CATALOG' })).map(r => r.name); for (let i = 0; i < definition.value.tables.length; i++) { const t = definition.value.tables[i]; schemaOptions.value[t.alias] = (await browse({ level: 'SCHEMA', catalog: t.catalog || undefined })).map(r => r.name); tableOptions.value[t.alias] = await browse(queryFor(i, 'TABLE')); columns.value[t.alias] = await browse(queryFor(i, 'COLUMN')); } } }); }
async function sourceChanged() { const sourceId = definition.value.sourceId; definition.value = { ...blank(), sourceId }; columns.value = {}; tableOptions.value = {}; schemaOptions.value = {}; await run(async () => { catalogs.value = (await browse({ level: 'CATALOG' })).map(r => r.name); }); }
async function catalogChanged(index: number) { const t = definition.value.tables[index]; t.schema = null; t.table = ''; clearFields(t.alias); await run(async () => { schemaOptions.value[t.alias] = (await browse({ level: 'SCHEMA', catalog: t.catalog || undefined })).map(r => r.name); tableOptions.value[t.alias] = schemaOptions.value[t.alias].length ? [] : await browse(queryFor(index, 'TABLE')); }); }
async function loadTables(index: number) { const t = definition.value.tables[index]; t.table = ''; clearFields(t.alias); await run(async () => { tableOptions.value[t.alias] = await browse(queryFor(index, 'TABLE')); }); }
async function loadColumns(index: number) { const t = definition.value.tables[index]; clearFields(t.alias); await run(async () => { columns.value[t.alias] = await browse(queryFor(index, 'COLUMN')); }); }
function clearFields(alias: string) { columns.value[alias] = []; definition.value.fields = definition.value.fields.filter(f => f.tableAlias !== alias); for (const join of definition.value.joins) { if (join.leftTable === alias) join.leftField = ''; if (join.rightTable === alias) join.rightField = ''; } }
function selectColumns(alias: string, selected: string[]) { const old = definition.value.fields.filter(f => f.tableAlias === alias), remaining = definition.value.fields.filter(f => f.tableAlias !== alias); definition.value.fields = [...remaining, ...selected.map(column => old.find(f => f.column === column) || { tableAlias: alias, column, name: remaining.some(f => f.name === column) ? `${alias}_${column}` : column })]; }
function addTable() { const alias = `t${definition.value.tables.length + 1}`; definition.value.tables.push({ alias, catalog: null, schema: null, table: '' }); definition.value.joins.push({ leftTable: 't1', leftField: '', rightTable: alias, rightField: '' }); }
function removeLast() { const t = definition.value.tables.pop(); definition.value.joins.pop(); if (t) clearFields(t.alias); }
async function confirm() { await run(async () => { const result = (await matchDirect(props.standardId, props.resourceCode, definition.value)).data; if (visible.value && !props.disabled) { emit('bound', result); visible.value = false; } }); }
</script>
@@ -14,7 +14,7 @@
<el-form-item label="期间字段"><el-select v-model="selection.periodField" clearable filterable><el-option v-for="f in columns[selection.resourceCode] || []" :key="f.name" :label="`${f.name} · ${f.type}`" :value="f.name" /></el-select></el-form-item>
<el-form-item label="附件引用字段"><el-select v-model="selection.attachmentFields" multiple filterable placeholder="无附件可不选"><el-option v-for="field in targets[selection.resourceCode] || []" :key="field" :label="field" :value="field" /></el-select></el-form-item>
<p class="mb-3 text-sm">选择目标标准中保存附件引用的字段。每个非空值应为32位大写MD5_原文件名,可带unStruct/前缀;每个字段对应一个附件。</p>
<el-table :data="selection.filters" border><el-table-column label="过滤字段"><template #default="{ row }"><el-select v-model="row.field" filterable><el-option v-for="f in columns[selection.resourceCode] || []" :key="f.name" :label="f.name" :value="f.name" /></el-select></template></el-table-column><el-table-column label="条件" width="160"><template #default="{ row }"><el-select v-model="row.operator"><el-option v-for="(label, value) in operators" :key="value" :value="value" :label="label" /></el-select></template></el-table-column><el-table-column label="值"><template #default="{ row }"><el-input v-if="!row.operator.includes('NULL')" :model-value="row.values[0] || ''" @update:model-value="row.values = [$event]" /></template></el-table-column><el-table-column label="操作" width="90"><template #default="{ $index }"><el-button link type="danger" @click="selection.filters.splice($index, 1)">删除</el-button></template></el-table-column></el-table>
<el-table :data="selection.filters" border><el-table-column label="过滤字段"><template #default="{ row }"><el-select v-model="row.field" filterable><el-option v-for="f in columns[selection.resourceCode] || []" :key="f.name" :label="f.name" :value="f.name" /></el-select></template></el-table-column><el-table-column label="条件" width="160"><template #default="{ row }"><el-select v-model="row.operator"><el-option v-for="(label, value) in operators" :key="value" :value="value" :label="label" /></el-select></template></el-table-column><el-table-column label="值"><template #default="{ row }"><el-select v-if="['IN', 'NOT_IN'].includes(row.operator)" v-model="row.values" multiple filterable allow-create default-first-option placeholder="输入业务编码后回车" /><el-input v-else-if="!row.operator.includes('NULL')" :model-value="row.values[0] || ''" @update:model-value="row.values = [$event]" /></template></el-table-column><el-table-column label="操作" width="90"><template #default="{ $index }"><el-button link type="danger" @click="selection.filters.splice($index, 1)">删除</el-button></template></el-table-column></el-table>
<el-button class="mt-2" :disabled="selection.filters.length >= 18" @click="selection.filters.push({ field: '', operator: 'EQ', values: [''] })">添加过滤</el-button>
</el-collapse-item></el-collapse>
</el-form><template #footer><el-button @click="taskVisible = false">取消</el-button><el-button type="primary" :loading="busy" @click="save">保存任务</el-button></template>
@@ -26,9 +26,9 @@
<pagination v-show="batchTotal > 0" v-model:page="batchPage" v-model:limit="batchSize" :total="batchTotal" @pagination="loadBatches" />
</el-drawer>
<el-drawer v-model="detailVisible" title="批次详情" size="min(1150px, 96vw)" append-to-body>
<template v-if="selected"><el-alert :title="selected.message || states[selected.state]" type="info" :closable="false" /><p class="my-3">批次 {{ selected.id }} · {{ states[selected.state] }} · {{ selected.rowCount }} 条记录</p>
<template v-if="selected"><el-alert :title="selected.message || states[selected.state]" type="info" :closable="false" /><p class="my-3">批次 {{ selected.id }} · {{ states[selected.state] }} · {{ selected.rowCount }} 条记录</p><p v-if="selected.snapshotId" class="mb-3">{{ rowSummary(selected) }}</p>
<el-tabs><el-tab-pane label="校验问题"><el-button class="mb-3" @click="exportIssues">导出整改清单</el-button><el-table :data="selected.issues" border max-height="500" empty-text="暂无校验问题记录"><el-table-column prop="resource" label="资源" /><el-table-column prop="row" label="记录序号" width="100" /><el-table-column prop="key" label="主键摘要" /><el-table-column prop="field" label="字段" /><el-table-column prop="rule" label="规则" /><el-table-column label="级别" width="80"><template #default="{ row }">{{ row.severity === 'BLOCKING' ? '阻断' : '警告' }}</template></el-table-column><el-table-column prop="message" label="原因" min-width="250" /></el-table></el-tab-pane>
<el-tab-pane label="快照与文件"><el-alert title="下载时重新校验数据集权限、行过滤和脱敏规则;当前有效数据范围必须与快照一致。" type="info" :closable="false" class="mb-3" /><el-table :data="artifacts" border><el-table-column prop="name" label="文件" min-width="240" /><el-table-column prop="length" label="字节数" width="100" /><el-table-column label="状态" width="100"><template #default="{ row }">{{ row.state === 'BOUND' ? '已保存' : '待核对' }}</template></el-table-column><el-table-column label="操作" width="100"><template #default="{ row }"><el-button link type="primary" :disabled="row.state !== 'BOUND'" @click="download(row)">下载</el-button></template></el-table-column></el-table></el-tab-pane>
<el-tab-pane label="快照与文件"><el-alert title="下载时重新校验原取数来源权限、结构及过滤范围;文件始终来自同一冻结快照。" type="info" :closable="false" class="mb-3" /><el-table :data="artifacts" border><el-table-column prop="name" label="文件" min-width="240" /><el-table-column prop="length" label="字节数" width="100" /><el-table-column label="状态" width="100"><template #default="{ row }">{{ row.state === 'BOUND' ? '已保存' : '待核对' }}</template></el-table-column><el-table-column label="操作" width="100"><template #default="{ row }"><el-button link type="primary" :disabled="row.state !== 'BOUND'" @click="download(row)">下载</el-button></template></el-table-column></el-table></el-tab-pane>
<el-tab-pane label="业务附件" lazy><AttachmentPanel :key="`${selected.id}:${selected.version}`" :batch="selected" @refresh="refreshDetails" /></el-tab-pane>
<el-tab-pane label="审核与操作记录"><el-table :data="audits" border><el-table-column prop="occurredAt" label="时间" width="190" /><el-table-column prop="action" label="操作" /><el-table-column prop="actorId" label="操作人" /><el-table-column prop="reason" label="意见 / 原因" min-width="300" /></el-table><pagination v-show="auditTotal > 0" v-model:page="auditPage" v-model:limit="auditSize" :total="auditTotal" @pagination="loadAudit" /></el-tab-pane>
<el-tab-pane label="提交预检"><el-alert v-for="item in blockers" :key="item" :title="item" type="warning" :closable="false" class="mb-3" /></el-tab-pane>
@@ -43,11 +43,16 @@ import { ElMessage, ElMessageBox } from 'element-plus';
import AttachmentPanel from './AttachmentPanel.vue';
import * as api from '@/api/datagov/regulatory-reporting/execution';
import type { Audit } from '@/api/datagov/regulatory-reporting';
import { listPlans, getPlan, matchFields } from '@/api/datagov/regulatory-reporting/plans';
import { listPlans, getPlan, matchFields, matchDirect } from '@/api/datagov/regulatory-reporting/plans';
import type { Plan, DatasetField } from '@/api/datagov/regulatory-reporting/plans';
const editPermission = 'aixun:integration:regulatory-reporting:edit';
function rowSummary(batch: api.Batch) {
const failures = new Set(batch.issues.filter(i => i.severity === 'BLOCKING' && i.row > 0).map(i => `${i.resource}:${i.row}`)).size;
const global = batch.issues.some(i => i.severity === 'BLOCKING' && i.row === 0);
return `共 ${batch.rowCount} 条,逐条校验失败 ${failures} 条,${global ? '其余仍受批次级阻断影响' : `逐条检查通过 ${Math.max(0, batch.rowCount - failures)} 条`};全部记录保留,未静默排除失败数据。`;
}
const periods: Record<string, string> = { MONTH: '月报', QUARTER: '季报', YEAR: '年报', CUSTOM: '自定义期间' };
const operators = { EQ: '等于', NE: '不等于', GT: '大于', GTE: '大于等于', LT: '小于', LTE: '小于等于', IS_NULL: '为空', IS_NOT_NULL: '不为空' };
const operators = { EQ: '等于', NE: '不等于', GT: '大于', GTE: '大于等于', LT: '小于', LTE: '小于等于', IN: '属于所选集合', NOT_IN: '不属于所选集合', IS_NULL: '为空', IS_NOT_NULL: '不为空' };
const states: Record<string, string> = { DRAFT: '待生成候选数据', READING: '读取中', VALIDATION_FAILED: '校验未通过', REVIEW_PENDING: '待审核', ATTACHING: '附件保存中', ATTACHMENT_UNKNOWN: '附件待核对', REJECTED: '审核驳回', FROZEN: '已审核冻结', GENERATING: '文件生成中', FILE_READY: '文件已生成', FAILED: '处理失败', UNKNOWN: '结果待核对', CANCELED: '已撤销' };
const actionNames: Record<string, string> = { prepare: '生成候选数据', approve: '审核并冻结', reject: '驳回', generate: '生成文件', reconcile: '核对结果', cancel: '撤销' };
const tasks = ref<api.Task[]>([]), total = ref(0), page = ref(1), size = ref(20), loading = ref(false), failed = ref(false), busy = ref(false);
@@ -61,7 +66,7 @@ watch(dates, () => { pendingBatchId.value = ''; });
async function load() { loading.value = true; failed.value = false; try { const r = (await api.listTasks(page.value, size.value)).data; tasks.value = r.rows; total.value = r.total; } catch { failed.value = true; tasks.value = []; } finally { loading.value = false; } }
async function searchPlans(keyword: string) { planChoices.value = (await listPlans({ keyword, pageNum: 1, pageSize: 100 })).data.rows; }
async function editTask(row?: unknown) { const task = row as api.Task | undefined; taskId.value = task?.id || crypto.randomUUID(); taskVersion.value = task?.version ?? -1; draft.value = task ? JSON.parse(JSON.stringify(task.definition)) : blank(); draft.value.selections.forEach(s => { s.attachmentFields ||= []; }); columns.value = {}; targets.value = {}; await searchPlans(''); if (task) await loadColumns((await getPlan(task.definition.planId)).data); taskVisible.value = true; }
async function loadColumns(plan: Plan) { for (const binding of plan.definition.bindings) { columns.value[binding.resourceCode] = (await matchFields(plan.definition.standardId, binding.resourceCode, binding.datasetId)).data.dataset.fields; targets.value[binding.resourceCode] = binding.mappings.map(m => m.target); } }
async function loadColumns(plan: Plan) { for (const binding of plan.definition.bindings) { columns.value[binding.resourceCode] = binding.directSource ? (await matchDirect(plan.definition.standardId, binding.resourceCode, binding.directSource.definition)).data.source.fields : (await matchFields(plan.definition.standardId, binding.resourceCode, binding.datasetId!)).data.dataset.fields; targets.value[binding.resourceCode] = binding.mappings.map(m => m.target); } }
async function choosePlan(id: string) { busy.value = true; try { const plan = (await getPlan(id)).data; draft.value.planVersion = plan.version; draft.value.selections = plan.definition.bindings.map(b => ({ resourceCode: b.resourceCode, periodField: '', keyFields: [], filters: [], attachmentFields: [] })); await loadColumns(plan); } finally { busy.value = false; } }
async function save() { if (busy.value) return; busy.value = true; try { for (const selection of draft.value.selections) for (const filter of selection.filters) if (filter.operator.includes('NULL')) filter.values = []; await api.saveTask(taskId.value, taskVersion.value, draft.value); taskVisible.value = false; ElMessage.success('任务已保存'); await load(); } finally { busy.value = false; } }
async function reason(title: string) { return (await ElMessageBox.prompt('请填写操作原因;审核通过时须说明警告项和空报记录的核对结论。', title, { inputType: 'textarea', inputValidator: (v: string) => !!v?.trim() && v.length <= 1000 || '请填写1—1000字意见' })).value; }
@@ -1,7 +1,7 @@
<template>
<div class="reporting-plans">
<el-card class="table-panel mt-3" shadow="hover">
<template #header><div class="toolbar-shell"><div class="table-heading"><h3>报送方案</h3><p>复用已发布标准和授权数据集,保存固定版本的资源映射</p></div>
<template #header><div class="toolbar-shell"><div class="table-heading"><h3>报送方案</h3><p>选择业务库、中间库或授权数据集,保存固定版本的资源映射</p></div>
<el-button v-hasPermi="['aixun:integration:regulatory-reporting:edit']" type="primary" icon="Plus" @click="create">新建方案</el-button></div></template>
<el-form inline @submit.prevent="search"><el-form-item label="方案"><el-input v-model="query.keyword" clearable placeholder="编码或名称" /></el-form-item><el-form-item><el-button type="primary" icon="Search" @click="search">查询</el-button></el-form-item></el-form>
<el-alert v-if="failed" title="方案读取失败,请重试" type="error" :closable="false" />
@@ -21,7 +21,7 @@
</el-card>
<el-drawer v-model="visible" :title="editing ? '配置报送方案' : '报送方案详情'" size="min(1100px, 96vw)" :close-on-click-modal="false">
<el-alert title="配置冻结后不可修改,需要变更时创建新版本。完整数据读取、报送执行和接口校验完成后,方案才能用于正式报送。" type="info" :closable="false" class="mb-3" />
<el-steps :active="step" finish-status="success" align-center class="mb-4"><el-step title="基础引用" /><el-step title="数据集与映射" /><el-step title="检查与保存" /></el-steps>
<el-steps :active="step" finish-status="success" align-center class="mb-4"><el-step title="基础引用" /><el-step title="取数与映射" /><el-step title="检查与保存" /></el-steps>
<el-form v-loading="busy" :disabled="!editing || busy" label-width="110px">
<div v-show="step === 0">
<el-form-item label="方案编码" required><el-input v-model="draft.code" :disabled="version >= 0" maxlength="64" /></el-form-item>
@@ -30,26 +30,30 @@
<el-form-item label="监管接收机构" required><el-select v-model="draft.regulatorId" filterable @change="regulatorChanged"><el-option v-for="r in regulators" :key="r.id" :value="r.id" :label="r.name" /></el-select></el-form-item>
<el-form-item label="上报系统" required><el-select v-model="draft.systemId" filterable @change="systemChanged"><el-option v-for="r in systems" :key="r.id" :value="r.id" :label="r.name" /></el-select></el-form-item>
<el-form-item label="报送主题" required><el-select v-model="draft.topicId" filterable><el-option v-for="r in topics" :key="r.id" :value="r.id" :label="r.name" /></el-select></el-form-item>
<el-form-item label="固定标准版本" required><el-select v-model="draft.standardId" filterable @change="standardChanged"><el-option v-for="s in standards" :key="s.id" :value="s.id" :label="`${s.definition.name} · ${s.definition.versionLabel} (${s.status === 'PUBLISHED' ? '已发布' : '不可用'})`" :disabled="s.status !== 'PUBLISHED'" /></el-select></el-form-item>
<el-form-item label="固定标准版本" required><el-select v-model="draft.standardId" filterable remote :remote-method="searchStandards" :loading="standardLoading" :no-data-text="standardError ? '加载失败,请重试' : '暂无匹配的已发布标准'" @change="standardChanged"><el-option v-for="s in standardOptions" :key="s.id" :value="s.id" :label="`${s.definition.name} · ${s.definition.versionLabel} (${s.status === 'PUBLISHED' ? '已发布' : '不可用'})`" :disabled="s.status !== 'PUBLISHED'" /></el-select><el-button v-if="standards.length < standardTotal" link :loading="standardLoading" @click="loadStandards(true)">加载更多({{ standards.length }}/{{ standardTotal }})</el-button></el-form-item>
<el-alert v-if="standardError" :title="standardError" type="error" :closable="false" class="mb-3"><el-button link type="primary" @click="searchStandards(standardKeyword)">重新加载标准</el-button></el-alert>
<el-form-item label="适配配置" required><el-select v-model="draft.adapterProfile"><el-option label="科技创新 B 接口" value="SASAC_SCIENCE_B" /><el-option label="司库 B 接口" value="SASAC_TREASURY_B" /></el-select></el-form-item>
<el-form-item label="说明"><el-input v-model="draft.description" type="textarea" maxlength="2000" /></el-form-item>
</div>
<div v-show="step === 1">
<el-alert v-if="!resources.length" title="请先选择已发布的标准" type="warning" :closable="false" />
<el-tabs v-model="activeResource"><el-tab-pane v-for="resource in resources" :key="resource.code" :label="`${resource.name} (${resource.fields.length})`" :name="resource.code">
<el-form-item label="授权数据集"><el-select :model-value="binding(resource.code)?.datasetId" filterable remote :remote-method="searchDatasets" :loading="datasetLoading" @change="bind(resource.code, $event)"><el-option v-for="d in datasetOptions" :key="d.id" :value="d.id" :label="`${d.name} (${d.code})`" /></el-select></el-form-item>
<p v-if="binding(resource.code)" class="mb-3">已固定发布 {{ binding(resource.code)?.releaseId }} · 结构 {{ binding(resource.code)?.schemaVersionId }}
<el-button v-if="editing" link type="primary" @click="bind(resource.code, binding(resource.code)!.datasetId)">重新读取并匹配</el-button></p>
<el-form-item label="业务库直连"><DirectSourcePicker :standard-id="draft.standardId" :resource-code="resource.code" :disabled="!editing || busy" :current="binding(resource.code)?.directSource" @bound="bindDirect(resource.code, $event)" /></el-form-item>
<el-form-item label="或授权数据集"><el-select :model-value="binding(resource.code)?.datasetId" filterable remote :remote-method="searchDatasets" :loading="datasetLoading" @visible-change="value => value && searchDatasets('')" @change="bind(resource.code, $event)"><el-option v-for="d in datasetOptions" :key="d.id" :value="d.id" :label="`${d.name} (${d.code})`" /></el-select></el-form-item>
<el-alert v-if="datasetError" :title="datasetError" type="error" :closable="false" class="mb-3" />
<p v-if="binding(resource.code)?.directSource" class="mb-3">已绑定直连来源 · 连接版本 {{ binding(resource.code)?.directSource?.sourceVersion }} · {{ binding(resource.code)?.directSource?.definition.tables.map(t => t.table).join('、') }}</p>
<p v-else-if="binding(resource.code)" class="mb-3">已固定发布 {{ binding(resource.code)?.releaseId }} · 结构 {{ binding(resource.code)?.schemaVersionId }}
<el-button v-if="editing" link type="primary" @click="bind(resource.code, binding(resource.code)!.datasetId!)">重新读取并匹配</el-button></p>
<el-table :data="mappings(resource.code)" border>
<el-table-column label="标准字段" min-width="170"><template #default="{ row }">{{ row.target }}<p>{{ resource.fields.find(f => f.name === row.target)?.label }}</p></template></el-table-column>
<el-table-column label="来源字段" min-width="220"><template #default="{ row }"><el-select v-model="row.source" filterable clearable @change="row.confirmed = false"><el-option v-for="f in sourceFields[resource.code] || []" :key="f.name" :value="f.name" :label="`${f.name} · ${f.type}`" /><el-option v-if="row.source && !sourceFields[resource.code]?.some(f => f.name === row.source)" :value="row.source" :label="row.source" /></el-select></template></el-table-column>
<el-table-column label="匹配依据" min-width="230"><template #default="{ row }"><template v-if="suggestion(resource.code, row.target)">{{ methodLabels[suggestion(resource.code, row.target)!.method] || '人工核对' }} · {{ confidenceLabels[suggestion(resource.code, row.target)!.confidence] || '待核对' }}<p>{{ suggestion(resource.code, row.target)?.reason }}</p></template><span v-else>已保存映射;可重新读取后检查</span></template></el-table-column>
<el-table-column label="转换" width="130"><template #default="{ row }"><el-button link type="primary" @click="configureTransform(row, resource.code)">{{ row.transform?.kind || '直接映射' }}</el-button></template></el-table-column>
<el-table-column label="人工确认" width="110"><template #default="{ row }"><el-checkbox v-model="row.confirmed" :disabled="!row.source && !['CONSTANT', 'CONCAT'].includes(row.transform?.kind || '')">已核对</el-checkbox></template></el-table-column>
<el-table-column label="人工确认" width="110"><template #default="{ row }"><el-checkbox v-model="row.confirmed" :disabled="!row.source && !['CONSTANT', 'REPORTER_CODE', 'CONCAT'].includes(row.transform?.kind || '')">已核对</el-checkbox></template></el-table-column>
</el-table>
</el-tab-pane></el-tabs>
</div>
<div v-show="step === 2"><p class="mb-3">{{ draft.name || '--' }} · {{ draft.versionLabel || '--' }},{{ resources.length }} 个资源,已绑定 {{ draft.bindings.length }} 个数据集。</p>
<div v-show="step === 2"><p class="mb-3">{{ draft.name || '--' }} · {{ draft.versionLabel || '--' }},{{ resources.length }} 个资源,已绑定 {{ draft.bindings.length }} 个取数来源。</p>
<el-button v-if="editing" :loading="busy" @click="check">运行预检查</el-button><el-button v-if="editing" :loading="busy" @click="sample">当前资源映射试算(最多5条)</el-button><el-button v-if="checks" @click="exportIssues">导出检查结果</el-button>
<template v-if="samples !== undefined"><el-alert title="样例仅用于核对映射;不含任务过滤,不代表完整数据、批次校验或快照。" type="info" :closable="false" class="my-3" /><el-table :data="samples" border empty-text="当前权限范围内没有样例记录"><el-table-column prop="resource" label="资源" width="150" /><el-table-column prop="row" label="样例" width="70" /><el-table-column label="源值"><template #default="{ row }"><pre style="white-space: pre-wrap; word-break: break-word">{{ JSON.stringify(row.source, null, 2) }}</pre></template></el-table-column><el-table-column label="转换后"><template #default="{ row }"><pre style="white-space: pre-wrap; word-break: break-word">{{ JSON.stringify(row.target, null, 2) }}</pre></template></el-table-column><el-table-column label="问题"><template #default="{ row }"><div v-for="(issue, i) in row.issues" :key="i">{{ issue.location }}:{{ issue.message }}</div></template></el-table-column></el-table></template>
<el-alert v-if="checks" class="my-3" :title="checks.configurationValid ? '基础引用和字段映射检查通过;执行条件尚未齐备' : '检查发现待处理项'" type="warning" :closable="false" />
@@ -59,28 +63,54 @@
<template #footer><div class="dialog-footer"><el-button @click="visible = false">关闭</el-button><el-button v-if="step > 0" @click="step--">上一步</el-button><el-button v-if="step < 2" type="primary" @click="next">下一步</el-button><el-button v-if="editing" type="primary" :loading="busy" @click="save">保存草稿</el-button></div></template>
</el-drawer>
<el-drawer v-model="auditVisible" title="方案操作记录" size="min(900px, 96vw)"><el-table :data="auditRows" border><el-table-column prop="occurredAt" label="时间" width="190" /><el-table-column label="操作" width="140"><template #default="{ row }">{{ auditLabels[row.action] || row.action }}</template></el-table-column><el-table-column prop="actorId" label="操作人" width="160" /><el-table-column prop="reason" label="原因" /></el-table><pagination v-show="auditTotal > 0" v-model:page="auditPage" v-model:limit="auditSize" :total="auditTotal" @pagination="loadAudit" /></el-drawer>
<el-dialog v-model="transformVisible" title="字段转换" width="650px" append-to-body><el-form label-width="110px" :disabled="!editing"><el-form-item label="转换类型"><el-select v-model="transform.kind"><el-option v-for="(label, value) in transformKinds" :key="value" :value="value" :label="label" /></el-select></el-form-item><el-form-item v-if="['CONSTANT', 'DEFAULT', 'DATE', 'DATETIME', 'DECIMAL', 'CONCAT'].includes(transform.kind)" label="参数"><el-input v-model="transform.argument" :placeholder="transform.kind === 'DECIMAL' ? '小数位(不允许舍入)' : ['DATE', 'DATETIME'].includes(transform.kind) ? '输入格式,如 uuuu-MM-dd' : transform.kind === 'CONCAT' ? '拼接分隔符' : '固定值 / 默认值'" /></el-form-item><el-form-item v-if="['DATE', 'DATETIME'].includes(transform.kind)" label="输出格式"><el-input v-model="transform.outputFormat" placeholder="如 uuuu-MM-dd" /></el-form-item><el-form-item v-if="transform.kind === 'CONCAT'" label="拼接字段"><el-select v-model="transform.sources" multiple filterable><el-option v-for="f in sourceFields[transformResource] || []" :key="f.name" :value="f.name" :label="f.name" /></el-select></el-form-item><template v-if="transform.kind === 'DICTIONARY'"><el-table :data="dictionaryRows" border><el-table-column label="源值"><template #default="{ row }"><el-input v-model="row.source" /></template></el-table-column><el-table-column label="目标值"><template #default="{ row }"><el-input v-model="row.target" /></template></el-table-column><el-table-column label="操作" width="80"><template #default="{ $index }"><el-button link type="danger" @click="dictionaryRows.splice($index, 1)">删除</el-button></template></el-table-column></el-table><el-button class="mt-2" @click="dictionaryRows.push({ source: '', target: '' })">添加字典项</el-button></template></el-form><template #footer><el-button @click="transformVisible = false">关闭</el-button><el-button v-if="editing" type="primary" @click="saveTransform">应用转换</el-button></template></el-dialog>
<el-dialog v-model="transformVisible" title="字段转换" width="650px" append-to-body><el-form label-width="110px" :disabled="!editing"><el-form-item label="转换类型"><el-select v-model="transform.kind"><el-option v-for="(label, value) in transformKinds" :key="value" :value="value" :label="label" /></el-select></el-form-item><el-form-item v-if="['CONSTANT', 'STABLE_GUID', 'DEFAULT', 'DATE', 'DATETIME', 'DECIMAL', 'CONCAT'].includes(transform.kind)" label="参数"><el-input v-model="transform.argument" :placeholder="transform.kind === 'DECIMAL' ? '小数位(不允许舍入)' : ['DATE', 'DATETIME'].includes(transform.kind) ? '输入格式,如 uuuu-MM-dd' : transform.kind === 'CONCAT' ? '拼接分隔符' : '固定值 / 默认值'" /></el-form-item><el-form-item v-if="['DATE', 'DATETIME'].includes(transform.kind)" label="输出格式"><el-input v-model="transform.outputFormat" placeholder="如 uuuu-MM-dd" /></el-form-item><el-form-item v-if="transform.kind === 'CONCAT'" label="拼接字段"><el-select v-model="transform.sources" multiple filterable><el-option v-for="f in sourceFields[transformResource] || []" :key="f.name" :value="f.name" :label="f.name" /></el-select></el-form-item><template v-if="transform.kind === 'DICTIONARY'"><el-table :data="dictionaryRows" border><el-table-column label="源值"><template #default="{ row }"><el-input v-model="row.source" /></template></el-table-column><el-table-column label="目标值"><template #default="{ row }"><el-input v-model="row.target" /></template></el-table-column><el-table-column label="操作" width="80"><template #default="{ $index }"><el-button link type="danger" @click="dictionaryRows.splice($index, 1)">删除</el-button></template></el-table-column></el-table><el-button class="mt-2" @click="dictionaryRows.push({ source: '', target: '' })">添加字典项</el-button></template></el-form><template #footer><el-button @click="transformVisible = false">关闭</el-button><el-button v-if="editing" type="primary" @click="saveTransform">应用转换</el-button></template></el-dialog>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import DirectSourcePicker from './DirectSourcePicker.vue';
import { listConfigs } from '@/api/datagov/regulatory-reporting';
import type { Audit, ConfigKind, ConfigView } from '@/api/datagov/regulatory-reporting';
import { getStandard, listStandards } from '@/api/datagov/regulatory-reporting/standards';
import type { StandardView } from '@/api/datagov/regulatory-reporting/standards';
import { blankPlan, listPlans, getPlan, getPlanAudit, changePlanState, savePlan, checkPlan, listDatasets, matchFields, samplePlan } from '@/api/datagov/regulatory-reporting/plans';
import type { Plan, PlanCheck, Dataset, DatasetField, Suggestion, Mapping, Transform, MappingSample } from '@/api/datagov/regulatory-reporting/plans';
import type { Plan, PlanCheck, Dataset, DatasetField, Suggestion, Mapping, Transform, MappingSample, DirectSource } from '@/api/datagov/regulatory-reporting/plans';
const rows = ref<Plan[]>([]), total = ref(0), loading = ref(false), failed = ref(false), query = reactive({ keyword: '', pageNum: 1, pageSize: 20 });
const visible = ref(false), editing = ref(false), busy = ref(false), step = ref(0), id = ref(''), version = ref(-1), draft = ref(blankPlan());
const regulators = ref<ConfigView[]>([]), systems = ref<ConfigView[]>([]), topics = ref<ConfigView[]>([]), standards = ref<StandardView[]>([]), selectedStandard = ref<StandardView>();
const standardLoading = ref(false), standardError = ref(''), standardTotal = ref(0), standardKeyword = ref(''), standardPage = ref(1);
const standardOptions = computed(() => selectedStandard.value && !standards.value.some(s => s.id === selectedStandard.value?.id) ? [selectedStandard.value, ...standards.value] : standards.value);
let standardRequest = 0;
async function searchStandards(keyword: string) { standardKeyword.value = keyword; standardPage.value = 1; await loadStandards(false); }
async function loadStandards(append: boolean) {
if (append && standardLoading.value) return;
const current = ++standardRequest, pageNum = append ? standardPage.value + 1 : 1;
standardLoading.value = true; standardError.value = '';
if (!append) { standards.value = []; standardTotal.value = 0; }
try {
const page = (await listStandards({ keyword: standardKeyword.value, status: 'PUBLISHED', pageNum, pageSize: 50 })).data;
if (current !== standardRequest) return;
if (!page.rows.length && (pageNum - 1) * 50 < page.total) throw new Error('标准分页读取不完整,请刷新重试');
standards.value = append ? [...new Map([...standards.value, ...page.rows].map(s => [s.id, s])).values()] : page.rows;
standardTotal.value = page.total; standardPage.value = pageNum;
} catch (error) { if (current === standardRequest) standardError.value = `标准候选加载失败:${error instanceof Error ? error.message : '请重试或联系管理员核对接口错误编号'}`; }
finally { if (current === standardRequest) standardLoading.value = false; }
}
const resources = computed(() => selectedStandard.value?.definition.resources || []), activeResource = ref(''), checks = ref<PlanCheck>();
const datasetOptions = ref<Dataset[]>([]), datasetLoading = ref(false), sourceFields = ref<Record<string, DatasetField[]>>({}), suggestions = ref<Record<string, Suggestion[]>>({});
const datasetError = ref('');
async function bindDirect(code: string, result: { source: DirectSource; suggestions: Suggestion[] }) {
if (binding(code)?.mappings.some(m => m.confirmed)) await ElMessageBox.confirm('替换来源将清除当前映射确认,是否继续?', '更换取数来源');
sourceFields.value[code] = result.source.fields; suggestions.value[code] = result.suggestions;
draft.value.bindings = draft.value.bindings.filter(b => b.resourceCode !== code);
draft.value.bindings.push({ resourceCode: code, datasetId: null, datasetVersion: 0, releaseId: null, schemaVersionId: null, schemaSha256: null, directSource: result.source, mappings: result.suggestions.map(s => ({ target: s.target, source: s.candidates.length === 1 ? s.candidates[0] : '', confirmed: false })) });
}
const methodLabels: Record<string, string> = { EXACT_CODE: '字段编码一致', NAME_CANDIDATE: '名称候选', NONE: '无候选' };
const confidenceLabels: Record<string, string> = { HIGH: '高置信度', REVIEW_REQUIRED: '需核对', AMBIGUOUS: '无唯一匹配' };
const auditLabels: Record<string, string> = { PLAN_CREATE: '创建方案', PLAN_UPDATE: '修改草稿', PLAN_FREEZE: '冻结配置', PLAN_DISABLE: '停用方案' };
const auditRows = ref<Audit[]>([]), auditVisible = ref(false), auditId = ref(''), auditPage = ref(1), auditSize = ref(20), auditTotal = ref(0);
const transformKinds = { DIRECT: '直接映射', CONSTANT: '常量', DEFAULT: '空值默认值', TRIM: '去首尾空白', UPPER: '转大写', LOWER: '转小写', DICTIONARY: '字典 / 组织编码 / 枚举映射', DATE: '日期格式', DATETIME: '日期时间格式', DECIMAL: '小数位规范', CONCAT: '多字段拼接' };
const transformKinds = { DIRECT: '直接映射', CONSTANT: '常量', REPORTER_CODE: '上报系统单位信用代码', STABLE_GUID: '稳定GUID(业务主键+固定命名空间)', DEFAULT: '空值默认值', TRIM: '去首尾空白', UPPER: '转大写', LOWER: '转小写', DICTIONARY: '字典 / 组织编码 / 枚举映射', DATE: '日期格式', DATETIME: '日期时间格式', DECIMAL: '小数位规范', CONCAT: '多字段拼接' };
const transformVisible = ref(false), transformResource = ref(''), transformTarget = ref<Mapping>(), dictionaryRows = ref<{ source: string; target: string }[]>([]);
const transform = ref<Transform>({ kind: 'DIRECT', argument: '', outputFormat: '', values: {}, sources: [] });
const samples = ref<MappingSample[]>();
@@ -94,8 +124,8 @@ watch(draft, () => { checks.value = undefined; samples.value = undefined; }, { d
async function load() { loading.value = true; failed.value = false; try { const r = (await listPlans(query)).data; rows.value = r.rows; total.value = r.total; } catch { failed.value = true; rows.value = []; total.value = 0; } finally { loading.value = false; } }
function search() { query.pageNum = 1; void load(); }
async function configs(kind: ConfigKind, parentId?: string) { const result: ConfigView[] = []; for (let pageNum = 1; ; pageNum++) { const r = (await listConfigs({ kind, parentId, pageNum, pageSize: 100 })).data; result.push(...r.rows); if (result.length >= r.total) return result; if (!r.rows.length) throw new Error('配置分页读取不完整'); } }
async function choices() { regulators.value = (await configs('DEPARTMENT')).filter(r => r.department?.role === 'REGULATOR'); const all: StandardView[] = []; for (let pageNum = 1; ; pageNum++) { const r = (await listStandards({ keyword: '', pageNum, pageSize: 100 })).data; all.push(...r.rows); if (all.length >= r.total) break; if (!r.rows.length) throw new Error('标准分页读取不完整'); } standards.value = all; }
function reset() { step.value = 0; selectedStandard.value = undefined; sourceFields.value = {}; suggestions.value = {}; checks.value = undefined; datasetOptions.value = []; systems.value = []; topics.value = []; }
async function choices() { regulators.value = (await configs('DEPARTMENT')).filter(r => r.department?.role === 'REGULATOR'); await searchStandards(''); }
function reset() { step.value = 0; selectedStandard.value = undefined; sourceFields.value = {}; suggestions.value = {}; checks.value = undefined; datasetOptions.value = []; datasetError.value = ''; systems.value = []; topics.value = []; }
async function create() { reset(); id.value = crypto.randomUUID(); version.value = -1; draft.value = blankPlan(); await choices(); editing.value = true; visible.value = true; }
async function open(planId: string, edit: boolean) { reset(); const plan = (await getPlan(planId)).data; id.value = plan.id; version.value = plan.version; draft.value = plan.definition; await choices(); systems.value = await configs('SYSTEM', draft.value.regulatorId); topics.value = await configs('TOPIC', draft.value.systemId); selectedStandard.value = (await getStandard(draft.value.standardId)).data; activeResource.value = resources.value[0]?.code || ''; editing.value = edit; visible.value = true; }
async function copy(planId: string) { await open(planId, true); id.value = crypto.randomUUID(); version.value = -1; draft.value.versionLabel = ''; }
@@ -103,10 +133,10 @@ async function regulatorChanged() { draft.value.systemId = ''; draft.value.topic
async function systemChanged() { draft.value.topicId = ''; topics.value = draft.value.systemId ? await configs('TOPIC', draft.value.systemId) : []; }
async function standardChanged() { draft.value.bindings = []; sourceFields.value = {}; suggestions.value = {}; selectedStandard.value = (await getStandard(draft.value.standardId)).data; draft.value.standardVersion = selectedStandard.value.version; activeResource.value = resources.value[0]?.code || ''; }
let datasetRequest = 0;
async function searchDatasets(keyword: string) { const current = ++datasetRequest; datasetLoading.value = true; try { const page = (await listDatasets({ keyword, pageNum: 1, pageSize: 100 })).data; if (current === datasetRequest) { datasetOptions.value = page.rows; if (page.total > 100) ElMessage.info('候选超过 100 项,请输入名称缩小范围'); } } finally { if (current === datasetRequest) datasetLoading.value = false; } }
async function searchDatasets(keyword: string) { const current = ++datasetRequest; datasetLoading.value = true; datasetError.value = ''; try { const page = (await listDatasets({ keyword, pageNum: 1, pageSize: 100 })).data; if (current === datasetRequest) { datasetOptions.value = page.rows; if (page.total > 100) ElMessage.info('候选超过 100 项,请输入名称缩小范围'); } } catch (e) { if (current === datasetRequest) { datasetOptions.value = []; datasetError.value = `数据集候选加载失败:${e instanceof Error ? e.message : '请重试'}。可单独使用业务库直连来源。`; } } finally { if (current === datasetRequest) datasetLoading.value = false; } }
async function bind(code: string, datasetId: string) { if (!datasetId || busy.value) return; if (binding(code) && binding(code)!.mappings.some(m => m.confirmed)) await ElMessageBox.confirm('重新匹配会清除该资源当前的人工确认,是否继续?', '重新匹配', { type: 'warning' }); busy.value = true; try { const result = (await matchFields(draft.value.standardId, code, datasetId)).data; const d = result.dataset; sourceFields.value[code] = d.fields; suggestions.value[code] = result.suggestions; draft.value.bindings = draft.value.bindings.filter(b => b.resourceCode !== code); draft.value.bindings.push({ resourceCode: code, datasetId: d.id, datasetVersion: d.version, releaseId: d.releaseId, schemaVersionId: d.schemaVersionId, schemaSha256: d.schemaSha256, mappings: result.suggestions.map(s => ({ target: s.target, source: s.candidates.length === 1 && s.compatible ? s.candidates[0] : '', confirmed: false })) }); } finally { busy.value = false; } }
function basics() { if (![draft.value.code, draft.value.name, draft.value.versionLabel, draft.value.regulatorId, draft.value.systemId, draft.value.topicId, draft.value.standardId].every(v => v.trim())) { ElMessage.warning('请先填写完整的基础引用'); return false; } return true; }
function next() { if (editing.value && !basics()) return; step.value++; if (step.value === 1 && editing.value) void searchDatasets(''); }
function next() { if (editing.value && !basics()) return; step.value++; for (const b of draft.value.bindings) if (b.directSource) sourceFields.value[b.resourceCode] = b.directSource.fields; }
async function check() { if (!basics()) return; busy.value = true; try { checks.value = (await checkPlan(draft.value)).data; } finally { busy.value = false; } }
async function save() { if (!basics() || busy.value) return; busy.value = true; try { const r = (await savePlan(id.value, version.value, draft.value)).data; version.value = r.version; draft.value = r.definition; ElMessage.success('方案草稿已保存'); await load(); } finally { busy.value = false; } }
async function changeState(planId: string, rowVersion: number, action: 'freeze' | 'disable') { const { value } = await ElMessageBox.prompt(action === 'freeze' ? '冻结后不能原地修改,且不代表已经具备报送执行条件。请填写冻结原因。' : '停用后不得用于新报送,请填写原因。', action === 'freeze' ? '冻结配置版本' : '停用方案', { inputValidator: (v: string) => !!v?.trim() && v.length <= 1000 || '请填写 1—1000 字原因', confirmButtonText: '确认', cancelButtonText: '取消' }); await changePlanState(planId, rowVersion, value, action); ElMessage.success(action === 'freeze' ? '配置版本已冻结' : '方案已停用'); await load(); }
@@ -3,6 +3,17 @@
<el-alert v-if="bound" title="已绑定质量规则固定版本" type="success" :closable="false" class="mb-2" />
<el-input v-else :model-value="modelValue" type="textarea" maxlength="4000" :disabled="disabled" placeholder="未绑定执行方式的文字规则会阻断批次校验" @update:model-value="emit('update:modelValue', $event)" />
<el-button v-hasPermi="['aixun:governance:quality-rule:validate']" class="mt-2" :disabled="disabled" @click="open">选择质量规则</el-button>
<el-button class="mt-2" :disabled="disabled" @click="openLocal">配置报送快照规则</el-button>
<el-dialog v-model="localVisible" title="报送快照规则" width="700px" append-to-body>
<el-alert title="规则在本批次转换后的全部记录上执行;不会先运行通用治理任务。条件值及比较字段应按已核对的规范配置。" type="info" :closable="false" class="mb-3" />
<el-form :disabled="disabled"><div v-for="(rule, index) in localRules" :key="index" class="mb-3">
<el-select v-model="rule.kind"><el-option v-for="(label, kind) in localKinds" :key="kind" :value="kind" :label="label" /></el-select>
<el-input v-if="['DATE_GTE', 'REQUIRED_IF'].includes(rule.kind)" v-model="rule.field" class="mt-2" placeholder="同一资源内的目标字段编码,如 BUILD_TIME" />
<el-select v-if="rule.kind === 'REQUIRED_IF'" v-model="rule.values" class="mt-2" multiple filterable allow-create default-first-option placeholder="触发条件的精确编码,输入后回车" />
<el-button link type="danger" @click="localRules.splice(index, 1)">移除</el-button>
</div><el-button :disabled="localRules.length >= 10" @click="localRules.push({ kind: 'UNIQUE', field: '', values: [] })">添加规则</el-button></el-form>
<template #footer><el-button @click="localVisible = false">取消</el-button><el-button type="primary" :disabled="disabled || !localRules.length" @click="saveLocal">应用规则</el-button></template>
</el-dialog>
<el-button v-if="bound" class="mt-2" :disabled="disabled" @click="clear">解除绑定</el-button>
<el-drawer v-model="visible" title="选择报送质量规则" size="min(950px, 95vw)" append-to-body>
<el-alert title="绑定当前可执行版本;规则变更后须重新确认。源数据质量检查通过后,仍需校验并审核批次内容。" type="info" :closable="false" class="mb-3" />
@@ -21,6 +32,15 @@ import type { RuleVO } from '@/api/datagov/quality-rule/types';
import { resolveQualityReference } from '@/api/datagov/regulatory-reporting/execution';
const props = defineProps<{ modelValue: string; disabled: boolean }>();
const emit = defineEmits<{ 'update:modelValue': [value: string] }>();
type LocalRule = { kind: string; field: string; values: string[] };
const localKinds = { UNIQUE: '本批次字段唯一', DATE_GTE: '日期不早于另一字段', REQUIRED_IF: '条件必填', CREDIT_CODE: '18位信用代码格式', UUID: '36位GUID格式' };
const localVisible = ref(false), localRules = ref<LocalRule[]>([]);
function openLocal() { try { const raw: LocalRule[] = props.modelValue.startsWith('REPORTING:') ? JSON.parse(props.modelValue.slice(10)) : [{ kind: 'UNIQUE', field: '', values: [] }]; if (!Array.isArray(raw) || raw.some(r => !r || !(r.kind in localKinds))) throw new Error('规则无效'); localRules.value = raw.map(r => ({ kind: r.kind, field: r.field || '', values: Array.isArray(r.values) ? r.values : [] })); localVisible.value = true; } catch { ElMessage.error('现有报送规则格式无效,请核对规则内容'); } }
async function saveLocal() {
if (localRules.value.some(r => ['DATE_GTE', 'REQUIRED_IF'].includes(r.kind) && !/^[A-Za-z_][A-Za-z0-9_.-]{0,127}$/.test(r.field) || r.kind === 'REQUIRED_IF' && !r.values.length)) { ElMessage.warning('请填写比较字段和条件编码'); return; }
if (props.modelValue && !props.modelValue.startsWith('REPORTING:')) await ElMessageBox.confirm('以显式报送快照规则替换当前校验规则?请先核对原规则含义。', '确认替换');
emit('update:modelValue', `REPORTING:${JSON.stringify(localRules.value)}`); localVisible.value = false;
}
const bound = computed(() => /^GOVERNANCE:[1-9]\d*:[1-9]\d*:[a-f0-9]{64}$/.test(props.modelValue || ''));
const visible = ref(false), loading = ref(false), binding = ref(false), failed = ref(false), keyword = ref(''), page = ref(1), size = ref(20), total = ref(0), rules = ref<RuleVO[]>([]);
async function open() { visible.value = true; page.value = 1; await load(); }
@@ -0,0 +1,14 @@
-- 达梦现有DataGov专属schema增量282;需已完成279、280、281。
-- 客户端设置遇错停止。已存在或部分执行时先核对表和安装记录,不可盲目重跑。
CREATE TABLE dg_reporting_plan_source (
organization_id BIGINT NOT NULL,
plan_id VARCHAR(36 CHAR) NOT NULL,
resource_code VARCHAR(128 CHAR) NOT NULL,
binding_json CLOB NOT NULL,
PRIMARY KEY (organization_id,plan_id,resource_code),
CONSTRAINT fk_reporting_plan_source FOREIGN KEY (organization_id,plan_id) REFERENCES dg_reporting_plan(organization_id,plan_id)
);
INSERT INTO dg_dm_install_step(step_key,sha256,state,error_code) VALUES('dg_reporting_plan_source:dg_reporting_plan_source','a167a7da76d97e62de603a7aafa7d669e2acf00114b4b48084043092436aa22c','SUCCESS',NULL);
COMMIT;
SELECT step_key,state FROM dg_dm_install_step WHERE step_key='dg_reporting_plan_source:dg_reporting_plan_source';
SELECT COUNT(*) AS direct_binding_rows FROM dg_reporting_plan_source;
+11 -1
查看文件
@@ -1,5 +1,5 @@
-- Fresh-install DM schema; target 8.4.4.80 Pack89.
-- Source fingerprint: 3db4b6f515d7e8c9a42ce80ca635be6417aa9b26bdf7e64897063b9068be9dab
-- Source fingerprint: fe478bb2dc0d7a7f1d9acb605b241d36af7d34892de751f14b96d5c7a8759dc7
-- @statement sys_social
CREATE TABLE sys_social (
id bigint not null comment '主键',
@@ -20848,3 +20848,13 @@ CREATE TABLE dg_reporting_artifact (
-- @statement dg_reporting_artifact
CREATE UNIQUE INDEX uk_reporting_artifact_operation ON dg_reporting_artifact(operation_key);
-- @statement dg_reporting_plan_source
CREATE TABLE dg_reporting_plan_source (
organization_id BIGINT NOT NULL,
plan_id VARCHAR(36 CHAR) NOT NULL,
resource_code VARCHAR(128 CHAR) NOT NULL,
binding_json CLOB NOT NULL,
PRIMARY KEY (organization_id,plan_id,resource_code),
CONSTRAINT fk_reporting_plan_source FOREIGN KEY (organization_id,plan_id) REFERENCES dg_reporting_plan(organization_id,plan_id)
);
+4
查看文件
@@ -1102,3 +1102,7 @@ migrations:
ownerUnit: integration
path: db/migration/integration/V20261130.281__create_reporting_execution.sql
sha256: 0f4552ba031b2696c13627f37aef5857ff4d92711fcf0eb4e3f8c77e32080720
- version: '20261201.282'
ownerUnit: integration
path: db/migration/integration/V20261201.282__create_reporting_direct_source.sql
sha256: 61e51dbda60bf28e726b89253d55030a5d73652a6f9e33483254498eff3b752a
@@ -0,0 +1,9 @@
-- Direct reporting bindings are separate from published dataset references.
CREATE TABLE dg_reporting_plan_source (
organization_id BIGINT NOT NULL,
plan_id VARCHAR(36) NOT NULL,
resource_code VARCHAR(128) NOT NULL,
binding_json LONGTEXT NOT NULL,
PRIMARY KEY (organization_id,plan_id,resource_code),
CONSTRAINT fk_reporting_plan_source FOREIGN KEY (organization_id,plan_id) REFERENCES dg_reporting_plan(organization_id,plan_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
@@ -0,0 +1,69 @@
# 科创直连报送修改(2026-12-01)
结论:PASS_WITH_LIMITATION。已修复列表和标准候选,增加报送自有直连来源、快照校验与报文命名配置,统一采集资源权限策略。B接口真实提交、企业DS核验及委端状态未完成,不能宣称科创直连上报闭环通过。
依据:用户提供的《科创系统直连国资委上报_修改需求与验收清单_20261201.md》。本次在现有源码上修改,保留11月30日未提交实现;没有使用Git、修改源业务数据或更新线上两个应用节点。附件中的外部核验结论作为待复测基线,不当作本机已验证结果。
## 实际修改
| 需求 | 实现与边界 |
| --- | --- |
| R01 | 标准、方案空/缺省/规范化空白关键词不追加INSTR;名称/编码搜索仍绑定参数,百分号和下划线保持字面含义;COUNT与分页共用组织及搜索条件,排序不变。模块配置列表已具备同类保护,无需重复改写。 |
| R02 | 标准列表增加严格校验的status参数;方案候选请求PUBLISHED,远程搜索、每页50条及继续加载,区分加载错误与无候选。详情仍保留已保存固定版本,选定后读取该版本结构;保存及冻结再次在后端验证状态和版本。 |
| R03 | 新增业务库/中间库来源选择器,复用已有数据源和受管连接;定义独立于已发布数据集,不要求先采集入仓、发布资产或运行画像。最多5表、200个输出字段,结构化LEFT JOIN、字段别名、参数绑定过滤;不开放任意SQL。关联右字段须能核实单列唯一约束,否则拒绝;缺失关联由目标必填检查报错。来源结构、连接版本、固定定义、过滤和授权证据随批次及私有快照保存。 |
| R04 | 复用字典换码及严格日期转换;增加快照字段唯一、日期先后、条件必填、18位信用代码格式、36位GUID检查;增加从上报系统取单位信用代码和稳定GUID转换。超长错误说明实际262/上限255,不截断值;重复主键标出全部相关记录。任务支持IN/NOT_IN集合,可明确选单条或多条。批次显示逐条失败数量,保留所有选中记录;批次级阻断存在时不宣称其余记录通过。 |
| R05部分 | 系统配置增加单位信用代码、接口代号,明确接口报文版本与内部标准版本分离。新批次固定时间、32位包编号和报文命名信息;配置完整时生成“单位_接口_版本_时间_包编号.zip”和“单位_资源_版本_时间_包编号.xml”,ZIP根目录为XML。尚无提交按钮或实际B接口网络调用,未绑定真实凭据、接收结果或DS查询能力。 |
| R06调查 | 文中两个错误编号未在本机DataProduct近48小时日志找到。现有来源候选查询已在专属达梦schema只读预编译成功,不能据此证明线上运行正常,也没有依据随意改该SQL。直连来源不调用资产/数据集候选接口;数据集候选失败单独提示,不阻断直连配置。 |
| R07 | StorageResourceService、StorageTableFileReferenceDirectory、LakehouseTableFileReferenceDirectory的采集入口与查看入口统一使用LoginHelper对可信服务端actorId的超级管理员判定;资源ID、组织和普通用户拒绝规则不变,未改历史create_dept。同步预检、资源解析及异步调用复用相同Owner方法,原有执行身份核验保持。 |
## 配置方式与限制
1. 新建方案先选择已发布标准;在“取数与映射”选择已有业务源/中间库,指定库、Schema、表或视图、输出字段。需要关联时指定左表字段和右表唯一字段;当前不支持任意SQL、跨数据源关联或无法核实唯一性的关联视图。
2. 来源权限复用当前组织的数据源范围,以及报送查看、数据源浏览和预览权限。受保护/非标量字段拒绝读取,权限撤销、结构或连接版本变化会拒绝新读取及旧文件访问。既有授权数据集路径的行过滤、脱敏和权限复核保持。
3. 数据源支持范围沿用当前JDBC对象浏览的已启用类型,新增直连路径排除Hive和MariaDB;单表沿用128字段元数据上限。单次完整取数最多100000条、8 MB,单字段最多100万字符,超限整次失败;5条样例不能用于生成快照。真实各数据库连通与实际科创数据读取仍NOT_RUN。
4. 映射字典须由已核对资料逐项配置;未命中报错,不回退源编码。当前未取得39项完整映射、企业关联定义和多值编码规范,因此没有伪造科创专用预置,也没有声称实际9条候选已全部通过平台检查。
5. 字段规则中选择“配置报送快照规则”,支持UNIQUE、DATE_GTE、REQUIRED_IF、CREDIT_CODE、UUID。保存形式为显式REPORTING规则数组;同样允许在填写规则中使用该受限规则格式。不自动把自然语言转成规则;未绑定的填写说明或外部字典仍会阻断,需按规范完成配置。信用代码检查是18位字符格式,不声称完成国家登记真实性核验。
6. EXT_REPORTSOCIALCODE可映射为“上报系统单位信用代码”。EXT_GUID可保留源系统稳定GUID,或选择稳定GUID转换,使用稳定业务主键和长期不变的命名空间;不以批次或时间生成每次变化的记录GUID。EXT_DATAFLAG仍需按真实新增/修改/删除配置并核对目标端已有记录。
7. 包时间格式为北京时间uuuuMMddHHmmss;包编号使用批次UUID去连字符,既有批次重生成不换编号。上报系统字段为空的旧批次保留既有命名兼容;配置完整的新批次使用规范命名。真实文件名规则仍须与待提供的原始接口规范核对,不以命名通过代替受理通过。
8. 提交时机仍未开放;不自动发送试报、重试未知结果或虚构DS接口。XML/ZIP仍来自已审核快照,生成不重新读取业务库内容。
## 数据库与制品
新增迁移282:dg_reporting_plan_source,保存直连资源定义及映射JSON;主键为组织、方案、资源,外键引用既有方案。无数据回填、菜单/角色变更或旧表删除。系统新增配置和冻结报文信息存既有JSON字段,不另加列。
- 源迁移:db/migration/integration/V20261201.282__create_reporting_direct_source.sql。
- 达梦部署SQL:db/dameng/increments/V20261201.282__reporting_direct_source.sql;依赖279—281和既有安装记录表。只执行此增量,不能将全新安装schema用于升级。已执行或部分完成必须先对账。
- 当前后端构建:aixun-modules/aixun-integration/target/aixun-integration.jar、aixun-modules/aixun-dataops/target/aixun-dataops.jar。
- 前端构建:aixun-ui/dist/。
- 本次未改DataProduct、Governance、Resource服务源码或共享RPC契约;11月30日的交接目录仍是此前有效版本,未用新文件混写旧包。
## 验证
- PASS:139项定向后端测试(Integration 129、DataOps 10),零失败/错误/跳过。覆盖报送旧流程、特殊字符、版本与权限拒绝、直连查询参数化、关联唯一约束、长文本完整保留、快照规则及普通/管理员资源范围。最初测试误用旧管理员ID的夹具已改为项目真实常量;实现未通过放宽普通用户范围处理。
- PASS:ReportingDamengListTest在真实达梦执行实际服务生成的列表SQL;使用只读CTE构造105个已发布版本、草稿、停用及跨组织条目,无DDL/DML。验证缺省/空/全空白关键词、名称/编码/特殊字符、COUNT与分页、稳定排序、第二页之后的已发布候选,并复现旧空关键词返回0的行为。
- PASS:受影响前端lint。全局vue-tsc有其他目录既有111项错误,报送目录0项,整体类型检查仍为PASS_WITH_LIMITATION。
- PASS:Integration、DataOps合并package。前端首次构建发现新组件多根节点,已改为单根容器后重新生产构建。
- SQL:迁移目录摘要、全新基线与增量DDL/安装记录一致性已核对;未执行迁移。未以只读预编译宣称业务查询结果通过。
- NOT_RUN:本次本地/线上部署、线上两个节点一致性、Browser/多账号人工UAT、真实10条科创来源读取及文件链、真实B接口受理、企业DS/委端入库核验。
主要命令:script/quality/check.sh --backend指定Reporting*Test及StorageTableFileReferenceDirectoryTest、StorageResourceServiceTest、UnifiedIngestionLayerActorTest;真实达梦测试通过script/database/with-dameng-env.py加载本项目私有配置;前端定向--frontend及--frontend-build;Maven Wrapper合并两服务package -DskipTests。私有配置内容不写入交付记录。
## 待补材料与剩余工作
附件目录只有本需求文件,未找到文中引用的B接口操作文档、接口规范、完整业务字典、来源关联及核验证据,已向用户询问本机路径或链接。
- R04实际科创配置及验收:需要完整39项换码、企业关联字段和唯一性、目标条件必填触发值及允许多值格式、正式模板和可授权使用的源库。不能仅凭6项例子补齐剩余映射。
- R05仍有开发与联调:确认file/RESCODE/Ver/USER/PASSWORD实际位置和编码后,实现受管凭据解析/审计、提交状态机、HTTP与serviceFlag分别记录、超时UNKNOWN及原请求对账、人工DS证据记录。需要实际测试接收配置和目标主键/已有记录核对;未完成不能全部归因于缺凭据。
- R06根因定位:需要节点41、42对应错误编号的脱敏日志及制品/数据库基线;本机没有相应现场证据,未擅自修改线上环境。
## 部署与恢复
本次仅源码修改、检查和构建,没有应用迁移或替换运行容器。部署时先核对并执行282,再配套更新Integration、DataOps和前端。保留既有配置、网络、挂载、源库数据及文件引用;远端双节点须分别验证。恢复优先前向修复,必要时使用此前有效应用制品,保留新表及批次;旧程序不能处理新直连方案/批次,不得删表或删除业务文件来回退。
## 当前未提交变更部署文件
按用户2026-12-01“未提交的更新代码”请求,以当前HEAD `4d8c05e`核对已暂存、未暂存及未跟踪源码;此前279—281及其他服务实现已进入提交基线。本次完整增量只有Integration、DataOps、前端及282,不按此前交付目录推定范围。
交付目录:`deliverables/20261201-当前未提交变更部署包/`。仅包含`aixun-integration.jar`、`aixun-dataops.jar`、完整`dist/`及`SQL/V20261201.282__reporting_direct_source.sql`;共1619文件、约364.6 MiB。未放源码、日志、校验文件、全新安装schema或未变更服务。目标库须已完成279—281,282新增一张直连来源定义表及安装记录。
制品核对PASS:复用本次已成功构建的两个可执行JAR及前端生产构建,源码时间早于构建;JAR归档完整、启动入口及变更类与当前编译输出一致,交付JAR、dist全部1616文件和SQL与当前输出/源文件逐项一致。打包前后37项源码及数据库输入内容、HEAD均未变化。未重复运行无输入变化的构建或测试;部署、迁移执行及实际业务验收仍NOT_RUN。此前11月30日交付目录保留作为已有交付/恢复引用,没有混写。