From 015e11cd95342be0bc0fc04fc30b9e1929a12555 Mon Sep 17 00:00:00 2001 From: zhanghao <774378400@qq.com> Date: Wed, 18 Nov 2026 14:17:38 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=94=AF=E6=8C=81=E5=9C=A8=E6=95=B0?= =?UTF-8?q?=E6=A8=A1=E4=B8=8A=E9=80=89=E7=89=B9=E5=BE=81=E8=87=AA=E5=8A=A8?= =?UTF-8?q?=E6=98=A0=E5=B0=84=E5=88=B0=E7=82=B9=E4=BA=91=EF=BC=8C=E5=BD=A2?= =?UTF-8?q?=E4=BD=8D=E5=85=AC=E5=B7=AE=E7=B1=BB=E5=9E=8B=E4=B9=9F=E6=B7=BB?= =?UTF-8?q?=E5=8A=A0=E4=BA=86=EF=BC=8C=E6=94=AF=E6=8C=81=E4=BA=86=E8=AE=BE?= =?UTF-8?q?=E7=BD=AE=E5=9F=BA=E5=87=86=EF=BC=8C=E5=A4=84=E7=90=86=E5=90=8E?= =?UTF-8?q?=E7=82=B9=E4=BA=91=E4=B9=9F=E6=94=AF=E6=8C=81=E5=AF=BC=E5=87=BA?= =?UTF-8?q?stl?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../freescan/018_inspection_cad_features.sql | 22 + .../service/impl/EdgeSystemServiceImpl.java | 1 + .../inspection/LabFeaturePlanController.java | 23 + .../inspection/LabInspectionController.java | 20 +- .../inspection/LabComparisonResults.java | 44 +- .../LabDimensionComparisonService.java | 33 +- .../inspection/LabFeaturePlanService.java | 92 + .../inspection/LabInspectionGateway.java | 18 +- am-web/package.json | 1 + am-web/pnpm-lock.yaml | 51 + am-web/src/api/lab/inspection/index.ts | 53 +- am-web/src/utils/inspectionPresentation.ts | 97 + .../views/lab/dimension/ComparisonPanel.vue | 584 ++++- .../lab/dimension/comparisonReadiness.mjs | 86 +- .../views/lab/inspection/CadFeatureViewer.vue | 465 ++++ .../views/lab/inspection/CadSectionPicker.vue | 197 ++ .../lab/inspection/FeatureDatumEditor.vue | 123 + .../lab/inspection/FeatureGeometryEditor.vue | 107 + .../lab/inspection/FeatureTemplateManager.vue | 885 +++++++ .../lab/inspection/GeneralToleranceEditor.vue | 165 ++ .../lab/inspection/InspectionCleanup.vue | 146 +- .../lab/inspection/InspectionFeatures.vue | 2055 +++++++++++++++++ .../lab/inspection/InspectionWorkbench.vue | 535 ++++- .../inspection/LegacyInspectionTemplates.vue | 540 +++++ .../lab/inspection/MeasurementParameters.vue | 272 +++ .../lab/inspection/ProcessedStlDownload.vue | 59 + .../views/lab/inspection/datumSelection.ts | 86 + am-web/src/views/lab/inspection/display.ts | 2 + .../lab/inspection/featurePresentation.ts | 206 ++ am-web/src/views/lab/inspection/geometry.ts | 31 + .../lab/inspection/measurementOptions.ts | 223 ++ .../src/views/lab/inspection/stlDownload.ts | 43 + am-web/src/views/lab/inspection/templates.vue | 544 +---- .../RELEASE-20261118-cad-inspection.md | 66 + scripts/bootstrap_db.py | 2 +- scripts/bootstrap_standalone.py | 2 +- scripts/cleanup_verification.py | 19 +- 37 files changed, 7090 insertions(+), 808 deletions(-) create mode 100644 am-backend/sql/freescan/018_inspection_cad_features.sql create mode 100644 am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/controller/admin/inspection/LabFeaturePlanController.java create mode 100644 am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/inspection/LabFeaturePlanService.java create mode 100644 am-web/src/utils/inspectionPresentation.ts create mode 100644 am-web/src/views/lab/inspection/CadFeatureViewer.vue create mode 100644 am-web/src/views/lab/inspection/CadSectionPicker.vue create mode 100644 am-web/src/views/lab/inspection/FeatureDatumEditor.vue create mode 100644 am-web/src/views/lab/inspection/FeatureGeometryEditor.vue create mode 100644 am-web/src/views/lab/inspection/FeatureTemplateManager.vue create mode 100644 am-web/src/views/lab/inspection/GeneralToleranceEditor.vue create mode 100644 am-web/src/views/lab/inspection/InspectionFeatures.vue create mode 100644 am-web/src/views/lab/inspection/LegacyInspectionTemplates.vue create mode 100644 am-web/src/views/lab/inspection/MeasurementParameters.vue create mode 100644 am-web/src/views/lab/inspection/ProcessedStlDownload.vue create mode 100644 am-web/src/views/lab/inspection/datumSelection.ts create mode 100644 am-web/src/views/lab/inspection/featurePresentation.ts create mode 100644 am-web/src/views/lab/inspection/measurementOptions.ts create mode 100644 am-web/src/views/lab/inspection/stlDownload.ts create mode 100644 deploy/windows11/RELEASE-20261118-cad-inspection.md diff --git a/am-backend/sql/freescan/018_inspection_cad_features.sql b/am-backend/sql/freescan/018_inspection_cad_features.sql new file mode 100644 index 0000000..c5edb96 --- /dev/null +++ b/am-backend/sql/freescan/018_inspection_cad_features.sql @@ -0,0 +1,22 @@ +-- Additive, repeatable migration. Execute before starting the new Java service. +-- Existing template, scan and immutable report tables are unchanged. +CREATE TABLE IF NOT EXISTS lab_inspection_feature_plan ( + tenant_id BIGINT NOT NULL, + scan_id VARCHAR(32) NOT NULL, + revision INT NOT NULL, + definition_json LONGTEXT NOT NULL, + evaluation_json LONGTEXT NULL, + update_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + PRIMARY KEY (tenant_id, scan_id) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; +CREATE TABLE IF NOT EXISTS lab_inspection_feature_template ( + id VARCHAR(32) NOT NULL, + tenant_id BIGINT NOT NULL, + name VARCHAR(100) NOT NULL, + revision INT NOT NULL DEFAULT 1, + definition_json LONGTEXT NOT NULL, + creator VARCHAR(64) NOT NULL DEFAULT '', + create_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + update_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + PRIMARY KEY (id), KEY idx_tenant_name (tenant_id, name) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; diff --git a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/edge/client/service/impl/EdgeSystemServiceImpl.java b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/edge/client/service/impl/EdgeSystemServiceImpl.java index 637e2f5..d166c09 100644 --- a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/edge/client/service/impl/EdgeSystemServiceImpl.java +++ b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/edge/client/service/impl/EdgeSystemServiceImpl.java @@ -113,6 +113,7 @@ public class EdgeSystemServiceImpl implements EdgeSystemService { request.getRobotId(), SystemServiceGrpc.SystemServiceBlockingStub.class); stub = stub.withDeadlineAfter((totalTimeoutMs == 0 ? ActionQueueTimeouts.SERVER_DEFAULT_TIMEOUT_MS : totalTimeoutMs) + 5000L, TimeUnit.MILLISECONDS); return stub.executeActionQueue(builder.build()); + } @Override diff --git a/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/controller/admin/inspection/LabFeaturePlanController.java b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/controller/admin/inspection/LabFeaturePlanController.java new file mode 100644 index 0000000..0bca7a0 --- /dev/null +++ b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/controller/admin/inspection/LabFeaturePlanController.java @@ -0,0 +1,23 @@ +package cn.iocoder.yudao.module.lab.controller.admin.inspection; +import cn.iocoder.yudao.module.lab.service.inspection.LabFeaturePlanService; +import cn.iocoder.yudao.framework.common.pojo.CommonResult; +import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder; +import jakarta.annotation.Resource; +import org.springframework.web.bind.annotation.*; +import org.springframework.security.access.prepost.PreAuthorize; +import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId; + +@RestController @RequestMapping("/lab/inspection/feature-templates") +public class LabFeaturePlanController { + @Resource private LabFeaturePlanService service; + @GetMapping @PreAuthorize("@ss.hasPermission('lab:task:query') or @ss.hasPermission('lab:result:query')") + public CommonResult list(){return CommonResult.success(service.templates(TenantContextHolder.getRequiredTenantId()));} + @GetMapping("/{id}") @PreAuthorize("@ss.hasPermission('lab:task:query') or @ss.hasPermission('lab:result:query')") + public CommonResult get(@PathVariable String id) throws Exception{return CommonResult.success(service.template(TenantContextHolder.getRequiredTenantId(),id));} + @PostMapping @PreAuthorize("@ss.hasPermission('lab:result:confirm')") + public CommonResult save(@RequestBody LabFeaturePlanService.Save body) throws Exception{return CommonResult.success(service.saveTemplate(TenantContextHolder.getRequiredTenantId(),body,String.valueOf(getLoginUserId())));} + @DeleteMapping("/{id}") @PreAuthorize("@ss.hasPermission('lab:result:confirm')") + public CommonResult delete(@PathVariable String id,@RequestParam int revision){service.delete(TenantContextHolder.getRequiredTenantId(),id,revision);return CommonResult.success(true);} + @ExceptionHandler(org.springframework.web.server.ResponseStatusException.class) + public CommonResult error(org.springframework.web.server.ResponseStatusException error){return CommonResult.error(error.getStatusCode().value(),error.getReason());} +} diff --git a/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/controller/admin/inspection/LabInspectionController.java b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/controller/admin/inspection/LabInspectionController.java index 72f109a..cfa45d1 100644 --- a/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/controller/admin/inspection/LabInspectionController.java +++ b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/controller/admin/inspection/LabInspectionController.java @@ -26,6 +26,7 @@ public class LabInspectionController { @Resource private LabInspectionRepository repository; @Resource private LabDimensionComparisonService comparisons; @Resource private LabInspectionTemplateService templates; + @Resource private LabFeaturePlanService featurePlans; @Resource private DimensionService dimensions; @Resource private SecurityFrameworkService security; @Resource private JdbcTemplate jdbc; @@ -51,9 +52,11 @@ public class LabInspectionController { Map job=engine==null?null:comparisons.engineJob(engine,method.equals("POST")); boolean binary=path.contains("/files/")||path.matches("/api/plan/templates/[a-zA-Z0-9_.-]+"); if(binary&&!security.hasPermission("lab:data:download"))throw new ResponseStatusException(HttpStatus.FORBIDDEN,"没有文件下载权限"); - if(binary&&job!=null&&job.get("delivery_id")!=null) { + if(binary&&job!=null) { String name=path.substring(path.lastIndexOf('/')+1); if(Set.of("report_signed_chromatogram.pdf","report.pdf","platform-result.stl").contains(name)) { + if(!"ARCHIVED".equals(job.get("status"))||job.get("delivery_id")==null||job.get("awaiting_revision")!=null) + throw new ResponseStatusException(HttpStatus.CONFLICT,"当前成果尚未完成归档,请等待归档完成或重试成果归档后下载"); long tenant=TenantContextHolder.getRequiredTenantId(); var delivery=jdbc.queryForMap("SELECT stl_id,pdf_id FROM lab_dimension_delivery WHERE id=? AND tenant_id=? AND deleted=0",job.get("delivery_id"),tenant); var file=dimensions.download(((Number)delivery.get(name.endsWith(".stl")?"stl_id":"pdf_id")).longValue()); @@ -63,14 +66,23 @@ public class LabInspectionController { } byte[] body=new byte[0]; if(method.equals("POST")) { - body=request.getInputStream().readNBytes(2*1024*1024+1);if(body.length>2*1024*1024)throw new ResponseStatusException(HttpStatus.PAYLOAD_TOO_LARGE,"检测计划请求内容过多"); + int limit=path.contains("/feature-")?32*1024*1024:2*1024*1024; + body=request.getInputStream().readNBytes(limit+1);if(body.length>limit)throw new ResponseStatusException(HttpStatus.PAYLOAD_TOO_LARGE,"检测计划请求内容过多"); if(path.endsWith("/plan/template")) { @SuppressWarnings("unchecked") Map parameters=mapper.readValue(body,Map.class); String chosen=Objects.toString(parameters.get("template_id"),"");parameters.remove("plan_template_snapshot"); if(chosen.startsWith("managed-"))parameters.put("plan_template_snapshot",templates.snapshot(TenantContextHolder.getRequiredTenantId(),chosen.substring(8))); body=mapper.writeValueAsBytes(parameters); } - if(engine!=null)comparisons.beginMutation(engine,path.substring(("/api/tasks/"+engine+"/").length())); + if(path.endsWith("/feature-template")) { + @SuppressWarnings("unchecked") Map parameters=mapper.readValue(body,Map.class); + if(!(parameters.get("definition") instanceof Map definition))throw new ResponseStatusException(HttpStatus.BAD_REQUEST,"请选择有效的特征模板"); + parameters.put("definition",featurePlans.templateDefinition(definition));body=mapper.writeValueAsBytes(parameters); + } + if(engine!=null) { + @SuppressWarnings("unchecked") Map parameters=body.length==0?Map.of():mapper.readValue(body,Map.class); + comparisons.beginMutation(engine,path.substring(("/api/tasks/"+engine+"/").length()),parameters); + } } java.net.http.HttpResponse upstream; try{upstream=gateway.forward(path,method,body);}catch(ResponseStatusException failure) { @@ -81,6 +93,8 @@ public class LabInspectionController { var json=repository.scan(TenantContextHolder.getRequiredTenantId(),engine).get("plan_json"); if(json!=null)return CommonResult.success(mapper.readValue(json.toString(),Object.class)); } + if(method.equals("GET")&&path.endsWith("/feature-plan")&&engine!=null&&failure.getStatusCode().value()>=500) + return CommonResult.success(featurePlans.saved(TenantContextHolder.getRequiredTenantId(),engine)); throw failure; } if(binary&&upstream.statusCode()<400) { diff --git a/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/inspection/LabComparisonResults.java b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/inspection/LabComparisonResults.java index 6c48005..0077749 100644 --- a/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/inspection/LabComparisonResults.java +++ b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/inspection/LabComparisonResults.java @@ -12,8 +12,10 @@ import java.util.zip.ZipFile; public class LabComparisonResults { @Resource private LabInspectionGateway gateway; @Resource private LabInspectionProperties settings; + private final com.fasterxml.jackson.databind.ObjectMapper mapper=new com.fasterxml.jackson.databind.ObjectMapper(); private static final long RESERVE=512L*1024*1024; - public record Pair(Path mesh,Path report,Path directory) implements AutoCloseable { + public record Pair(Path mesh,Path report,Path directory,Map featureDocument) implements AutoCloseable { + public Pair(Path mesh,Path report,Path directory){this(mesh,report,directory,Map.of());} @Override public void close() throws IOException { try(var paths=Files.list(directory)){for(Path path:paths.toList())Files.deleteIfExists(path);}Files.deleteIfExists(directory); } @@ -48,6 +50,14 @@ public class LabComparisonResults { boolean success=false; try { Set names=new LinkedHashSet<>();declaredMeshNames(state,names); + if(names.isEmpty()&&state.get("stl_export") instanceof Map export&&"done".equals(export.get("status"))) { + names.add("cleaned_source.stl"); + } + if(names.size()==1&&names.contains("cleaned_source.stl")) { + if(!(state.get("stl_export") instanceof Map export)||!"done".equals(export.get("status")))throw new IOException("处理后STL尚未就绪,请重新生成"); + Object input=export.get("input_revision"); + if((input instanceof Number||input instanceof String text&&text.matches("[0-9]{1,10}"))&&!Objects.toString(input).equals(Objects.toString(state.get("revision"))))throw new IOException("处理后STL版本已变化,请重新生成"); + } if(names.size()==1)mesh=download(engineId,names.iterator().next(),directory.resolve("result.stl")); pdf=download(engineId,"report_signed_chromatogram.pdf",directory.resolve("report.pdf")); if(pdf==null)pdf=download(engineId,"report.pdf",directory.resolve("report.pdf")); @@ -73,9 +83,39 @@ public class LabComparisonResults { if(mesh==null||pdf==null)throw new IOException("计算服务尚未返回成套的处理后STL和PDF;可在工作区检查输出后重试归档"); try(var in=Files.newInputStream(pdf)){if(!new String(in.readNBytes(5),java.nio.charset.StandardCharsets.US_ASCII).equals("%PDF-"))throw new IOException("计算服务返回的PDF内容无效");} validateMesh(mesh); - success=true;return new Pair(mesh,pdf,directory); + if(names.size()==1&&names.contains("cleaned_source.stl"))verifyProcessedExport(engineId,state); + Map featureDocument=publishedFeatures(engineId,state); + success=true;return new Pair(mesh,pdf,directory,featureDocument); } finally {if(!success)new Pair(mesh,pdf,directory).close();} } + private void verifyProcessedExport(String engine,Map before) throws IOException { + String path="/api/tasks/"+engine; + Object value=gateway.json(path,"GET",gateway.forward(path,"GET",new byte[0])); + if(!(value instanceof Map after)||!(before.get("stl_export") instanceof Map expected) + ||!(after.get("stl_export") instanceof Map current)||!"done".equals(current.get("status")) + ||!Objects.equals(expected.get("input_revision"),current.get("input_revision")) + ||!Objects.equals(before.get("revision"),after.get("revision")) + ||!LabInspectionGateway.revision(before).equals(LabInspectionGateway.revision(after))) + throw new IOException("处理后STL输入或报告版本在下载期间已变化,请重新生成并归档"); + } + private Map publishedFeatures(String engine,Map state) throws IOException { + if(state.get("feature_evaluation")==null&&state.get("result_snapshot_id")==null)return Map.of(); + var response=gateway.forward("/api/tasks/"+engine+"/files/feature_results.json","GET",new byte[0]); + try(var input=response.body()) { + if(response.statusCode()>=400)throw new IOException("报告特征快照尚未就绪,暂不能归档"); + byte[] bytes=input.readNBytes(32*1024*1024+1); + if(bytes.length>32*1024*1024)throw new IOException("报告特征快照过大,暂不能归档"); + Map graph=mapper.readValue(bytes,new com.fasterxml.jackson.core.type.TypeReference<>(){}); + if(!"mm".equals(graph.get("unit"))||!(graph.get("features") instanceof List)||!(graph.get("controls") instanceof List)||!(graph.get("datum_systems") instanceof List)||"stale".equals(graph.get("evaluation_state"))) + throw new IOException("报告特征快照无效或已经失效,暂不能归档"); + String expected=Objects.toString(state.get("result_snapshot_id"),""); + if(!expected.isBlank()&&(!(graph.get("result_snapshot") instanceof Map identity)||!expected.equals(identity.get("id")))) + throw new IOException("报告测量快照版本不一致,等待重新同步"); + if(graph.get("report_revision")!=null&&!graph.get("report_revision").toString().equals(LabInspectionGateway.revision(state))) + throw new IOException("报告与特征快照成果版本不一致"); + return graph; + } + } private static void validateMesh(Path mesh) throws IOException { long size=Files.size(mesh); try(var file=new RandomAccessFile(mesh.toFile(),"r")) { diff --git a/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/inspection/LabDimensionComparisonService.java b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/inspection/LabDimensionComparisonService.java index 9a66525..4dda1e5 100644 --- a/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/inspection/LabDimensionComparisonService.java +++ b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/inspection/LabDimensionComparisonService.java @@ -29,6 +29,7 @@ public class LabDimensionComparisonService { @Resource private LabInspectionGateway gateway; @Resource private LabInspectionRepository repository; @Resource private LabInspectionTemplateService templates; + @Resource private LabFeaturePlanService featurePlans; @Resource private LabComparisonResults results; @Resource private ObjectMapper mapper; private final Semaphore submissions=new Semaphore(2); @@ -89,17 +90,26 @@ public class LabDimensionComparisonService { options.put("source_clean",req.isSourceClean()?"1":"0");options.put("review_cleanup",!req.isSourceClean()&&req.isReviewCleanup()?"1":"0"); options.put("cleanup_options",mapper.writeValueAsString(req.getCleanupOptions())); var drawing=input.files().get("drawing"); - var snapshot=templates.resolveUpload(tenant(),req.getPlanTemplateId(),input.files().get("target").name(),drawing==null?"":drawing.name()); - if(snapshot==null)throw bad("请选择已维护且启用的检测计划"); options.put("selected_template_id",req.getPlanTemplateId()); options.put("plan_template_id","cad-geometry"); - options.put("plan_template_snapshot",mapper.writeValueAsString(snapshot)); + if(req.getPlanTemplateId().startsWith("feature-")) { + var snapshot=featurePlans.template(tenant(),req.getPlanTemplateId().substring(8)); + if(!(snapshot.get("definition") instanceof Map definition)||Boolean.FALSE.equals(definition.get("enabled"))||!(definition.get("controls") instanceof List controls)||controls.isEmpty()) + throw bad("请选择已维护且启用的 CAD 特征计划"); + if(!gateway.health().containsKey("feature_capabilities"))throw bad("CAD 特征计划需要新版检测 EXE,请安装后刷新状态"); + options.put("feature_template_id",req.getPlanTemplateId().substring(8)); + options.put("feature_template_snapshot",mapper.writeValueAsString(snapshot)); + } else { + var snapshot=templates.resolveUpload(tenant(),req.getPlanTemplateId(),input.files().get("target").name(),drawing==null?"":drawing.name()); + if(snapshot==null)throw bad("请选择已维护且启用的检测计划"); + options.put("plan_template_snapshot",mapper.writeValueAsString(snapshot)); + } return options; } private record Intent(Map job,DimensionService.ComparisonInput input,Map options,boolean created) {} public Map start(Start req) { tenant();dimensions.checkComparisonAccess(req.getTaskId(),req.getUnitId(),"",false); - if(req.getPlanTemplateId()==null||!req.getPlanTemplateId().startsWith("managed-")||req.getPlanTemplateId().length()<=8) + if(req.getPlanTemplateId()==null||!req.getPlanTemplateId().matches("(?:managed-|feature-)[a-f0-9]{32}")) throw bad("请选择已维护且启用的检测计划,不能使用默认自动匹配或空计划"); if(!Boolean.TRUE.equals(gateway.health().get("available")))throw new ResponseStatusException(HttpStatus.SERVICE_UNAVAILABLE,"本机计算服务未就绪,请启动检测EXE后重试"); if(!submissions.tryAcquire())throw new ResponseStatusException(HttpStatus.TOO_MANY_REQUESTS,"当前比对提交较多,请稍后重试"); @@ -148,9 +158,14 @@ public class LabDimensionComparisonService { }finally{submissions.release();} } public void beginMutation(String engine,String action) { + beginMutation(engine,action,Map.of()); + } + public void beginMutation(String engine,String action,Map parameters) { var job=engineJob(engine,true); - if(action.equals("binding-proposals"))return; - jdbc.update("UPDATE lab_dimension_comparison SET awaiting_revision=COALESCE(awaiting_revision,COALESCE(engine_revision,'')),status='PROCESSING',last_error=NULL WHERE id=? AND tenant_id=?",job.get("id"),tenant()); + if(action.equals("binding-proposals")||action.equals("feature-proposals")&&!"apply".equals(parameters.get("mode")) + ||action.equals("cleanup")&&"export_stl".equals(parameters.get("operation")))return; + String status=action.startsWith("feature-")&&!action.equals("feature-report")?"REVIEW":"PROCESSING"; + jdbc.update("UPDATE lab_dimension_comparison SET awaiting_revision=COALESCE(awaiting_revision,COALESCE(engine_revision,'')),status=?,last_error=NULL WHERE id=? AND tenant_id=?",status,job.get("id"),tenant()); } public void observe(String engine,Map state) { var list=rows("SELECT * FROM lab_dimension_comparison WHERE engine_id=? AND tenant_id=?",engine,tenant());if(list.isEmpty())return; @@ -194,6 +209,12 @@ public class LabDimensionComparisonService { String planPath=path+"/plan";Object plan=gateway.json(planPath,"GET",gateway.forward(planPath,"GET",new byte[0]));String planJson=mapper.writeValueAsString(plan); repository.plan(tenant(),engine,planJson); try(var pair=results.fetch(engine,state)) { + if(!pair.featureDocument().isEmpty()) { + var published=new LinkedHashMap(); + if(plan instanceof Map oldPlan)oldPlan.forEach((key,value)->published.put(key.toString(),value));else published.put("plan",plan); + published.put("featureDocument",pair.featureDocument());published.put("resultSnapshotId",state.get("result_snapshot_id")); + planJson=mapper.writeValueAsString(published); + } @SuppressWarnings("unchecked") var latest=(Map)gateway.json(path,"GET",gateway.forward(path,"GET",new byte[0])); if(!revision.equals(LabInspectionGateway.revision(latest))||!"done".equals(latest.get("status"))||Boolean.FALSE.equals(latest.get("report_ready"))){observe(engine,latest);return;} if(required(id).get("awaiting_revision")!=null)return; diff --git a/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/inspection/LabFeaturePlanService.java b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/inspection/LabFeaturePlanService.java new file mode 100644 index 0000000..6055034 --- /dev/null +++ b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/inspection/LabFeaturePlanService.java @@ -0,0 +1,92 @@ +package cn.iocoder.yudao.module.lab.service.inspection; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import jakarta.annotation.Resource; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Service; +import org.springframework.http.HttpStatus; +import org.springframework.web.server.ResponseStatusException; +import java.util.*; + +/** Full, versioned feature graph storage. Never flatten datums or tolerance frames. */ +@Service +public class LabFeaturePlanService { + @Resource private JdbcTemplate jdbc; + @Resource private ObjectMapper mapper; + private static final Set DERIVED=Set.of("measured","extraction_audit","diagnostic","status","scan_region","scan_region_diagnostic","preview_points","measurement_state","assessment_state","reason_code","next_action","workflow_note","workflow_warnings"); + @SuppressWarnings("unchecked") public void store(long tenant, String scan, Map document, boolean evaluated) throws java.io.IOException { + if(!(document.get("revision") instanceof Number number)||number.longValue()<0||number.longValue()>Integer.MAX_VALUE) + throw new ResponseStatusException(HttpStatus.BAD_GATEWAY,"计算服务返回的特征版本无效"); + int revision=number.intValue(); + String value=mapper.writeValueAsString(document); + Map definition=mapper.readValue(value,new TypeReference<>(){});definition.remove("evaluation");definition.remove("result_snapshot"); + for(var f:(List>)definition.getOrDefault("features",List.of())) DERIVED.forEach(f::remove); + for(var c:(List>)definition.getOrDefault("controls",List.of())) {c.remove("result");DERIVED.forEach(c::remove);} + jdbc.update("INSERT INTO lab_inspection_feature_plan(tenant_id,scan_id,revision,definition_json,evaluation_json) VALUES(?,?,?,?,?) ON DUPLICATE KEY UPDATE definition_json=CASE WHEN revision<=VALUES(revision) THEN VALUES(definition_json) ELSE definition_json END,evaluation_json=CASE WHEN revision<=VALUES(revision) THEN VALUES(evaluation_json) ELSE evaluation_json END,revision=GREATEST(revision,VALUES(revision)),update_time=NOW()",tenant,scan,revision,mapper.writeValueAsString(definition),evaluated?value:null); + } + public Map saved(long tenant,String scan) throws java.io.IOException { + var rows=jdbc.queryForList("SELECT definition_json,evaluation_json FROM lab_inspection_feature_plan WHERE tenant_id=? AND scan_id=?",tenant,scan); + if(rows.isEmpty())throw new ResponseStatusException(HttpStatus.NOT_FOUND,"尚无已保存的 CAD 特征计划"); + var row=rows.get(0);Object json=row.get("evaluation_json");if(json==null)json=row.get("definition_json"); + return Map.of("document",mapper.readValue(json.toString(),Map.class),"capabilities",Map.of(),"feature_types",Map.of(),"engine_unavailable",true); + } + public Map templates(long tenant) { + return Map.of("list",jdbc.queryForList("SELECT id,name,revision,update_time AS updateTime FROM lab_inspection_feature_template WHERE tenant_id=? ORDER BY update_time DESC",tenant)); + } + public Map template(long tenant,String id) throws Exception { + var rows=jdbc.queryForList("SELECT id,name,revision,definition_json FROM lab_inspection_feature_template WHERE tenant_id=? AND id=?",tenant,id); + if(rows.isEmpty())throw new ResponseStatusException(HttpStatus.NOT_FOUND,"特征模板不存在"); + var row=rows.get(0);row.put("definition",mapper.readValue(row.remove("definition_json").toString(),new TypeReference>(){}));return row; + } + public record Save(String id,String name,Integer revision,Map definition) {} + @SuppressWarnings("unchecked") public Map saveTemplate(long tenant, Save request,String creator) throws Exception { + if(request==null||request.name()==null || request.name().isBlank() || request.name().length()>100)throw new ResponseStatusException(HttpStatus.BAD_REQUEST,"请输入最多 100 字的模板名称"); + Map graph=templateDefinition(request.definition()); + String id=request.id(), json=mapper.writeValueAsString(graph); + if(id==null || id.isBlank()) {id=UUID.randomUUID().toString().replace("-","");jdbc.update("INSERT INTO lab_inspection_feature_template(id,tenant_id,name,definition_json,creator) VALUES(?,?,?,?,?)",id,tenant,request.name().trim(),json,creator);} + else if(request.revision()==null||jdbc.update("UPDATE lab_inspection_feature_template SET name=?,definition_json=?,revision=revision+1 WHERE tenant_id=? AND id=? AND revision=?",request.name().trim(),json,tenant,id,request.revision())!=1)throw new ResponseStatusException(HttpStatus.CONFLICT,"模板不存在或已修改,请重新加载"); + return template(tenant,id); + } + @SuppressWarnings("unchecked") public Map templateDefinition(Map definition) throws java.io.IOException { + if(definition==null||!Objects.equals(definition.get("schema_version"),2))throw new ResponseStatusException(HttpStatus.BAD_REQUEST,"请选择 v2 特征定义"); + // Descriptors are reusable; task-specific CAD bindings and measured values are not. + Map graph=mapper.readValue(mapper.writeValueAsString(definition),new TypeReference<>(){}); + if(!"mm".equals(graph.get("unit")))throw new ResponseStatusException(HttpStatus.BAD_REQUEST,"特征模板单位必须为 mm"); + for(String group:List.of("features","controls","datum_systems"))if(!(graph.get(group) instanceof List entries) || entries.size()>500 || entries.stream().anyMatch(e->!(e instanceof Map)))throw new ResponseStatusException(HttpStatus.BAD_REQUEST,"特征、控制和基准体系必须为最多 500 项的列表"); + Set featureIds=identifiers((List>)graph.get("features")),frameIds=identifiers((List>)graph.get("datum_systems")); + identifiers((List>)graph.get("controls")); + for(var control:(List>)graph.get("controls")) { + if(!featureIds.contains(control.get("feature_id"))||control.get("other_feature_id")!=null&&!featureIds.contains(control.get("other_feature_id"))||control.get("datum_system_id")!=null&&!frameIds.contains(control.get("datum_system_id"))) + throw new ResponseStatusException(HttpStatus.BAD_REQUEST,"检测控制引用了不存在的特征或基准体系"); + } + Set datumIds=new HashSet<>();Set labels=new HashSet<>(); + for(var feature:(List>)graph.get("features"))if(feature.get("datum_label") instanceof String label&&!label.isBlank()) { + if(!label.matches("[A-Z]{1,3}")||!labels.add(label))throw new ResponseStatusException(HttpStatus.BAD_REQUEST,"基准标签必须唯一且为 1–3 位大写字母"); + datumIds.add(feature.get("id")); + } + for(var frame:(List>)graph.get("datum_systems")) { + if(!(frame.get("precedence") instanceof List groups)||groups.isEmpty()||groups.size()>3)throw new ResponseStatusException(HttpStatus.BAD_REQUEST,"基准体系需按主、次、第三顺序配置"); + Set used=new HashSet<>(); + for(Object group:groups)if(!(group instanceof List ids)||ids.isEmpty()||ids.stream().anyMatch(id->!datumIds.contains(id)||!used.add(id)))throw new ResponseStatusException(HttpStatus.BAD_REQUEST,"基准体系包含重复或失效的基准引用"); + } + graph.remove("evaluation");graph.remove("result_snapshot");Object cad=graph.remove("cad_sha256");if(cad!=null)graph.put("reference_cad_sha256",cad);graph.remove("capability");graph.remove("revision"); + for(var feature:(List>)graph.getOrDefault("features",List.of())) { + DERIVED.forEach(feature::remove); + Object source=feature.remove("source"); + if(source instanceof Map s){feature.put("descriptor_source_kind",Objects.toString(s.get("kind"),""));feature.put("reference_binding",s);} + if(feature.get("nominal") instanceof Map nominal){nominal.remove("patch_mesh");nominal.remove("support_points");} + feature.put("binding_status","needs_rematch"); + } + for(var control:(List>)graph.getOrDefault("controls",List.of())) {control.remove("result");DERIVED.forEach(control::remove);} + return graph; + } + private static Set identifiers(List> entries) { + Set ids=new HashSet<>(); + for(var entry:entries)if(!(entry.get("id") instanceof String id)||id.isBlank()||id.length()>100||!ids.add(id))throw new ResponseStatusException(HttpStatus.BAD_REQUEST,"特征、控制与基准体系标识不能为空或重复"); + return ids; + } + public void delete(long tenant,String id,int revision) { + if(jdbc.update("DELETE FROM lab_inspection_feature_template WHERE tenant_id=? AND id=? AND revision=?",tenant,id,revision)!=1)throw new ResponseStatusException(HttpStatus.CONFLICT,"模板不存在或已修改"); + } +} diff --git a/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/inspection/LabInspectionGateway.java b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/inspection/LabInspectionGateway.java index be58836..4fc098c 100644 --- a/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/inspection/LabInspectionGateway.java +++ b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/inspection/LabInspectionGateway.java @@ -21,6 +21,7 @@ public class LabInspectionGateway { @Resource private LabInspectionProperties properties; @Resource private LabInspectionRepository repository; @Resource private ObjectMapper mapper; + @Resource private LabFeaturePlanService featurePlans; private HttpClient client; private record Availability(boolean available,long checkedAt) {} private volatile Availability availability=new Availability(false,0); @@ -42,10 +43,10 @@ public class LabInspectionGateway { } public void authorize(String path,String method) { boolean allowed=method.equals("GET")&&(path.equals("/api/health")||path.matches("/api/plan/templates(?:/[a-zA-Z0-9_.-]+)?")); - if(path.matches("/api/tasks/[a-f0-9]{32}(?:/(?:preview|plan-preview|plan|plan/template|plan/import|binding-proposals|cleanup|cleanup/auto|compare|generate-report|auto-measure|files/[a-zA-Z0-9_.-]+))?")) { + if(path.matches("/api/tasks/[a-f0-9]{32}(?:/(?:cad-features|feature-plan|feature-evaluate|feature-report|feature-proposals|feature-construct|feature-template|preview|plan-preview|plan|plan/template|plan/import|binding-proposals|cleanup|cleanup/auto|compare|generate-report|auto-measure|files/[a-zA-Z0-9_.-]+))?")) { if(!repository.owns(TenantContextHolder.getRequiredTenantId(),path.split("/")[3]))throw new ResponseStatusException(HttpStatus.NOT_FOUND,"检测任务不存在"); - allowed|=method.equals("GET")&&path.matches("/api/tasks/[a-f0-9]{32}(?:/(?:preview|plan-preview|plan|files/[a-zA-Z0-9_.-]+))?"); - allowed|=method.equals("POST")&&path.matches("/api/tasks/[a-f0-9]{32}/(?:plan|plan/template|plan/import|binding-proposals|cleanup|cleanup/auto|compare|generate-report|auto-measure)"); + allowed|=method.equals("GET")&&path.matches("/api/tasks/[a-f0-9]{32}(?:/(?:cad-features|feature-plan|preview|plan-preview|plan|files/[a-zA-Z0-9_.-]+))?"); + allowed|=method.equals("POST")&&path.matches("/api/tasks/[a-f0-9]{32}/(?:feature-plan|feature-evaluate|feature-report|feature-proposals|feature-construct|feature-template|plan|plan/template|plan/import|binding-proposals|cleanup|cleanup/auto|compare|generate-report|auto-measure)"); } if(!allowed)throw new ResponseStatusException(HttpStatus.NOT_FOUND,"不支持的检测接口,请从任务工作台发起比对"); } @@ -71,8 +72,12 @@ public class LabInspectionGateway { public Map health() { try { var response=send(request("/api/health",properties.getConnectTimeout()).GET().build()); - try(var in=response.body()){if(response.statusCode()>=400){availability=new Availability(false,System.currentTimeMillis());return Map.of("available",false,"message","计算服务健康检查失败");}} - return Map.of("available",true,"message",""); + if(response.statusCode()>=400){response.body().close();availability=new Availability(false,System.currentTimeMillis());return Map.of("available",false,"message","计算服务健康检查失败");} + Object value=json("/api/health","GET",response); + var health=new LinkedHashMap();health.put("available",true);health.put("message",""); + if(value instanceof Map body && body.get("feature_capabilities") instanceof Map capabilities) + health.put("feature_capabilities",capabilities); + return health; }catch(Exception error){return Map.of("available",false,"message","本机计算服务未就绪,请启动检测EXE后重试");} } public HttpResponse forward(String path,String method,byte[] body) { @@ -113,6 +118,9 @@ public class LabInspectionGateway { } if(method.equals("POST")&&path.matches("/api/tasks/[a-f0-9]{32}/(?:plan|plan/template|plan/import)")&&value instanceof Map result) repository.plan(TenantContextHolder.getRequiredTenantId(),path.split("/")[3],mapper.writeValueAsString(result)); + if(path.matches("/api/tasks/[a-f0-9]{32}/(?:feature-plan|feature-evaluate|feature-template|feature-proposals|feature-construct)") + && value instanceof Map result && result.get("document") instanceof Map document) + featurePlans.store(TenantContextHolder.getRequiredTenantId(),path.split("/")[3],document,document.containsKey("evaluation")&&!"stale".equals(document.get("evaluation_state"))); return value; } public static String revision(Map state){return Objects.toString(state.get("report_revision"),Objects.toString(state.get("revision"),""));} diff --git a/am-web/package.json b/am-web/package.json index 705473c..e0f7e8a 100644 --- a/am-web/package.json +++ b/am-web/package.json @@ -129,6 +129,7 @@ "@types/nprogress": "^0.2.3", "@types/qrcode": "^1.5.6", "@types/qs": "^6.15.0", + "@types/three": "0.181.0", "@unocss/eslint-config": "^66.6.8", "@unocss/eslint-plugin": "66.6.8", "@unocss/transformer-variant-group": "^66.6.8", diff --git a/am-web/pnpm-lock.yaml b/am-web/pnpm-lock.yaml index 79464f2..b28e205 100644 --- a/am-web/pnpm-lock.yaml +++ b/am-web/pnpm-lock.yaml @@ -297,6 +297,9 @@ importers: '@types/qs': specifier: ^6.15.0 version: 6.15.0 + '@types/three': + specifier: 0.181.0 + version: 0.181.0 '@unocss/eslint-config': specifier: ^66.6.8 version: 66.6.8(eslint@10.3.0(jiti@2.6.1)(supports-color@10.2.2))(supports-color@10.2.2)(typescript@6.0.3) @@ -800,6 +803,9 @@ packages: resolution: {integrity: sha512-kzyuwOAQnXJNLS9PSyrk0CWk35nWJW/zl/6KvnTBMFK65gm7U1/Z5BqjxeapjZCIhQcM/DsrEmcbRwDyXyXK4A==} engines: {node: '>=14'} + '@dimforge/rapier3d-compat@0.12.0': + resolution: {integrity: sha512-uekIGetywIgopfD97oDL5PfeezkFpNhwlzlaEYNOA0N6ghdsOvh/HYjSMek5Q2O1PYvRSDFcqFVJl4r4ZBwOow==} + '@element-plus/icons-vue@2.3.2': resolution: {integrity: sha512-OzIuTaIfC8QXEPmJvB4Y4kw34rSXdCJzxcD1kFStBvr8bK6X1zQAYDo0CNMjojnfTqRQCJ0I7prlErcoRiET2A==} peerDependencies: @@ -1771,6 +1777,9 @@ packages: '@transloadit/prettier-bytes@0.0.7': resolution: {integrity: sha512-VeJbUb0wEKbcwaSlj5n+LscBl9IPgLPkHVGBkh00cztv6X4L/TJXK58LzFuBKX7/GAfiGhIwH67YTLTlzvIzBA==} + '@tweenjs/tween.js@23.1.3': + resolution: {integrity: sha512-vJmvvwFxYuGnF2axRtPYocag6Clbb5YS7kLL+SO/TeVFzHqDIWrNKYtcsPMibjDx9O+bu+psAy9NKfWklassUA==} + '@tybys/wasm-util@0.10.1': resolution: {integrity: sha512-9tTaPJLSiejZKx+Bmog4uSubteqTvFrVrURwkmHixBo0G4seD0zUxp98E1DzUBJxLQ3NPwXrGKDiVjwx/DpPsg==} @@ -1819,6 +1828,12 @@ packages: '@types/qs@6.15.0': resolution: {integrity: sha512-JawvT8iBVWpzTrz3EGw9BTQFg3BQNmwERdKE22vlTxawwtbyUSlMppvZYKLZzB5zgACXdXxbD3m1bXaMqP/9ow==} + '@types/stats.js@0.17.4': + resolution: {integrity: sha512-jIBvWWShCvlBqBNIZt0KAshWpvSjhkwkEu4ZUcASoAvhmrgAUI2t1dXrjSL4xXVLB4FznPrIsX3nKXFl/Dt4vA==} + + '@types/three@0.181.0': + resolution: {integrity: sha512-MLF1ks8yRM2k71D7RprFpDb9DOX0p22DbdPqT/uAkc6AtQXjxWCVDjCy23G9t1o8HcQPk7woD2NIyiaWcWPYmA==} + '@types/trusted-types@2.0.7': resolution: {integrity: sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==} @@ -1831,6 +1846,9 @@ packages: '@types/web-bluetooth@0.0.21': resolution: {integrity: sha512-oIQLCGWtcFZy2JW77j9k8nHzAOpqMHLQejDA48XXMWH6tjCQHz5RCFz1bzsmROyL6PUm+LLnUiI4BCn221inxA==} + '@types/webxr@0.5.24': + resolution: {integrity: sha512-h8fgEd/DpoS9CBrjEQXR+dIDraopAEfu4wYVNY2tEPwk60stPWhvZMf4Foo5FakuQ7HFZoa8WceaWFervK2Ovg==} + '@typescript-eslint/eslint-plugin@8.59.2': resolution: {integrity: sha512-j/bwmkBvHUtPNxzuWe5z6BEk3q54YRyGlBXkSsmfoih7zNrBvl5A9A98anlp/7JbyZcWIJ8KXo/3Tq/DjFLtuQ==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} @@ -2339,6 +2357,9 @@ packages: slate: ^0.123.0 snabbdom: ^3.6.0 + '@webgpu/types@0.1.74': + resolution: {integrity: sha512-lgiI4hbuLcI9unnm2cL/tvCaQU45dp0xcLWJh5uB/9MBGvIA4F8XIk7nSiBeg+K4xWGYwgZKn80LmERI5CxoTA==} + '@xmldom/xmldom@0.8.11': resolution: {integrity: sha512-cQzWCtO6C8TQiYl1ruKNn2U6Ao4o4WBBcbL61yJl84x+j5sOWWFU9X7DpND8XZG3daDppSsigMdfAIl2upQBRw==} engines: {node: '>=10.0.0'} @@ -3413,6 +3434,9 @@ packages: picomatch: optional: true + fflate@0.8.3: + resolution: {integrity: sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==} + file-entry-cache@11.1.2: resolution: {integrity: sha512-N2WFfK12gmrK1c1GXOqiAJ1tc5YE+R53zvQ+t5P8S5XhnmKYVB5eZEiLNZKDSmoG8wqqbF9EXYBBW/nef19log==} @@ -4189,6 +4213,9 @@ packages: resolution: {integrity: sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==} engines: {node: '>= 8'} + meshoptimizer@0.22.0: + resolution: {integrity: sha512-IebiK79sqIy+E4EgOr+CAw+Ke8hAspXKzBd0JdgEmPHiAwmvEj2S4h1rfvo+o/BnfEYd/jAOg5IeeIjzlzSnDg==} + micromatch@4.0.8: resolution: {integrity: sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==} engines: {node: '>=8.6'} @@ -6226,6 +6253,8 @@ snapshots: '@ctrl/tinycolor@4.2.0': {} + '@dimforge/rapier3d-compat@0.12.0': {} + '@element-plus/icons-vue@2.3.2(vue@3.5.34(typescript@6.0.3))': dependencies: vue: 3.5.34(typescript@6.0.3) @@ -6981,6 +7010,8 @@ snapshots: '@transloadit/prettier-bytes@0.0.7': {} + '@tweenjs/tween.js@23.1.3': {} + '@tybys/wasm-util@0.10.1': dependencies: tslib: 2.8.1 @@ -7028,6 +7059,18 @@ snapshots: '@types/qs@6.15.0': {} + '@types/stats.js@0.17.4': {} + + '@types/three@0.181.0': + dependencies: + '@dimforge/rapier3d-compat': 0.12.0 + '@tweenjs/tween.js': 23.1.3 + '@types/stats.js': 0.17.4 + '@types/webxr': 0.5.24 + '@webgpu/types': 0.1.74 + fflate: 0.8.3 + meshoptimizer: 0.22.0 + '@types/trusted-types@2.0.7': optional: true @@ -7037,6 +7080,8 @@ snapshots: '@types/web-bluetooth@0.0.21': {} + '@types/webxr@0.5.24': {} + '@typescript-eslint/eslint-plugin@8.59.2(@typescript-eslint/parser@8.59.2(eslint@10.3.0(jiti@2.6.1)(supports-color@10.2.2))(supports-color@10.2.2)(typescript@6.0.3))(eslint@10.3.0(jiti@2.6.1)(supports-color@10.2.2))(supports-color@10.2.2)(typescript@6.0.3)': dependencies: '@eslint-community/regexpp': 4.12.2 @@ -7820,6 +7865,8 @@ snapshots: slate: 0.123.0 snabbdom: 3.6.3 + '@webgpu/types@0.1.74': {} + '@xmldom/xmldom@0.8.11': {} '@zxcvbn-ts/core@3.0.4': @@ -9028,6 +9075,8 @@ snapshots: optionalDependencies: picomatch: 4.0.5 + fflate@0.8.3: {} + file-entry-cache@11.1.2: dependencies: flat-cache: 6.1.22 @@ -9777,6 +9826,8 @@ snapshots: merge2@1.4.1: {} + meshoptimizer@0.22.0: {} + micromatch@4.0.8: dependencies: braces: 3.0.3 diff --git a/am-web/src/api/lab/inspection/index.ts b/am-web/src/api/lab/inspection/index.ts index b8a7401..f979925 100644 --- a/am-web/src/api/lab/inspection/index.ts +++ b/am-web/src/api/lab/inspection/index.ts @@ -1,11 +1,58 @@ import request from '@/config/axios' +import { visibleTemplate } from '@/utils/inspectionPresentation' const base = '/lab/inspection', root = `${base}/api` export const health = () => request.get({ url: `${base}/health`, timeout: 10000 }) export const comparison = (taskId: string, unitId: string, signal?: AbortSignal) => request.get({ url: `${base}/comparison`, params: { taskId, unitId }, signal }) -export const startComparison = (data: any) => request.post({ url: `${base}/comparison/start`, data, timeout: 620000 }) +export const startComparison = (data: any) => + request.post({ url: `${base}/comparison/start`, data, timeout: 620000 }) export const templates = () => request.get({ url: `${base}/templates/options` }) +export const featureCapabilities = async () => (await health()).feature_capabilities +export const featureTemplate = (id: string) => + request.get({ url: `${base}/feature-templates/${id}` }) +export const featureTemplates = async () => { + const response = await request.get({ url: `${base}/feature-templates` }) + const rows = await Promise.all( + response.list.map(async (row: any) => { + const detail = await featureTemplate(row.id) + return visibleTemplate(detail.definition) + ? { + ...row, + enabled: detail.definition.enabled !== false, + controlCount: detail.definition.controls?.length || 0 + } + : null + }) + ) + return { ...response, list: rows.filter(Boolean) } +} +export const saveFeatureTemplate = (data: any) => + request.post({ url: `${base}/feature-templates`, data }) +export const deleteFeatureTemplate = (id: string, revision: number) => + request.delete({ url: `${base}/feature-templates/${id}`, params: { revision } }) +export const comparisonTemplates = async () => { + const legacy = await templates() + try { + const features = await featureTemplates() + return { + ...legacy, + templates: [ + ...legacy.templates.map((item: any) => ({ ...item, kind: 'legacy' })), + ...features.list + .filter((item: any) => item.enabled && item.controlCount > 0) + .map((item: any) => ({ + id: `feature-${item.id}`, + label: item.name, + version: item.revision, + kind: 'feature' + })) + ] + } + } catch { + return { ...legacy, featureTemplatesUnavailable: true } + } +} export const templatePage = (params: any) => request.get({ url: `${base}/templates/page`, params }) export const templateDetail = (id: string) => request.get({ url: `${base}/templates/${id}` }) export const saveTemplate = (data: any) => request.post({ url: `${base}/templates/save`, data }) @@ -16,11 +63,13 @@ export const record = (id: string) => request.get({ url: `${base}/records/${id}` export const sync = (id: string) => request.post({ url: `${base}/records/${id}/sync`, timeout: 120000 }) export const get = (id: string, action: string) => - request.get({ url: `${root}/tasks/${id}/${action}` }) + request.get({ url: `${root}/tasks/${id}/${action}`, timeout: 600000 }) export const post = (id: string, action: string, data: any = {}) => request.post({ url: `${root}/tasks/${id}/${action}`, data, timeout: 600000 }) export const artifact = (id: string, name: string) => request.download({ url: `${root}/tasks/${id}/files/${name}` }) +export const processedStl = (id: string) => + request.download({ url: `${root}/tasks/${id}/files/cleaned_source.stl`, timeout: 600000 }) export const templateFile = (id: string) => request.download({ url: `${root}/plan/templates/${encodeURIComponent(id)}` }) export function saveBlob(blob: Blob, name: string) { diff --git a/am-web/src/utils/inspectionPresentation.ts b/am-web/src/utils/inspectionPresentation.ts new file mode 100644 index 0000000..4263a0b --- /dev/null +++ b/am-web/src/utils/inspectionPresentation.ts @@ -0,0 +1,97 @@ +export function userMessage(error: any, fallback = '操作未完成,请稍后重试') { + const message = String(typeof error === 'string' ? error : error?.message || '').trim() + if (!message) return fallback + if (/access violation|Non-positive solid volume|几何内核|ABViewer|OCP/i.test(message)) + return '模型读取失败,请检查模型完整性,或重新导出 STEP 后上传。' + if ( + /Python|Java\b|ECONN|Network Error|fetch failed|request failed|连接失败|源码服务|终端日志/i.test( + message + ) + ) + return '检测服务暂不可用,请稍后重试或联系管理员。' + if ( + /schema_version|\bv2\b|\bID\b|\w+_\w+|topology\.log|projection\.log|JSON|Traceback|TypeError|KeyError|ValueError|SyntaxError|[A-Za-z]:[\\/]|\/api\/|feature_id|datum_system_id/.test( + message + ) + ) + return fallback + if (/算法待支持|尚未实现|未实现|约束模拟器/.test(message)) + return '当前测量方式不支持此项配置,请调整特征、基准或测量方式。' + if (!/[\u3400-\u9fff]/.test(message)) return fallback + return message +} + +export const methodLabel = (method: string) => + ({ + minimum_zone_normalized_parallel_planes_envelope: '最小区域平面度', + minimum_zone_concentric_circles_envelope: '最小区域圆度', + minimum_zone_coaxial_cylinders_envelope: '最小区域圆柱度', + minimum_enclosing_line_cylinder_envelope: '包络轴线直线度', + least_squares_diameter: '最小二乘直径', + least_squares_radius: '最小二乘半径', + minimum_zone_parallel_planes_lp: '最小区域平面度', + minimum_zone_concentric_circles_powell: '最小区域圆度', + minimum_zone_coaxial_cylinders_powell: '最小区域圆柱度', + minimum_enclosing_line_cylinder: '包络轴线直线度', + least_squares_included_angle_deg: '圆锥角度', + defined_circle_arc_length: '指定弧段长度', + minimum_circumscribed_sample_cylinder: '外圆包络配合直径', + maximum_inscribed_sample_cylinder: '内孔包络配合直径', + associated_direction_angle_deg: '方向夹角', + parallel_axis_pitch_distance: '平行轴线间距', + projected_center_distance: '指定方向距离', + center_to_center_distance: '空间中心距', + datum_constrained_axis_orientation_at_defined_length: '轴线方向公差', + datum_constrained_parallel_plane_zone: '平面方向公差', + diametrical_associated_axis_zone: '同轴或同心公差带', + datum_axis_radial_range: '径向跳动', + datum_axis_radial_circular_range: '径向圆跳动', + datum_axis_radial_total_range: '径向全跳动', + datum_axis_axial_circular_range: '端面圆跳动', + datum_axis_axial_total_range: '端面全跳动', + measured_plane_intersections_at_reference_line: '指定位置的平面间距', + measured_center_to_plane_distance: '点面距离', + parallel_measured_axis_distance: '平行轴距', + shortest_measured_skew_axis_distance: '空间轴线最短距离', + minimum_sampled_surface_distance: '扫描区域最小点距', + full_retained_scan_projected_extent: '扫描区域投影跨度', + measured_direction_angle_acute_deg: '较小夹角', + measured_direction_angle_directed_deg: '方向夹角', + measured_direction_angle_supplementary_deg: '补角', + datum_321_associated_axis_position: '轴线位置度', + datum_321_associated_center_diametrical_position: '中心位置度', + datum_associated_median_plane_symmetry: '中间面对称度', + datum_321_bilateral_exact_trimmed_cad_profile: '曲面轮廓度', + datum_321_bilateral_analytic_profile: '解析特征轮廓度' + })[method] || '其他评价方法' + +export function drawingIssue(issue: any) { + return issue.diagnostic + ? userMessage(issue.diagnostic, '请核对图纸标注与几何位置') + : { + ambiguous_binding: '存在多个匹配特征,请选择对应位置', + unmatched_dimension: '未找到对应尺寸,请补充关联', + unmatched_feature: '未找到对应特征,请重新选面', + drawing_unreadable: '图纸读取失败,请检查文件', + drawing_coverage_unverified: '请核对检测项及基准关系' + }[issue.status] || '请核对检测配置' +} + +export function visibleTemplate(definition: any) { + return definition?.template_usage !== 'verification' +} + +export function pendingInspectionCount(state: any): number { + if (state?.status !== 'done') return 0 + const counts = state.result_counts || {} + return Math.max(0, Number(counts.pending) || 0, Number(counts.without_value) || 0) +} + +export function inspectionCompletionLabel(state: any): string | undefined { + if (state?.status !== 'done') return undefined + if (state.report_ready === false) return '计划已计算 · 待生成报告' + const pending = pendingInspectionCount(state) + if (pending) return `计算完成 · 待处理 ${pending} 项` + if (state.measurement_complete === false) return '计算完成 · 待复核' + return undefined +} diff --git a/am-web/src/views/lab/dimension/ComparisonPanel.vue b/am-web/src/views/lab/dimension/ComparisonPanel.vue index 912e479..b819c0f 100644 --- a/am-web/src/views/lab/dimension/ComparisonPanel.vue +++ b/am-web/src/views/lab/dimension/ComparisonPanel.vue @@ -1,61 +1,195 @@ @@ -69,23 +203,115 @@ import '@/views/lab/inspection/inspection.scss' import { comparisonPollInterval } from '@/views/lab/scan-task/workbenchPolling.mjs' import { comparisonBlockers } from './comparisonReadiness.mjs' import { checkPermi } from '@/utils/permission' -const InspectionWorkbench = defineAsyncComponent(() => import('@/views/lab/inspection/InspectionWorkbench.vue')) -const props = defineProps<{ taskId: string; unitId: string; revision: number; ready: boolean; dirty: boolean; sourceChanged: boolean; active: boolean; inputs: { modelId: any; drawingId: any; cloudId: any }; selectedInputs?: { modelId: any; drawingId: any; cloudId: any }; savingInputs?: boolean; cloudFileCount?: number }>() -const emit = defineEmits<{ changed: []; 'open-materials': []; 'save-inputs': []; 'archive-cloud': [] }>() -const router = useRouter(), job = ref({}), health = ref({}), catalog = ref([]), error = ref(''), loading = ref(false), busy = ref(false), syncing = ref(false), expanded = ref(false), workspace = ref() -const options = reactive({ planTemplateId: '', sourceScale: 1, targetScale: 1, tolerance: 1, autoReport: true, sourceClean: false, reviewCleanup: false }) +const InspectionWorkbench = defineAsyncComponent( + () => import('@/views/lab/inspection/InspectionWorkbench.vue') +) +const props = defineProps<{ + taskId: string + unitId: string + revision: number + ready: boolean + dirty: boolean + sourceChanged: boolean + active: boolean + inputs: { modelId: any; drawingId: any; cloudId: any } + selectedInputs?: { modelId: any; drawingId: any; cloudId: any } + savingInputs?: boolean + cloudFileCount?: number +}>() +const emit = defineEmits<{ + changed: [] + 'open-materials': [] + 'save-inputs': [] + 'archive-cloud': [] +}>() +const router = useRouter(), + job = ref({}), + health = ref({}), + catalog = ref([]), + error = ref(''), + loading = ref(false), + busy = ref(false), + syncing = ref(false), + expanded = ref(false), + workspace = ref() +const options = reactive({ + planTemplateId: '', + sourceScale: 1, + targetScale: 1, + tolerance: 1, + autoReport: true, + sourceClean: false, + reviewCleanup: false +}) const planSelect = ref() -const selectedPlan = computed(() => catalog.value.find(plan => plan.id === options.planTemplateId)) -const units = [{value: 1,label:'毫米 mm'},{value:1000,label:'米 m'},{value:0.001,label:'微米 μm'}] -const labels: Record = {SUBMITTING:'正在提交资料',UNKNOWN:'提交结果待核对',PROCESSING:'计算处理中',REVIEW:'待人工核对',ARCHIVE_PENDING:'计算完成,正在归档',ARCHIVE_ERROR:'计算完成,成果归档待处理',ARCHIVED:'成果已成套归档',FAILED:'比对失败'} +const featureTemplatesUnavailable = ref(false) +const planGroups = computed(() => + [ + { + label: 'CAD 特征计划(基准 / 形位公差)', + items: catalog.value.filter((item) => item.kind === 'feature') + }, + { label: '原有检测计划', items: catalog.value.filter((item) => item.kind !== 'feature') } + ].filter((group) => group.items.length) +) +const selectedPlan = computed(() => + catalog.value.find((plan) => plan.id === options.planTemplateId) +) +const units = [ + { value: 1, label: '毫米 mm' }, + { value: 1000, label: '米 m' }, + { value: 0.001, label: '微米 μm' } +] +const labels: Record = { + SUBMITTING: '正在提交资料', + UNKNOWN: '提交结果待核对', + PROCESSING: '计算处理中', + REVIEW: '待人工核对', + ARCHIVE_PENDING: '计算完成,正在归档', + ARCHIVE_ERROR: '计算完成,成果归档待处理', + ARCHIVED: '成果已成套归档', + FAILED: '比对失败' +} const sameInput = computed(() => { // Historical snapshots stored Snowflake IDs as JSON integers; preserve them before parsing. - try { const frozen = JSON.parse((job.value.input_json || '{}').replace(/"id"\s*:\s*(\d{16,})(?=\s*[,}])/g, '"id":"$1"')); return String(frozen.model?.id || '') === String(props.inputs.modelId || '') && String(frozen.drawing?.id || '') === String(props.inputs.drawingId || '') && String(frozen.cloud?.id || '') === String(props.inputs.cloudId || '') } - catch { return false } + try { + const frozen = JSON.parse( + (job.value.input_json || '{}').replace(/"id"\s*:\s*(\d{16,})(?=\s*[,}])/g, '"id":"$1"') + ) + return ( + String(frozen.model?.id || '') === String(props.inputs.modelId || '') && + String(frozen.drawing?.id || '') === String(props.inputs.drawingId || '') && + String(frozen.cloud?.id || '') === String(props.inputs.cloudId || '') + ) + } catch { + return false + } }) -const pendingSameInput = computed(() => sameInput.value && ['SUBMITTING','UNKNOWN','PROCESSING','REVIEW','ARCHIVE_PENDING','ARCHIVE_ERROR'].includes(job.value.status)) -const calculationActive = computed(() => ['SUBMITTING','UNKNOWN','PROCESSING'].includes(job.value.status)) -const blockers = computed(() => comparisonBlockers({ unitId: props.unitId, inputs: props.selectedInputs || props.inputs, dirty: props.dirty, sourceChanged: props.sourceChanged, planId: options.planTemplateId, plans: catalog.value, healthAvailable: health.value.available, pending: pendingSameInput.value, cloudFileCount: props.cloudFileCount })) +const pendingSameInput = computed( + () => + sameInput.value && + ['SUBMITTING', 'UNKNOWN', 'PROCESSING', 'REVIEW', 'ARCHIVE_PENDING', 'ARCHIVE_ERROR'].includes( + job.value.status + ) +) +const calculationActive = computed(() => + ['SUBMITTING', 'UNKNOWN', 'PROCESSING'].includes(job.value.status) +) +const blockers = computed(() => + comparisonBlockers({ + unitId: props.unitId, + inputs: props.selectedInputs || props.inputs, + dirty: props.dirty, + sourceChanged: props.sourceChanged, + planId: options.planTemplateId, + plans: catalog.value, + healthAvailable: health.value.available, + featureAvailable: !!health.value.feature_capabilities, + pending: pendingSameInput.value, + cloudFileCount: props.cloudFileCount + }) +) function canResolveIssue(action: string) { if (['save', 'archive'].includes(action)) return checkPermi(['lab:data:upload']) return action !== 'workspace' || !!job.value.engine_id @@ -94,89 +320,263 @@ function resolveIssue(action: string) { if (action === 'save') emit('save-inputs') else if (action === 'archive') emit('archive-cloud') else if (action === 'materials') emit('open-materials') - else if (action === 'plan') { planSelect.value?.$el?.scrollIntoView({ block: 'center', behavior: 'smooth' }); planSelect.value?.focus() } - else if (action === 'refresh') void refresh(true) + else if (action === 'plan') { + planSelect.value?.$el?.scrollIntoView({ block: 'center', behavior: 'smooth' }) + planSelect.value?.focus() + } else if (action === 'refresh') void refresh(true) else if (action === 'workspace' && job.value.engine_id) expanded.value = true } -let timer: ReturnType | undefined, generation = 0, abort: AbortController | undefined +let timer: ReturnType | undefined, + generation = 0, + abort: AbortController | undefined let lastDelivery = '' -let suspended=false -function schedulePoll(token:number){clearTimeout(timer);const delay=comparisonPollInterval(job.value.status);if(delay&&token===generation&&props.active&&!suspended&&!document.hidden)timer=setTimeout(()=>refresh(),delay)} +let suspended = false +function schedulePoll(token: number) { + clearTimeout(timer) + const delay = comparisonPollInterval(job.value.status) + if (delay && token === generation && props.active && !suspended && !document.hidden) + timer = setTimeout(() => refresh(), delay) +} async function refresh(withHealth = false) { if (!props.active || !props.unitId || suspended || document.hidden || loading.value) return const current = generation loading.value = true error.value = '' try { - const [currentJob, state, plans] = await Promise.all([Api.comparison(props.taskId,props.unitId,abort?.signal),withHealth ? Api.health() : Promise.resolve(null),withHealth ? Api.templates() : Promise.resolve(null)]) + const [currentJob, state, plans] = await Promise.all([ + Api.comparison(props.taskId, props.unitId, abort?.signal), + withHealth ? Api.health() : Promise.resolve(null), + withHealth ? Api.comparisonTemplates() : Promise.resolve(null) + ]) if (current !== generation) return job.value = currentJob || {} if (state) health.value = state - if (plans) catalog.value = plans.templates || [] + if (plans) { + catalog.value = plans.templates || [] + featureTemplatesUnavailable.value = !!plans.featureTemplatesUnavailable + } const delivery = String(job.value.delivery_id || '') if (delivery && lastDelivery && delivery !== lastDelivery) emit('changed') if (delivery && !lastDelivery) emit('changed') lastDelivery = delivery - } catch (e: any) { if (current === generation && !abort?.signal.aborted) error.value = e?.message || '读取比对状态失败' } - finally { if(current === generation) { loading.value = false;schedulePoll(current) } } + } catch (e: any) { + if (current === generation && !abort?.signal.aborted) + error.value = e?.message || '读取比对状态失败' + } finally { + if (current === generation) { + loading.value = false + schedulePoll(current) + } + } } -watch(() => [props.taskId,props.unitId,props.active], async () => { - generation++; abort?.abort(); abort = new AbortController(); clearTimeout(timer); loading.value=false;job.value = {}; lastDelivery = '' - if (props.active && props.unitId && props.unitId !== '0') await refresh(true) -},{immediate:true}) +watch( + () => [props.taskId, props.unitId, props.active], + async () => { + generation++ + abort?.abort() + abort = new AbortController() + clearTimeout(timer) + loading.value = false + job.value = {} + lastDelivery = '' + if (props.active && props.unitId && props.unitId !== '0') await refresh(true) + }, + { immediate: true } +) async function start() { if (busy.value || props.savingInputs || !props.ready) return - if (blockers.value.length) { ElMessage.warning(blockers.value[0].text); return } + if (blockers.value.length) { + ElMessage.warning(blockers.value[0].text) + return + } const token = generation - busy.value = true; error.value = '' + busy.value = true + error.value = '' try { - const started = await Api.startComparison({taskId:props.taskId,unitId:props.unitId,revision:props.revision,...options}) + const started = await Api.startComparison({ + taskId: props.taskId, + unitId: props.unitId, + revision: props.revision, + ...options + }) if (token !== generation) return job.value = started schedulePoll(token) emit('changed') if (job.value.engine_id) expanded.value = true - } catch(e:any) { if(token === generation) { const failure = e?.message || '提交失败,请刷新状态后核对'; await refresh(); if(token === generation) error.value = failure } } - finally { busy.value = false } + } catch (e: any) { + if (token === generation) { + const failure = e?.message || '提交失败,请刷新状态后核对' + await refresh() + if (token === generation) error.value = failure + } + } finally { + busy.value = false + } } async function sync() { if (syncing.value || !job.value.engine_id) return syncing.value = true - try { await Api.sync(job.value.engine_id); await refresh(); emit('changed'); ElMessage.success('已更新归档状态') } - catch(e:any) { error.value = e?.message || '归档尚未完成' } - finally { syncing.value = false } + try { + await Api.sync(job.value.engine_id) + await refresh() + emit('changed') + ElMessage.success('已更新归档状态') + } catch (e: any) { + error.value = e?.message || '归档尚未完成' + } finally { + syncing.value = false + } +} +async function workspaceChanged() { + await refresh() + emit('changed') +} +async function canLeave() { + return !expanded.value || !workspace.value || (await workspace.value.confirmLeave()) +} +async function closeWorkspace(done: () => void) { + if (await canLeave()) { + done() + await workspaceChanged() + } } -async function workspaceChanged() { await refresh(); emit('changed') } -async function canLeave() { return !expanded.value || !workspace.value || await workspace.value.confirmLeave() } -async function closeWorkspace(done: () => void) { if(await canLeave()) { done(); await workspaceChanged() } } defineExpose({ canLeave }) -function visibilityChanged(){if(document.hidden)clearTimeout(timer);else if(props.active&&comparisonPollInterval(job.value.status))void refresh()} -onMounted(()=>document.addEventListener('visibilitychange',visibilityChanged)) -onActivated(()=>{suspended=false;if(props.active)void refresh()}) -onDeactivated(()=>{suspended=true;clearTimeout(timer);generation++;abort?.abort();abort=new AbortController();loading.value=false}) -onBeforeUnmount(() => { generation++; clearTimeout(timer); abort?.abort();document.removeEventListener('visibilitychange',visibilityChanged) }) +function visibilityChanged() { + if (document.hidden) clearTimeout(timer) + else if (props.active && comparisonPollInterval(job.value.status)) void refresh() +} +onMounted(() => document.addEventListener('visibilitychange', visibilityChanged)) +onActivated(() => { + suspended = false + if (props.active) void refresh() +}) +onDeactivated(() => { + suspended = true + clearTimeout(timer) + generation++ + abort?.abort() + abort = new AbortController() + loading.value = false +}) +onBeforeUnmount(() => { + generation++ + clearTimeout(timer) + abort?.abort() + document.removeEventListener('visibilitychange', visibilityChanged) +}) diff --git a/am-web/src/views/lab/dimension/comparisonReadiness.mjs b/am-web/src/views/lab/dimension/comparisonReadiness.mjs index f5b0f0b..3bedb92 100644 --- a/am-web/src/views/lab/dimension/comparisonReadiness.mjs +++ b/am-web/src/views/lab/dimension/comparisonReadiness.mjs @@ -1,13 +1,81 @@ /** Explain each start requirement with an actionable next step. PDF is optional. */ -export function comparisonBlockers({ unitId, inputs = {}, dirty, sourceChanged, planId, plans = [], healthAvailable, pending, cloudFileCount = 0 }) { +export function comparisonBlockers({ + unitId, + inputs = {}, + dirty, + sourceChanged, + planId, + plans = /** @type {any[]} */ ([]), + healthAvailable, + featureAvailable = true, + pending, + cloudFileCount = 0 +}) { const issues = [] - if (!unitId || String(unitId) === '0') issues.push({ key: 'unit', text: '请先选择需要比对的样件。', action: 'materials', label: '选择样件' }) - if (dirty) issues.push({ key: 'save', text: '比对资料版本尚未保存,当前选择还未生效。', action: 'save', label: '保存比对资料版本' }) - if (!inputs.modelId) issues.push({ key: 'model', text: '尚未选用三维数模,请上传或选择 X_T / STP 版本。', action: 'materials', label: '选择三维数模' }) - if (!inputs.cloudId) issues.push({ key: 'cloud', text: cloudFileCount ? '扫描已导出 PLY,但尚未归档并选用于当前样件。' : '尚未关联扫描 PLY,请先完成扫描并导出 PLY。', action: cloudFileCount === 1 ? 'archive' : 'materials', label: cloudFileCount === 1 ? '归档并选用扫描PLY' : '查看扫描导出文件' }) - if (sourceChanged) issues.push({ key: 'scan', text: '扫描执行已更新或仍在执行,请结束扫描后关联对应的 PLY。', action: 'materials', label: '检查扫描PLY' }) - if (!planId || !plans.some(plan => plan.id === planId)) issues.push({ key: 'plan', text: '检测计划为必填项,请明确选择一个已维护且启用的计划。', action: 'plan', label: '选择检测计划' }) - if (!healthAvailable) issues.push({ key: 'health', text: '计算服务尚未就绪,请启动本机检测 EXE 后刷新状态。', action: 'refresh', label: '刷新计算服务状态' }) - if (pending) issues.push({ key: 'pending', text: '当前输入已有未完成的比对,请查看现有作业,避免重复提交。', action: 'workspace', label: '查看当前比对' }) + if (!unitId || String(unitId) === '0') + issues.push({ + key: 'unit', + text: '请先选择需要比对的样件。', + action: 'materials', + label: '选择样件' + }) + if (dirty) + issues.push({ + key: 'save', + text: '比对资料版本尚未保存,当前选择还未生效。', + action: 'save', + label: '保存比对资料版本' + }) + if (!inputs.modelId) + issues.push({ + key: 'model', + text: '尚未选用三维数模,请上传或选择 X_T / STP 版本。', + action: 'materials', + label: '选择三维数模' + }) + if (!inputs.cloudId) + issues.push({ + key: 'cloud', + text: cloudFileCount + ? '扫描已导出 PLY,但尚未归档并选用于当前样件。' + : '尚未关联扫描 PLY,请先完成扫描并导出 PLY。', + action: cloudFileCount === 1 ? 'archive' : 'materials', + label: cloudFileCount === 1 ? '归档并选用扫描PLY' : '查看扫描导出文件' + }) + if (sourceChanged) + issues.push({ + key: 'scan', + text: '扫描执行已更新或仍在执行,请结束扫描后关联对应的 PLY。', + action: 'materials', + label: '检查扫描PLY' + }) + if (!planId || !plans.some((plan) => plan.id === planId)) + issues.push({ + key: 'plan', + text: '检测计划为必填项,请明确选择一个已维护且启用的计划。', + action: 'plan', + label: '选择检测计划' + }) + if (!healthAvailable) + issues.push({ + key: 'health', + text: '计算服务尚未就绪,请启动本机检测 EXE 后刷新状态。', + action: 'refresh', + label: '刷新计算服务状态' + }) + else if (planId?.startsWith('feature-') && !featureAvailable) + issues.push({ + key: 'feature-capability', + text: 'CAD 特征计划需要新版检测 EXE,请安装后刷新状态。', + action: 'refresh', + label: '刷新计算服务状态' + }) + if (pending) + issues.push({ + key: 'pending', + text: '当前输入已有未完成的比对,请查看现有作业,避免重复提交。', + action: 'workspace', + label: '查看当前比对' + }) return issues } diff --git a/am-web/src/views/lab/inspection/CadFeatureViewer.vue b/am-web/src/views/lab/inspection/CadFeatureViewer.vue new file mode 100644 index 0000000..6060852 --- /dev/null +++ b/am-web/src/views/lab/inspection/CadFeatureViewer.vue @@ -0,0 +1,465 @@ + + + diff --git a/am-web/src/views/lab/inspection/CadSectionPicker.vue b/am-web/src/views/lab/inspection/CadSectionPicker.vue new file mode 100644 index 0000000..3999d86 --- /dev/null +++ b/am-web/src/views/lab/inspection/CadSectionPicker.vue @@ -0,0 +1,197 @@ + + diff --git a/am-web/src/views/lab/inspection/FeatureDatumEditor.vue b/am-web/src/views/lab/inspection/FeatureDatumEditor.vue new file mode 100644 index 0000000..8952c8c --- /dev/null +++ b/am-web/src/views/lab/inspection/FeatureDatumEditor.vue @@ -0,0 +1,123 @@ + + + diff --git a/am-web/src/views/lab/inspection/FeatureGeometryEditor.vue b/am-web/src/views/lab/inspection/FeatureGeometryEditor.vue new file mode 100644 index 0000000..a77994e --- /dev/null +++ b/am-web/src/views/lab/inspection/FeatureGeometryEditor.vue @@ -0,0 +1,107 @@ + + + diff --git a/am-web/src/views/lab/inspection/FeatureTemplateManager.vue b/am-web/src/views/lab/inspection/FeatureTemplateManager.vue new file mode 100644 index 0000000..464bd38 --- /dev/null +++ b/am-web/src/views/lab/inspection/FeatureTemplateManager.vue @@ -0,0 +1,885 @@ + + + diff --git a/am-web/src/views/lab/inspection/GeneralToleranceEditor.vue b/am-web/src/views/lab/inspection/GeneralToleranceEditor.vue new file mode 100644 index 0000000..91b4c89 --- /dev/null +++ b/am-web/src/views/lab/inspection/GeneralToleranceEditor.vue @@ -0,0 +1,165 @@ + + + diff --git a/am-web/src/views/lab/inspection/InspectionCleanup.vue b/am-web/src/views/lab/inspection/InspectionCleanup.vue index 831c064..56298ec 100644 --- a/am-web/src/views/lab/inspection/InspectionCleanup.vue +++ b/am-web/src/views/lab/inspection/InspectionCleanup.vue @@ -4,7 +4,13 @@ >

点云处理工作区

在扫描原始坐标系中调整规则。先预览保留 / 排除点,再确认并重新对齐。

重新读取
+ 重新读取
保留内部删除内部 + >
{{ Number(vi) + 1 }}移除
添加顶点
CAD 主体编号:{{ - r.component_ids?.join(', ') - }}。修改前置规则后,请重新生成自动方案。
已匹配 {{ r.component_ids?.length || 0 }} 个 CAD + 主体。修改前置规则后,请重新生成方案。 -
预览按照完整原始点云计算保留结果,窗口最多显示 24,000 - 个采样点。规则只排除原始点,正式对齐使用确认后保留的点云。
+
预览显示部分点;清理和对齐使用确认后保留的完整点云。
@@ -180,7 +182,7 @@ }}保留点 / 原始点
表面 RMS表面均方根偏差{{ number(current.summary?.statistics?.rms_mm) }} mm点到设计表面的偏差
优先使用 CAD - 圆或平面拟合。推荐仅辅助定位,可根据三维位置换选,生成报告时自动确认并计算。
+ >
选择对应的几何位置,或通过三维选点调整。
{{ selectedRow.table === 'gauge' - ? '点间距使用两个真实扫描点,会将本项控制方式改为点间距。孔心距、面距请选对应 CAD 几何推荐。' + ? '点间距测量两个选定点之间的距离;孔心距或面距请选择对应几何特征。' : '近似位置用于查找附近 CAD 圆;三点指定需在同一截面选择分散圆周点,测量时再用附近扫描点拟合。' }}
@@ -400,38 +399,77 @@

检测结果与报告

测量结果、表面色谱和报告下载集中展示,历史成果版本返回任务查看。

测量结果、表面色谱和报告下载集中展示,历史版本在报告管理中查询。

调整计划与选点历史成果
调整检测定义历史报告

+ 统计搜索范围 {{ current.summary.surface_statistics.search_mm }} mm:参与 + {{ current.summary.surface_statistics.in_search_count?.toLocaleString() }} 点,范围外 + {{ current.summary.surface_statistics.outside_search_count?.toLocaleString() }} + 点;局部法向投影均值 + {{ + number( + current.summary.surface_statistics.within_search?.triangle_normal_projection?.mean_mm + ) + }} + mm。

参与统计点数全部保留点数{{ current.summary?.statistics?.count?.toLocaleString() ?? '—' }}
均方根偏差 / mm最短距离 RMS / mm{{ number(current.summary?.statistics?.rms_mm) }}
有测量值{{ measuredCount }} / {{ rows.length }}
有测量值{{ + resultLoadState === 'ready' + ? resultRows.filter((r) => r.measured_mm != null).length + : '—' + }} + / {{ resultLoadState === 'ready' ? resultRows.length : '—' }}
通过 / 超差{{ rows.filter((r) => r.inspection_result === '通过').length }} / - {{ rows.filter((r) => r.inspection_result === '失败').length }}{{ + resultLoadState === 'ready' + ? resultRows.filter((r) => ['通过', '合格'].includes(r.inspection_result)).length + : '—' + }} + / + {{ + resultLoadState === 'ready' + ? resultRows.filter((r) => ['失败', '不合格'].includes(r.inspection_result)).length + : '—' + }}
预览报告 + 预览报告下载 PDF下载结果包下载处理后点云处理日志
- 检测项目结果 + + 重新读取 + + + {{ + resultAction(s.row) + }} -
{{ dirty ? '有修改待保存' : '计划已同步' }} + diff --git a/am-web/src/views/lab/inspection/MeasurementParameters.vue b/am-web/src/views/lab/inspection/MeasurementParameters.vue new file mode 100644 index 0000000..4fc257f --- /dev/null +++ b/am-web/src/views/lab/inspection/MeasurementParameters.vue @@ -0,0 +1,272 @@ + + + diff --git a/am-web/src/views/lab/inspection/ProcessedStlDownload.vue b/am-web/src/views/lab/inspection/ProcessedStlDownload.vue new file mode 100644 index 0000000..214eaf6 --- /dev/null +++ b/am-web/src/views/lab/inspection/ProcessedStlDownload.vue @@ -0,0 +1,59 @@ + + + diff --git a/am-web/src/views/lab/inspection/datumSelection.ts b/am-web/src/views/lab/inspection/datumSelection.ts new file mode 100644 index 0000000..de5a901 --- /dev/null +++ b/am-web/src/views/lab/inspection/datumSelection.ts @@ -0,0 +1,86 @@ +// Shared by template editing and task editing; eligibility comes from the engine. +export function datumCandidates(features: any[], types: Record) { + return features.filter((f) => types[f.type]?.datum_allowed === true) +} + +export function nextDatumLabel(features: any[]) { + const used = new Set(features.map((f) => f.datum_label).filter(Boolean)) + for (let index = 1; index <= 18278; index++) { + let value = index, + label = '' + while (value > 0) { + value-- + label = String.fromCharCode(65 + (value % 26)) + label + value = Math.floor(value / 26) + } + if (!used.has(label)) return label + } + throw Error('基准标签已用完,请检查特征定义') +} + +export function validateDatumFrames(features: any[], frames: any[], types: Record) { + const labels = new Set() + for (const f of features) + if (f.datum_label) { + if ( + !types[f.type]?.datum_allowed || + !/^[A-Z]{1,3}$/.test(f.datum_label) || + labels.has(f.datum_label) + ) + throw Error('基准标签需唯一且对应有效几何特征') + labels.add(f.datum_label) + } + for (const frame of frames) { + if ( + !frame.name?.trim() || + !Array.isArray(frame.precedence) || + frame.precedence.length < 1 || + frame.precedence.length > 3 || + frame.precedence.some((g: any) => !Array.isArray(g) || !g.length) + ) + throw Error('基准体系名称和主基准不能为空,并按优先级连续配置') + const ids = frame.precedence.flat() + if ( + new Set(ids).size !== ids.length || + ids.some((id: string) => !features.find((f) => f.id === id)?.datum_label) + ) + throw Error('基准体系包含重复或失效引用') + } +} + +export function selectDatumFeatures( + features: any[], + frames: any[], + frameId: string, + index: number, + ids: string[], + types: Record +) { + if (!Number.isInteger(index) || index < 0 || index > 2) throw Error('基准优先级无效') + const frame = frames.find((f) => f.id === frameId) + if (!frame) throw Error('基准体系已变化,请重新加载') + const allowed = new Set(datumCandidates(features, types).map((f) => f.id)) + if (new Set(ids).size !== ids.length || ids.some((id) => !allowed.has(id))) + throw Error('请选择可作为基准的有效几何特征') + const groups = frame.precedence.map((g: string[]) => [...g]) + while (groups.length <= index) groups.push([]) + groups[index] = [...ids] + while (groups.length > 1 && !groups.at(-1).length) groups.pop() + if (groups.slice(0, -1).some((g) => g.length === 0)) + throw Error('请按主、次、第三基准顺序配置;清空前一级前先清空后续基准') + const all = groups.flat() + if (new Set(all).size !== all.length) throw Error('同一特征不能重复用于不同基准优先级') + const labels: Record = {}, + pool = features.map((f) => ({ ...f })) + for (const id of ids) { + const feature = pool.find((f) => f.id === id) + if (!feature.datum_label) { + feature.datum_label = nextDatumLabel(pool) + labels[id] = feature.datum_label + } + } + return { + labels, + frames: frames.map((f) => (f.id === frameId ? { ...f, precedence: groups } : f)) + } +} diff --git a/am-web/src/views/lab/inspection/display.ts b/am-web/src/views/lab/inspection/display.ts index 56a3e23..8b883ab 100644 --- a/am-web/src/views/lab/inspection/display.ts +++ b/am-web/src/views/lab/inspection/display.ts @@ -20,3 +20,5 @@ export const inputName = (row: any, role: string) => { } } export const fileSize = (n: number) => (n ? `${(n / 1024 / 1024).toFixed(2)} MB` : '—') + +export { userMessage, methodLabel, drawingIssue } from '@/utils/inspectionPresentation' diff --git a/am-web/src/views/lab/inspection/featurePresentation.ts b/am-web/src/views/lab/inspection/featurePresentation.ts new file mode 100644 index 0000000..8abfc14 --- /dev/null +++ b/am-web/src/views/lab/inspection/featurePresentation.ts @@ -0,0 +1,206 @@ +const derivedFields = new Set([ + 'measurement_state', + 'assessment_state', + 'reason_code', + 'next_action', + 'workflow_note', + 'workflow_warnings', + 'extraction_audit', + 'measured', + 'evaluation', + 'evaluation_state', + 'result', + 'result_snapshot', + 'diagnostic', + 'status', + 'patch_mesh', + 'support_points', + 'preview_points', + 'scan_region', + 'scan_region_diagnostic' +]) +export function toleranceLabel(t: any): string { + if (!t) return '—' + if (t.mode === 'limits') + return t.lower != null && t.upper != null + ? `${t.lower}~${t.upper}` + : t.lower != null + ? `≥${t.lower}` + : `≤${t.upper}` + if (t.mode === 'upper') return `≤${t.upper}` + const signed = (x: number) => (x === 0 ? '0' : x > 0 ? `+${x}` : `${x}`) + return `${signed(t.upper)}/${signed(t.lower)}` +} +// Editable metadata defines dirtiness; multi-megabyte immutable geometry is not a form field. +export function definitionSignature(doc: any): string { + return JSON.stringify(doc, (key, value) => (derivedFields.has(key) ? undefined : value)) +} +export function definitionForExport(doc: any): any { + const outputs = new Set([ + 'extraction_audit', + 'measured', + 'result', + 'evaluation', + 'evaluation_state', + 'result_snapshot', + 'scan_region', + 'scan_region_diagnostic' + ]) + const copy = JSON.parse( + JSON.stringify(doc, (key, value) => (outputs.has(key) ? undefined : value)) + ) + invalidateFeatureResults(copy) + return copy +} +export function invalidateFeatureResults(doc: any): void { + for (const feature of doc.features) { + delete feature.extraction_audit + delete feature.measured + delete feature.status + delete feature.diagnostic + delete feature.scan_region + delete feature.scan_region_diagnostic + } + for (const control of doc.controls) { + delete control.result + for (const key of [ + 'measurement_state', + 'assessment_state', + 'reason_code', + 'next_action', + 'workflow_note', + 'workflow_warnings' + ]) + delete control[key] + } + delete doc.result_snapshot + delete doc.evaluation_state + delete doc.evaluation +} +export function useFeatureResults(graph: any): boolean { + if (graph.evaluation_state === 'stale') + return ( + graph.controls.length > 0 && + (graph.report_scope === 'feature_plan' || + !!graph.template_selection || + graph.controls.some((c: any) => c.required)) + ) + if (!graph.evaluation) return false + if (graph.report_scope === 'feature_plan' && graph.controls.length) return true + if (graph.controls.some((c: any) => c.result?.value != null)) return true + if (graph.legacy_migration) return false + return ( + !!graph.template_selection || + graph.controls.some( + (c: any) => c.required || !['cad_geometry', 'drawing_recommendation'].includes(c.origin) + ) + ) +} +export function combinedResultRows(plan: any[], features: any[]): any[] { + return [ + ...plan.map((row, plan_index) => ({ + ...row, + plan_index, + ...(row.measured_mm == null && row.trial_measured_mm != null + ? { + measured_mm: row.trial_measured_mm, + error_mm: row.nominal_mm == null ? null : row.trial_measured_mm - row.nominal_mm, + inspection_result: '待判定' + } + : {}), + result_source: '检测计划' + })), + ...features.map((row) => ({ ...row, result_source: 'CAD 特征' })) + ] +} +export type ResultLoadState = 'idle' | 'loading' | 'ready' | 'error' +export function snapshotResultRows( + plan: any[], + features: any[], + primary: boolean, + state: ResultLoadState +): any[] { + return state === 'ready' ? combinedResultRows(primary ? [] : plan, features) : [] +} +export function featureDisplayControls(graph: any, hasPlan: boolean): any[] { + if (!useFeatureResults(graph)) return [] + const controls = + !hasPlan || graph.template_selection + ? graph.controls + : graph.controls.filter( + (c: any) => + c.required || + !['cad_geometry', 'drawing_recommendation'].includes(c.origin) || + c.result?.value != null + ) + return graph.evaluation_state === 'stale' + ? controls.map((c: any) => ({ + ...c, + result: { status: 'stale' }, + measurement_state: 'pending', + assessment_state: 'pending', + reason_code: 'result_stale', + next_action: 'recalculate', + workflow_note: '检测条件已更新,请重新计算;历史报告仍可查看。' + })) + : controls +} + +export function resultNote( + row: any, + sanitize: (value: any, fallback?: string) => string = ( + _value, + fallback = '请核对测量位置与提取参数' + ) => fallback +): string { + const diagnostic = row.workflow_note || row.diagnostic || row.measurement_reason || '' + if ( + row.reason_code === 'nominal_mismatch' || + /与计划名义.*不一致|CAD 尺寸.*不一致/.test(diagnostic) + ) + return 'CAD 尺寸与计划不一致,请核对位置或模型版本' + if ( + row.measurement_state === 'computed_unverified' || + (row.trial_measured_mm != null && + row.measurement_status !== '自动测量' && + /门槛|候选试测/.test(diagnostic)) + ) + return '拟合质量未通过,请核对扫描覆盖与提取范围' + const labels: any = { + result_stale: '检测条件已更新,请重新计算;历史报告仍可查看。', + binding_required: '请选择测量位置', + ambiguous_binding: '存在多个匹配位置,请选择对应要素', + no_points_in_region: '当前选区未提取到扫描点,请先核对位置与对齐', + insufficient_support: '当前选区支持点不足,请核对提取范围与局部扫描', + insufficient_coverage: '当前特征覆盖不足,请核对选区与扫描覆盖', + reference_extraction_failed: row.workflow_note || '参考要素提取失败,请核对对应测量位置', + insufficient_scan: '当前特征支持不足,请核对选区与局部扫描', + datum_required: '请设置基准或检查基准扫描数据', + unsupported: '当前测量方式不支持此项配置', + cad_unavailable: '设计模型读取失败,请检查模型文件', + alignment_check: '请核对单位与对齐结果', + tolerance_unset: '未配置公差,保留测量值', + capability_unverified: '已有测量值,判定依据待完善' + } + if (labels[row.reason_code]) return labels[row.reason_code] + if (row.measured_mm == null) { + if (diagnostic) return sanitize(diagnostic, '请核对测量位置与提取参数') + return '请选择测量位置并计算' + } + if (!row.tol_text && !row.tolerance) return labels.tolerance_unset + if (row.status === 'capability_unverified') return labels.capability_unverified + return '' +} +export function resultAction(row: any): string { + const labels: Record = { + recalculate: '重新计算', + tolerance: '设置公差', + datum: '设置基准', + capability: '完善判定依据', + scan: '检查扫描', + parameters: '调整参数', + model: '检查模型', + alignment: '检查对齐' + } + return labels[row.next_action] || (row.measured_mm == null ? '选择测量位置' : '定位复核') +} diff --git a/am-web/src/views/lab/inspection/geometry.ts b/am-web/src/views/lab/inspection/geometry.ts index 1b8f9a6..e5cd041 100644 --- a/am-web/src/views/lab/inspection/geometry.ts +++ b/am-web/src/views/lab/inspection/geometry.ts @@ -63,3 +63,34 @@ export function nearestPoint(hits: ScreenPoint[], x: number, y: number, radius = } return nearest } + +export function selectedCadFaces(features: any[], selected: string[]): any[] { + const ids = new Set(selected) + return features.filter( + (f) => + ids.has(f.id) || (!f.nominal_feature_group && f.source?.face_ids?.some((id) => ids.has(id))) + ) +} + +export function mergedAxialRange( + features: any[], + center: number[], + axis: number[] +): [number, number] { + const length = Math.hypot(...axis) + if (!length || !xyz(center)) throw new Error('请核对合并特征的轴线') + const n = axis.map((v) => v / length) + const values = features.flatMap((f) => { + const g = f.nominal, + length = Math.hypot(...(g.axis || [])) + if (!xyz(g.center) || !length || g.axial_range?.length !== 2) + throw new Error('所选曲面缺少有效轴向范围') + return g.axial_range.map((z: number) => + n.reduce( + (total, value, i) => total + (g.center[i] + (z * g.axis[i]) / length - center[i]) * value, + 0 + ) + ) + }) + return [Math.min(...values), Math.max(...values)] +} diff --git a/am-web/src/views/lab/inspection/measurementOptions.ts b/am-web/src/views/lab/inspection/measurementOptions.ts new file mode 100644 index 0000000..0fbdb91 --- /dev/null +++ b/am-web/src/views/lab/inspection/measurementOptions.ts @@ -0,0 +1,223 @@ +/** Validate user-supplied measurement definitions without inventing physical defaults. */ +export function measurementParameterError( + kind: string, + featureType: string | undefined, + p: any +): string { + const finite = (v: any) => typeof v === 'number' && Number.isFinite(v) + if ( + ['distance', 'length', 'thickness', 'hole_distance', 'chamfer'].includes(kind) && + p.mode && + ![ + 'center', + '3d_center', + 'projected', + 'plane_distance', + 'point_plane', + 'axis_distance', + 'surface_minimum' + ].includes(p.mode) + ) + return '请选择有效的测量方式' + if ( + kind === 'angle' && + p.angle_mode && + !['acute', 'directed', 'supplementary'].includes(p.angle_mode) + ) + return '请选择角度定义' + if (['circular_runout', 'total_runout'].includes(kind)) { + if (p.runout_direction && !['axial', 'radial'].includes(p.runout_direction)) + return '请选择跳动方向' + if ( + p.min_coverage_deg != null && + (!finite(p.min_coverage_deg) || p.min_coverage_deg <= 0 || p.min_coverage_deg > 360) + ) + return '圆周覆盖应大于 0° 且不超过 360°' + if ( + kind === 'circular_runout' && + p.runout_direction === 'axial' && + (!finite(p.max_ring_width_mm) || p.max_ring_width_mm <= 0) + ) + return '请设置实际圆环带宽' + } + if (kind === 'fitting_diameter' && !['internal', 'external'].includes(p.material_side)) + return '请选择内孔或外圆' + if (['parallelism', 'perpendicularity', 'angularity'].includes(kind) && featureType !== 'plane') { + if (!finite(p.evaluation_length_mm) || p.evaluation_length_mm <= 0) + return '请填写大于零的轴线评价长度' + if (!['cylindrical', 'parallel_planes'].includes(p.zone)) return '请选择公差带形状' + } + if (kind === 'angularity' && (!finite(p.angle_deg) || p.angle_deg < 0 || p.angle_deg > 180)) + return '请填写 0–180° 的理论角度' + if (kind === 'arc_length' && (!finite(p.sweep_deg) || p.sweep_deg <= 0 || p.sweep_deg > 360)) + return '请填写大于 0° 且不超过 360° 的弧段角度' + if (p.direction_feature_id) { + if (p.direction != null) return '请选择参考特征或指定向量之一' + if (p.direction_source && !['nominal', 'measured'].includes(p.direction_source)) + return '请选择设计或实测参考方向' + } else if ( + p.direction != null || + ['chamfer', 'extent'].includes(kind) || + p.mode === 'projected' + ) { + if ( + !Array.isArray(p.direction) || + p.direction.length !== 3 || + !p.direction.every(finite) || + Math.hypot(...p.direction) === 0 + ) + return '请填写完整且非零的测量方向' + } + return '' +} + +/** CAD values are for nominal definitions only; never called to fill scan results. */ +export function nominalFromGeometry( + c: any, + f: any, + other?: any, + features: any[] = [] +): number | null { + const a = f?.nominal, + b = other?.nominal + let p = c.parameters || {} + const dot = (x: number[], y: number[]) => x.reduce((s, n, i) => s + n * y[i], 0) + const unit = (x: number[]) => { + const length = Math.hypot(...x) + if (!length) throw Error('zero direction') + return x.map((v) => v / length) + } + try { + if (p.direction_feature_id) { + const ref = + features.find((v) => v.id === p.direction_feature_id) || + (f?.id === p.direction_feature_id ? f : undefined) + if (!ref?.nominal?.axis) return null + p = { ...p, direction: ref.nominal.axis } + } + if (['diameter', 'fitting_diameter'].includes(c.kind)) return 2 * a.radius + if (['radius', 'fillet_radius'].includes(c.kind)) return a.radius + if (c.kind === 'taper') return (2 * a.semi_angle * 180) / Math.PI + if (c.kind === 'arc_length' && p.sweep_deg) return (a.radius * p.sweep_deg * Math.PI) / 180 + if (c.kind === 'extent' && p.direction) { + const direction = unit(p.direction), + points = a.patch_mesh?.vertices || a.support_points + if (points?.length) { + const values = points.map((v: number[]) => dot(v, direction)) + let lo = Infinity, + hi = -Infinity + for (const v of values) { + lo = Math.min(lo, v) + hi = Math.max(hi, v) + } + return hi - lo + } + if (a.bounds && direction.filter((v: number) => Math.abs(v) > 1e-8).length === 1) + return Math.abs( + dot( + a.bounds[1].map((v: number, i: number) => v - a.bounds[0][i]), + direction + ) + ) + return null + } + if (!b) return null + const d = a.center.map((n: number, i: number) => n - b.center[i]) + if (c.kind === 'angle') { + const cosine = dot(unit(a.axis), unit(b.axis)), + angle = + (Math.acos( + Math.max(-1, Math.min(1, p.angle_mode === 'directed' ? cosine : Math.abs(cosine))) + ) * + 180) / + Math.PI + return p.angle_mode === 'supplementary' ? 180 - angle : angle + } + const mode = + p.mode || + (c.kind === 'thickness' + ? 'plane_distance' + : p.direction + ? 'projected' + : c.kind === 'hole_distance' + ? 'axis_distance' + : 'center') + if (mode === 'surface_minimum') return null + if (mode === 'projected') { + const v = dot(d, unit(p.direction)) + return p.signed ? v : Math.abs(v) + } + if (mode === 'plane_distance') { + if (f.type !== 'plane' || other.type !== 'plane') return null + const axis = unit(p.direction || a.axis), + na = unit(a.axis), + nb = unit(b.axis) + if (Math.abs(dot(na, nb)) < 0.99 || Math.abs(dot(nb, axis)) < 1e-6) return null + return Math.abs(dot(d, nb) / dot(nb, axis)) + } + if (mode === 'point_plane') { + const plane = f.type === 'plane' ? a : b, + point = f.type === 'plane' ? b : a + return Math.abs( + dot( + point.center.map((v: number, i: number) => v - plane.center[i]), + unit(plane.axis) + ) + ) + } + if (mode === 'axis_distance') { + const n = unit(a.axis), + m = unit(b.axis), + cross = [n[1] * m[2] - n[2] * m[1], n[2] * m[0] - n[0] * m[2], n[0] * m[1] - n[1] * m[0]] + if (Math.hypot(...cross) > 1e-6) + return c.kind === 'hole_distance' ? null : Math.abs(dot(d, unit(cross))) + const z = dot(d, n) + return Math.sqrt(Math.max(0, dot(d, d) - z * z)) + } + return Math.hypot(...d) + } catch { + return null + } +} + +export function toleranceError(t: any, size: boolean, nominal: any): string { + if (!t) return '' + if (t.mode === 'limits') { + const values = [t.lower, t.upper].filter((v) => v != null) + return !size || + !values.length || + values.some((v) => !Number.isFinite(v)) || + (t.lower != null && t.upper != null && t.lower > t.upper) + ? '请填写有效的尺寸上限或下限' + : '' + } + if ( + !Number.isFinite(t.upper) || + !Number.isFinite(t.lower) || + t.upper < t.lower || + (!size && (t.upper < 0 || t.lower !== 0)) + ) + return '公差上下限无效' + return size && !Number.isFinite(nominal) ? '有尺寸偏差时需填写名义值' : '' +} +export function setToleranceBound(c: any, key: string, value: any, size: boolean): void { + if (value == null) { + if (c.tolerance?.mode === 'limits') { + delete c.tolerance[key] + if (c.tolerance.lower == null && c.tolerance.upper == null) c.tolerance = null + } else c.tolerance = null + return + } + c.tolerance ||= { mode: size ? 'bilateral' : 'upper', upper: 0, lower: 0 } + c.tolerance[key] = value +} +export function setToleranceMode(c: any, mode: string): void { + const old = c.tolerance + if (old?.mode === mode) return + const offset = Number.isFinite(c.nominal) ? (mode === 'limits' ? c.nominal : -c.nominal) : null + c.tolerance = { + mode, + lower: old?.lower != null && offset != null ? old.lower + offset : null, + upper: old?.upper != null && offset != null ? old.upper + offset : null + } +} diff --git a/am-web/src/views/lab/inspection/stlDownload.ts b/am-web/src/views/lab/inspection/stlDownload.ts new file mode 100644 index 0000000..6f31248 --- /dev/null +++ b/am-web/src/views/lab/inspection/stlDownload.ts @@ -0,0 +1,43 @@ +export async function downloadProcessedStl( + api: { + state: () => Promise + start: (revision: number) => Promise + file: () => Promise + save: (file: Blob) => void + }, + onProgress: (value: any) => void, + active: () => boolean = () => true, + wait: () => Promise = () => new Promise((resolve) => setTimeout(resolve, 1500)), + now: () => number = Date.now +): Promise { + const started = now() + let state = await api.state() + if (!active()) return false + let progress = state.stl_export || {} + if (!['processing', 'done'].includes(progress.status)) + progress = (await api.start(state.revision)).stl_export || {} + while (active()) { + onProgress(progress) + if (progress.status === 'done') { + const file = await api.file() + const header = await file.slice(0, 84).arrayBuffer() + if ( + header.byteLength !== 84 || + new DataView(header).getUint32(80, true) < 1 || + file.size !== 84 + 50 * new DataView(header).getUint32(80, true) + ) + throw Error('STL 文件无效,请重新生成') + if (!active()) return false + api.save(file) + return true + } + if (progress.status === 'error' || progress.status === 'stale') + throw Error(progress.message || 'STL 生成失败,请重新生成') + if (now() - started > 660000) throw Error('STL 生成时间较长,请稍后重新下载') + await wait() + if (!active()) return false + state = await api.state() + progress = state.stl_export || {} + } + return false +} diff --git a/am-web/src/views/lab/inspection/templates.vue b/am-web/src/views/lab/inspection/templates.vue index 1076f51..902bb29 100644 --- a/am-web/src/views/lab/inspection/templates.vue +++ b/am-web/src/views/lab/inspection/templates.vue @@ -1,527 +1,33 @@ - diff --git a/deploy/windows11/RELEASE-20261118-cad-inspection.md b/deploy/windows11/RELEASE-20261118-cad-inspection.md new file mode 100644 index 0000000..71d2340 --- /dev/null +++ b/deploy/windows11/RELEASE-20261118-cad-inspection.md @@ -0,0 +1,66 @@ +# CAD 特征、基准与处理后 STL + +本次在原有任务尺寸比对工作区中接入同级 ai-scanner 的 CAD 特征检测组件。计算由独立的检测 EXE 完成,平台不自行用前端拟合结果代替检测服务判定。 + +## 使用入口 + +- 任务的尺寸比对工作区新增“CAD 特征”:在数模选面、预览并应用匹配、调整提取范围、提取点云特征和计算控制项。 +- 检测项根据 EXE 的能力清单显示尺寸与形位公差类型;不支持、拟合不足、待复核及未验证能力的结果保留原始状态。 +- 支持设置基准标签、主/次/第三基准优先级及共同基准,控制项可关联基准体系。 +- “维护检测计划”提供 CAD 特征计划及原有检测计划两个入口。新特征模板保存描述、名义几何、公差与基准关系,应用到其他 CAD 时重新匹配,不复制上次测量结果或有效绑定。 +- 点云处理及结果页面提供“下载处理后 STL”,显示生成进度,校验文件后下载。它不直接确认交付;交付仍使用现有 STL/PDF 成套归档和确认流程。报告已生成而 STL 尚未就绪时,生成 STL 后可在任务中“重试成果归档”。 + +## 检测 EXE 契约 + +沿用 `lab.inspection.base-url`,模板默认通过 `INSPECTION_PYTHON_BASE_URL` 指向 `http://127.0.0.1:8769`。实际环境配置和现场私有配置不由此次移植改写。 + +新版 EXE 需要提供以下契约;用户另行安装和维护 EXE,`update.ps1` 不负责升级 EXE: + +| 方法与任务路径 | 用途 | +| --- | --- | +| `GET /api/health` | 返回 `feature_capabilities.types` 和 `feature_capabilities.controls`,用于可用特征、公差及基准资格 | +| `GET /api/tasks/{id}/cad-features` | CAD 名义特征、稳定面标识及三角网格 | +| `GET/POST /api/tasks/{id}/feature-plan` | 读取或保存 v2 特征定义,包含 revision、mm 单位、features、controls、datum_systems | +| `POST .../feature-proposals` | `mode:preview` 仅预览,`mode:apply` 应用匹配 | +| `POST .../feature-construct`、`POST .../feature-template` | 构造特征及应用模板 | +| `POST .../feature-evaluate` | 提取并评价,返回明确结果或诊断状态 | +| `POST .../feature-report` | 发布报告及新的成果版本 | +| `POST .../cleanup` | `operation:export_stl`,携带当前 revision | +| `GET /api/tasks/{id}` | 原有状态之外,提供 `stl_export.status/progress/message`,导出失效时返回 stale/error | +| `GET .../files/cleaned_source.stl` | 当前处理后点云生成的有效二进制 STL | +| `GET .../files/feature_results.json` | 与发布报告对应的完整特征结果快照;有 result_snapshot_id 时必须与文档的 result_snapshot.id 一致 | + +创建检测任务时,特征模板通过服务端读取的 `feature_template_id`、`feature_template_snapshot` 传给 EXE;原有计划继续使用 `plan_template_snapshot`。原始文件仍由平台校验归属、版本及校验和后提交。 + +未返回能力清单的旧 EXE 仍可使用原有计划;CAD 入口会停用,安装新版后点击工作区“刷新状态”或重新打开。匹配预览和 STL 导出不改变等待新报告的业务状态。编辑后的计算结果与历史发布报告分开,归档时从 EXE 获取发布快照,并在传输后再次核对成果版本。 + +生成特征报告后切换到成果页并刷新归档状态,不立即下载旧 PDF。当前成果尚未归档、归档失败或正在等待新版本时,PDF 下载保持停用,后端同样拒绝把上一版交付文件当作本版返回。只读及计算服务离线时禁用编辑控件,仍可查看定义;切换样件或关闭工作区后,延迟响应不会覆盖下一样件或继续发起后续计算。 + +## 数据库及获准发布后的升级 + +新增幂等、只建表的 `am-backend/sql/freescan/018_inspection_cad_features.sql`: + +- `lab_inspection_feature_plan`:按租户与检测记录保存版本化定义、当前评价结果。 +- `lab_inspection_feature_template`:按租户保存可复用模板,使用乐观版本校验。 + +该迁移已登记到 `scripts/bootstrap_standalone.py` 的批准增量清单,现有 `deploy/windows11/update.ps1` 的 `--upgrade` 阶段自动执行。既有模板、任务、用户、菜单及历史报告不做全量覆盖,不引入 ai-scanner 的业务数据或恢复数据 SQL。前端新增开发依赖 `@types/three@0.181.0`,锁文件已同步,发布仍使用 `pnpm install --frozen-lockfile` 构建。 + +本次仅准备代码和升级路径,没有发布授权。之后每次发布仍按 `PRODUCTION-RELEASE.md`:用户当次明确要求发布、现场空闲,正式 AI 通过 `update.ps1` 更新并核对 `deployment.json`;不手工换 JAR,不执行全量迁移或空库初始化。 + +## 验证范围 + +开发验证使用本机 HTTP 模拟服务与 H2 内存数据库;核验权限与任务归属、模板脱敏和重新匹配、版本冲突、预览/导出状态、报告快照一致性、下载校验、超时及页面卸载处理,并执行现有相关回归及前后端构建。 + +后端实验室模块 239 项测试及完整 JAR 打包通过;前端 17 项相关行为测试通过,并执行改动范围的类型检查、ESLint / Stylelint / Prettier 检查和完整 standalone 构建。测试不包含真实 EXE 算法及界面交互验收。 + +初次移植验证没有连接现场设备、正式服务或正式数据库。Windows 界面自动化通道返回访问拒绝,浏览器交互验证受限;安装包的后续接口联调结果见下节,真实零件匹配精度及计量能力仍需现场验收。任务新增测试源码、模拟页面、构建输出和临时日志在验证结束后清理。 + +## 2026-11-18 安装包接口联调补充 + +用户安装 EXE 后,已在开发库 `192.168.28.10/am-freescan` 执行 018 增量,仅创建两张特征表;重复执行新增结构为零。修正基础资产清单将 018 误作种子数据的问题,完整离线升级清单可通过检查,没有运行初始化或全量迁移。 + +使用同一安装包的本机独立实例与新 Java 检测网关、业务服务及开发 MySQL 完成 17 项联调。独立实例仅绑定回环地址,输出集中于本轮验证目录。合成样例包含 6 个平面、1 个圆柱面、A/B/C 基准及 9 项尺寸/形位控制;孔径设计值 10 mm,实测约 9.991989 mm;处理后 STL 共 95,191 个三角面,PDF/STL 成套归档、PDF 下载及发布特征快照冻结均通过。EXE 返回的 `capability_unverified` 保留为待核验状态,平台未转换为合格。 + +修正 STL 归档对新版内容指纹的误判:`stl_export.input_revision` 可以为哈希值,不能与数字清理修订号比较;归档时核对下载前后的导出状态、输入指纹、清理及报告版本。旧数字版本兼容,显式返回文件名时同样检查版本与就绪状态,发生变化或 stale 时仍拒绝归档。验证数据清理脚本已补齐新特征表,并保护仍被非验证作业引用的模板。 + +本次后端 232 项测试及完整打包、29 项既有 Python 检查及 3 项新增清理边界检查通过。此次接口联调没有启动完整业务后端,也未重启现有旧版 IDEA 实例;新页面接口的启用仍须按项目约定,以隔离开发配置重新启动新版后端。浏览器交互验收及真实零件计量验收不包含在本次接口联调结果中。此次测试任务、模板、执行数据及临时文件均按验证批次清理,未修改正式库、设备配置或正式服务,也未提交或推送。 diff --git a/scripts/bootstrap_db.py b/scripts/bootstrap_db.py index a38cf94..091cbf7 100644 --- a/scripts/bootstrap_db.py +++ b/scripts/bootstrap_db.py @@ -136,7 +136,7 @@ def load_assets(): seeds = {} for path in sorted(SQL_ROOT.glob("*.sql")): if path.name.endswith("_schema.sql") or path.name in {"005_scan_only.sql", "006_resource_scheduling.sql", - "007_scanner_integration.sql", "008_scanner_execution_view.sql", "009_rotary_base_integration.sql", "010_scanner_framework_reference.sql", "011_fixture_framework.sql", "012_robot_service_endpoint.sql", "013_execution_plan.sql", "014_dimension_delivery.sql", "015_fixture_trajectory.sql", "017_dimension_comparison.sql"}: + "007_scanner_integration.sql", "008_scanner_execution_view.sql", "009_rotary_base_integration.sql", "010_scanner_framework_reference.sql", "011_fixture_framework.sql", "012_robot_service_endpoint.sql", "013_execution_plan.sql", "014_dimension_delivery.sql", "015_fixture_trajectory.sql", "017_dimension_comparison.sql", "018_inspection_cad_features.sql"}: # Dedicated additive migration runs after bootstrap_cmvr. It is not # a reference seed and must never pass through the seed executor. continue diff --git a/scripts/bootstrap_standalone.py b/scripts/bootstrap_standalone.py index ca9a098..729d0cb 100644 --- a/scripts/bootstrap_standalone.py +++ b/scripts/bootstrap_standalone.py @@ -35,7 +35,7 @@ MIGRATIONS = ( "008_scanner_execution_view.sql", "009_rotary_base_integration.sql", "010_scanner_framework_reference.sql", "011_fixture_framework.sql", "012_robot_service_endpoint.sql", "013_execution_plan.sql", "014_dimension_delivery.sql", - "015_fixture_trajectory.sql", "017_dimension_comparison.sql", + "015_fixture_trajectory.sql", "017_dimension_comparison.sql", "018_inspection_cad_features.sql", ) def plan(): diff --git a/scripts/cleanup_verification.py b/scripts/cleanup_verification.py index 0b17ef9..4541361 100644 --- a/scripts/cleanup_verification.py +++ b/scripts/cleanup_verification.py @@ -28,7 +28,8 @@ lab_sample lab_fixture lab_fixture_applicable lab_fixture_framework lab_fixture_ NATIVE_TABLES = '''aima_test_case aima_task aima_task_test_case aima_task_instance aima_test_log te_detection_item te_detection_item_version te_task_config_info te_task_orchestration te_task_inst te_task_inst_flow_version te_node_inst te_ai_evaluation'''.split() -TABLES = LAB_TABLES + NATIVE_TABLES + ['infra_file','lab_device','lab_scanner_command','lab_scanner_framework_transfer','lab_inspection_scan'] +TABLES = LAB_TABLES + NATIVE_TABLES + ['infra_file','lab_device','lab_scanner_command','lab_scanner_framework_transfer', + 'lab_inspection_feature_plan','lab_inspection_feature_template','lab_inspection_scan'] def plan_rows(data, prefixes=None): @@ -69,9 +70,25 @@ def plan_rows(data, prefixes=None): choose(table, lambda r: has(r, 'task_id', task_ids)) comparison_keys={(str(r.get('tenant_id')),str(r.get('engine_id'))) for r in rows('lab_dimension_comparison') if r.get('engine_id')} choose('lab_inspection_scan',lambda r:(str(r.get('tenant_id')),str(r.get('id'))) in comparison_keys) + choose('lab_inspection_feature_plan',lambda r:(str(r.get('tenant_id')),str(r.get('scan_id'))) in comparison_keys) + choose('lab_inspection_feature_template',lambda r:marked(r.get('name'))) + template_keys={(str(r.get('tenant_id')),str(r.get('id'))) for r in rows('lab_inspection_feature_template')} for index,row in enumerate(data.get('lab_dimension_comparison',[])): if index not in selected.get('lab_dimension_comparison',set()) and (str(row.get('tenant_id')),str(row.get('engine_id'))) in comparison_keys: raise ValueError('非测试比对作业仍引用待清理的计算记录') + if template_keys and index not in selected.get('lab_dimension_comparison',set()): + options=json.loads(row.get('options_json') or '{}') + selection=str(options.get('selected_template_id','')) + references={str(options.get('feature_template_id',''))} + if selection.startswith('feature-'): + references.add(selection[8:]) + snapshot=options.get('feature_template_snapshot') + if isinstance(snapshot,str): + snapshot=json.loads(snapshot) + if isinstance(snapshot,dict): + references.add(str(snapshot.get('id',''))) + if any((str(row.get('tenant_id')),identifier) in template_keys for identifier in references): + raise ValueError('非测试比对作业仍引用待清理的特征模板') if any(r.get('status') in ('SUBMITTING','UNKNOWN','PROCESSING','ARCHIVE_PENDING') for r in rows('lab_dimension_comparison')): raise ValueError('比对作业尚未确认终态,拒绝清理') execution_ids = ids('lab_execution')