From c903364fa2bf0ca2687cdef3aad242a2c4bcfbd3 Mon Sep 17 00:00:00 2001 From: lixiaolong <702156524@qq.com> Date: Thu, 12 Nov 2026 10:24:55 +0800 Subject: [PATCH] feat: integrate dimension comparison and optimize task workbench Connect task CAD, PDF and PLY to the supplier workspace and preserve paired result provenance. Add fixture framework download/copy, reduce idle map and task polling, improve tab navigation, and update standalone schema migration. --- .../sql/freescan/017_dimension_comparison.sql | 35 + .../inspection/LabInspectionController.java | 103 ++ .../LabInspectionTemplateController.java | 27 + .../master/LabFixtureFrameworkController.java | 7 +- .../service/dimension/DimensionService.java | 69 +- .../service/execution/LabAgvViewService.java | 9 +- .../inspection/LabComparisonResults.java | 99 ++ .../LabDimensionComparisonService.java | 221 +++ .../inspection/LabInspectionGateway.java | 119 ++ .../inspection/LabInspectionProperties.java | 15 + .../inspection/LabInspectionRepository.java | 27 + .../LabInspectionTemplateService.java | 105 ++ .../master/LabFixtureFrameworkService.java | 6 + .../inspection/plan-template-seeds.json | 474 ++++++ .../src/main/resources/application.yaml | 9 + am-web/src/api/lab/inspection/index.ts | 33 + am-web/src/api/lab/master/fixture/index.ts | 1 + am-web/src/api/lab/scan-task/agvView.ts | 6 +- am-web/src/config/axios/service.ts | 4 + am-web/src/router/modules/remaining.ts | 3 +- .../views/lab/dimension/ComparisonPanel.vue | 144 ++ am-web/src/views/lab/dimension/workbench.vue | 41 +- .../src/views/lab/document/report/index.vue | 2 +- .../lab/inspection/InspectionCleanup.vue | 568 +++++++ .../views/lab/inspection/InspectionViewer.vue | 628 ++++++++ .../lab/inspection/InspectionWorkbench.vue | 1395 +++++++++++++++++ am-web/src/views/lab/inspection/display.ts | 25 + am-web/src/views/lab/inspection/geometry.ts | 65 + .../src/views/lab/inspection/inspection.scss | 281 ++++ am-web/src/views/lab/inspection/templates.vue | 527 +++++++ .../views/lab/md/fixture/FixtureFramework.vue | 44 +- am-web/src/views/lab/md/fixture/detail.vue | 7 +- am-web/src/views/lab/md/fixture/index.vue | 2 +- am-web/src/views/lab/scan-task/AgvLiveMap.vue | 44 +- .../lab/scan-task/ScanExecutionMonitor.vue | 12 +- .../lab/scan-task/ScannerExecutionViews.vue | 5 +- am-web/src/views/lab/scan-task/agvMap.mjs | 6 +- am-web/src/views/lab/scan-task/index.vue | 50 +- .../views/lab/scan-task/workbenchPolling.mjs | 13 + deploy/windows11/README.md | 15 +- deploy/windows11/manage.ps1 | 1 + docs/dimension-comparison-source.json | 10 + scripts/apply_dimension_comparison.py | 41 + scripts/bootstrap_db.py | 2 +- scripts/bootstrap_standalone.py | 20 +- scripts/cleanup_verification.py | 11 +- 46 files changed, 5234 insertions(+), 97 deletions(-) create mode 100644 am-backend/sql/freescan/017_dimension_comparison.sql create mode 100644 am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/controller/admin/inspection/LabInspectionController.java create mode 100644 am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/controller/admin/inspection/LabInspectionTemplateController.java create mode 100644 am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/inspection/LabComparisonResults.java create mode 100644 am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/inspection/LabDimensionComparisonService.java create mode 100644 am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/inspection/LabInspectionGateway.java create mode 100644 am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/inspection/LabInspectionProperties.java create mode 100644 am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/inspection/LabInspectionRepository.java create mode 100644 am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/inspection/LabInspectionTemplateService.java create mode 100644 am-backend/yudao-module-lab/src/main/resources/inspection/plan-template-seeds.json create mode 100644 am-web/src/api/lab/inspection/index.ts create mode 100644 am-web/src/views/lab/dimension/ComparisonPanel.vue create mode 100644 am-web/src/views/lab/inspection/InspectionCleanup.vue create mode 100644 am-web/src/views/lab/inspection/InspectionViewer.vue create mode 100644 am-web/src/views/lab/inspection/InspectionWorkbench.vue create mode 100644 am-web/src/views/lab/inspection/display.ts create mode 100644 am-web/src/views/lab/inspection/geometry.ts create mode 100644 am-web/src/views/lab/inspection/inspection.scss create mode 100644 am-web/src/views/lab/inspection/templates.vue create mode 100644 am-web/src/views/lab/scan-task/workbenchPolling.mjs create mode 100644 docs/dimension-comparison-source.json create mode 100644 scripts/apply_dimension_comparison.py diff --git a/am-backend/sql/freescan/017_dimension_comparison.sql b/am-backend/sql/freescan/017_dimension_comparison.sql new file mode 100644 index 0000000..7cad5f6 --- /dev/null +++ b/am-backend/sql/freescan/017_dimension_comparison.sql @@ -0,0 +1,35 @@ +-- Selected supplier inspection support; business task/scan state machines and menus are retained. +CREATE TABLE IF NOT EXISTS lab_inspection_scan ( + id varchar(32) NOT NULL PRIMARY KEY, tenant_id bigint NOT NULL, title varchar(200) NOT NULL, + status varchar(32) NOT NULL DEFAULT 'processing', report_ready bit NOT NULL DEFAULT b'0', + report_revision varchar(100) NULL, archive_status varchar(32) NOT NULL DEFAULT 'pending', + inputs_json longtext NULL, settings_json longtext NULL, state_json longtext NULL, plan_json longtext NULL, + last_error varchar(2000) 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, + KEY idx_inspection_scan_tenant(tenant_id,create_time) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; +CREATE TABLE IF NOT EXISTS lab_inspection_template ( + id varchar(32) NOT NULL PRIMARY KEY, tenant_id bigint NOT NULL, name varchar(100) NOT NULL, + description varchar(1000) NOT NULL DEFAULT '', part_numbers varchar(500) NOT NULL DEFAULT '', + enabled boolean NOT NULL DEFAULT TRUE, revision int NOT NULL DEFAULT 1, rows_json longtext NOT NULL, + row_count int NOT NULL, builtin_key varchar(100) NULL, deleted boolean NOT NULL DEFAULT FALSE, + 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, + UNIQUE KEY uk_inspection_template_seed(tenant_id,builtin_key), + KEY idx_inspection_template_tenant(tenant_id,deleted,enabled) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; +CREATE TABLE IF NOT EXISTS lab_dimension_comparison ( + id varchar(32) NOT NULL PRIMARY KEY, tenant_id bigint NOT NULL, task_id bigint NOT NULL, + unit_id bigint NOT NULL, case_id bigint NOT NULL, source_execution_id bigint NULL, + engine_id varchar(32) NULL, submission_key varchar(64) NOT NULL, + input_signature varchar(64) NOT NULL, input_json longtext NOT NULL, options_json longtext NOT NULL, + status varchar(32) NOT NULL, engine_revision varchar(100) NULL, awaiting_revision varchar(100) NULL, delivery_id bigint NULL, + last_error varchar(2000) NULL, creator varchar(64) NOT NULL, + create_time datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), + update_time datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6), + UNIQUE KEY uk_dimension_submission(tenant_id,submission_key), + UNIQUE KEY uk_dimension_engine(tenant_id,engine_id), + KEY idx_dimension_comparison_case(tenant_id,case_id,create_time), + KEY idx_dimension_comparison_poll(status,update_time) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; 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 new file mode 100644 index 0000000..72f109a --- /dev/null +++ b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/controller/admin/inspection/LabInspectionController.java @@ -0,0 +1,103 @@ +package cn.iocoder.yudao.module.lab.controller.admin.inspection; + +import cn.iocoder.yudao.framework.common.pojo.CommonResult; +import cn.iocoder.yudao.framework.security.core.service.SecurityFrameworkService; +import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder; +import cn.iocoder.yudao.module.lab.service.inspection.*; +import cn.iocoder.yudao.module.lab.service.dimension.DimensionService; +import com.fasterxml.jackson.databind.ObjectMapper; +import jakarta.annotation.Resource; +import jakarta.servlet.http.*; +import jakarta.validation.Valid; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.server.ResponseStatusException; +import org.springframework.http.HttpStatus; +import org.springframework.jdbc.core.JdbcTemplate; +import java.io.*; +import java.nio.file.*; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.*; + +@RestController @RequestMapping("/lab/inspection") +public class LabInspectionController { + @Resource private LabInspectionGateway gateway; + @Resource private LabInspectionRepository repository; + @Resource private LabDimensionComparisonService comparisons; + @Resource private LabInspectionTemplateService templates; + @Resource private DimensionService dimensions; + @Resource private SecurityFrameworkService security; + @Resource private JdbcTemplate jdbc; + @Resource private ObjectMapper mapper; + @GetMapping("/health") @PreAuthorize("@ss.hasPermission('lab:task:query') or @ss.hasPermission('lab:result:query')") + public CommonResult health(){return CommonResult.success(gateway.health());} + @GetMapping("/comparison") @PreAuthorize("@ss.hasPermission('lab:task:query')") + public CommonResult comparison(@RequestParam long taskId,@RequestParam long unitId){return CommonResult.success(comparisons.latestView(taskId,unitId));} + @PostMapping("/comparison/start") @PreAuthorize("@ss.hasPermission('lab:data:upload')") + public CommonResult start(@Valid @RequestBody LabDimensionComparisonService.Start req){return CommonResult.success(comparisons.start(req));} + @GetMapping("/records/{id}") @PreAuthorize("@ss.hasPermission('lab:task:query') or @ss.hasPermission('lab:result:query')") + public CommonResult record(@PathVariable String id) throws Exception{return CommonResult.success(comparisons.savedState(id));} + @PostMapping("/records/{id}/sync") @PreAuthorize("@ss.hasPermission('lab:data:upload') or @ss.hasPermission('lab:document:update')") + public CommonResult sync(@PathVariable String id) throws Exception{return CommonResult.success(comparisons.synchronize(id));} + @GetMapping("/api/**") @PreAuthorize("@ss.hasPermission('lab:task:query') or @ss.hasPermission('lab:result:query')") + public CommonResult get(HttpServletRequest request,HttpServletResponse response) throws Exception{return relay(request,response);} + @PostMapping("/api/**") @PreAuthorize("@ss.hasPermission('lab:data:upload') or @ss.hasPermission('lab:result:confirm') or @ss.hasPermission('lab:document:update')") + public CommonResult post(HttpServletRequest request,HttpServletResponse response) throws Exception{return relay(request,response);} + private CommonResult relay(HttpServletRequest request,HttpServletResponse response) throws Exception { + String uri=request.getRequestURI(),path=uri.substring(uri.indexOf("/lab/inspection")+"/lab/inspection".length()),method=request.getMethod(); + gateway.authorize(path,method); + String engine=path.matches("/api/tasks/[a-f0-9]{32}.*")?path.split("/")[3]:null; + 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) { + String name=path.substring(path.lastIndexOf('/')+1); + if(Set.of("report_signed_chromatogram.pdf","report.pdf","platform-result.stl").contains(name)) { + 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()); + response.setContentType(name.endsWith(".pdf")?"application/pdf":"application/octet-stream");response.setHeader("Cache-Control","private, no-store");response.setHeader("X-Content-Type-Options","nosniff"); + response.setHeader("Content-Disposition","attachment; filename*=UTF-8''"+URLEncoder.encode(file.get("name").toString(),StandardCharsets.UTF_8));Files.copy((Path)file.get("path"),response.getOutputStream());return null; + } + } + 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,"检测计划请求内容过多"); + 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())); + } + java.net.http.HttpResponse upstream; + try{upstream=gateway.forward(path,method,body);}catch(ResponseStatusException failure) { + if(method.equals("GET")&&path.matches("/api/tasks/[a-f0-9]{32}")) { + var cached=comparisons.savedState(engine);cached.put("engine_unavailable",true);return CommonResult.success(cached); + } + if(method.equals("GET")&&path.endsWith("/plan")&&engine!=null) { + var json=repository.scan(TenantContextHolder.getRequiredTenantId(),engine).get("plan_json"); + if(json!=null)return CommonResult.success(mapper.readValue(json.toString(),Object.class)); + } + throw failure; + } + if(binary&&upstream.statusCode()<400) { + response.setContentType(upstream.headers().firstValue("Content-Type").orElse("application/octet-stream"));response.setHeader("X-Content-Type-Options","nosniff");response.setHeader("Cache-Control","private, no-store"); + upstream.headers().firstValue("Content-Disposition").ifPresent(v->response.setHeader("Content-Disposition",v));try(var in=upstream.body()){in.transferTo(response.getOutputStream());}return null; + } + Object value=gateway.json(path,method,upstream); + if(engine!=null&&path.equals("/api/tasks/"+engine)&&value instanceof Map state) { + comparisons.observe(engine,state); + @SuppressWarnings("unchecked") var mutable=(Map)state;mutable.put("platform_job",comparisons.jobView(engine)); + } + return CommonResult.success(value); + } + @ExceptionHandler(ResponseStatusException.class) + public CommonResult upstreamError(ResponseStatusException error){return CommonResult.error(error.getStatusCode().value(),Objects.toString(error.getReason(),"检测请求失败"));} + @ExceptionHandler(org.springframework.dao.EmptyResultDataAccessException.class) + public CommonResult missing(){return CommonResult.error(404,"检测记录不存在");} + @ExceptionHandler(com.fasterxml.jackson.core.JsonProcessingException.class) + public CommonResult invalidJson(){return CommonResult.error(400,"检测数据格式无效,请检查检测计划或计算服务返回内容");} +} diff --git a/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/controller/admin/inspection/LabInspectionTemplateController.java b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/controller/admin/inspection/LabInspectionTemplateController.java new file mode 100644 index 0000000..55bcd11 --- /dev/null +++ b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/controller/admin/inspection/LabInspectionTemplateController.java @@ -0,0 +1,27 @@ +package cn.iocoder.yudao.module.lab.controller.admin.inspection; + +import cn.iocoder.yudao.framework.common.pojo.CommonResult; +import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder; +import cn.iocoder.yudao.module.lab.service.inspection.LabInspectionTemplateService; +import jakarta.annotation.Resource; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.server.ResponseStatusException; +import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId; + +@RestController @RequestMapping("/lab/inspection/templates") +public class LabInspectionTemplateController { + @Resource private LabInspectionTemplateService service; + @GetMapping("/page") @PreAuthorize("@ss.hasPermission('lab:result:query')") + public CommonResult page(@RequestParam(defaultValue="") String name,@RequestParam(defaultValue="") String enabled,@RequestParam(defaultValue="1") int pageNo,@RequestParam(defaultValue="20") int pageSize){return CommonResult.success(service.page(TenantContextHolder.getRequiredTenantId(),name,enabled,Math.max(1,pageNo),Math.max(1,Math.min(100,pageSize))));} + @GetMapping("/options") @PreAuthorize("@ss.hasPermission('lab:task:query') or @ss.hasPermission('lab:result:query') or @ss.hasPermission('lab:document:query')") + public CommonResult options(){return CommonResult.success(service.options(TenantContextHolder.getRequiredTenantId()));} + @GetMapping("/{id}") @PreAuthorize("@ss.hasPermission('lab:result:query')") + public CommonResult detail(@PathVariable String id){return CommonResult.success(service.detail(TenantContextHolder.getRequiredTenantId(),id));} + @PostMapping("/save") @PreAuthorize("@ss.hasPermission('lab:result:confirm')") + public CommonResult save(@RequestBody LabInspectionTemplateService.SaveRequest request){return CommonResult.success(service.save(TenantContextHolder.getRequiredTenantId(),request,java.util.Objects.toString(getLoginUserId(),"system")));} + @DeleteMapping("/{id}") @PreAuthorize("@ss.hasPermission('lab:result:confirm')") + public CommonResult remove(@PathVariable String id,@RequestParam int revision){service.remove(TenantContextHolder.getRequiredTenantId(),id,revision);return CommonResult.success(true);} + @ExceptionHandler(ResponseStatusException.class) + public CommonResult error(ResponseStatusException e){return CommonResult.error(e.getStatusCode().value(),e.getReason());} +} diff --git a/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/controller/admin/master/LabFixtureFrameworkController.java b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/controller/admin/master/LabFixtureFrameworkController.java index e6752d9..a5c1d78 100644 --- a/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/controller/admin/master/LabFixtureFrameworkController.java +++ b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/controller/admin/master/LabFixtureFrameworkController.java @@ -10,7 +10,12 @@ public class LabFixtureFrameworkController { private final LabFixtureFrameworkService service; @ExceptionHandler(com.cmvr.scanner.ScannerException.class) public CommonResult frameworkError(com.cmvr.scanner.ScannerException error){return CommonResult.error(error.remoteStatus,error.getMessage());} @GetMapping("/definition") @PreAuthorize("@ss.hasPermission('lab:fixture:query')") public CommonResult definition(){return CommonResult.success(service.definition());} - @GetMapping("/get") @PreAuthorize("@ss.hasPermission('lab:fixture:query')") public CommonResult get(@RequestParam Long fixtureId){return CommonResult.success(java.util.Map.of("history",service.history(fixtureId),"current",service.current(fixtureId)==null?java.util.Map.of():service.current(fixtureId)));} + @GetMapping("/get") @PreAuthorize("@ss.hasPermission('lab:fixture:query')") public CommonResult get(@RequestParam Long fixtureId){var history=service.history(fixtureId);var current=service.current(fixtureId);return CommonResult.success(java.util.Map.of("history",history,"current",current==null?java.util.Map.of():current));} + @GetMapping("/file") @PreAuthorize("@ss.hasPermission('lab:fixture:query') and @ss.hasPermission('lab:data:download')") + public org.springframework.http.ResponseEntity file(@RequestParam Long fixtureId,@RequestParam String version,@RequestParam String fileId){ + var binary=service.file(fixtureId,version,fileId);var headers=new org.springframework.http.HttpHeaders();headers.setContentType(org.springframework.http.MediaType.APPLICATION_OCTET_STREAM);headers.setCacheControl("private, no-store");headers.set("X-Content-Type-Options","nosniff");binary.headers().forEach((key,values)->{if(key.equalsIgnoreCase("content-length")||key.equalsIgnoreCase("content-disposition"))headers.put(key,values);}); + return org.springframework.http.ResponseEntity.ok().headers(headers).body(output->{try(binary){binary.stream().transferTo(output);}}); + } public record Start(Long fixtureId,String expectedVersion,boolean confirmed,TeTaskExecuteTrailVO resources){} public record ImportFiles(Long fixtureId,String expectedVersion,boolean confirmed,Object frameworkUrls){} @PostMapping("/import") @PreAuthorize("@ss.hasPermission('lab:fixture:update')") public CommonResult importFiles(@RequestBody ImportFiles body){if(body.fixtureId()==null)throw cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.invalidParamException("请选择夹具");return CommonResult.success(service.importFiles(body.fixtureId(),body.expectedVersion(),body.confirmed(),body.frameworkUrls()));} diff --git a/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/dimension/DimensionService.java b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/dimension/DimensionService.java index 21536fa..e8517f5 100644 --- a/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/dimension/DimensionService.java +++ b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/dimension/DimensionService.java @@ -48,6 +48,7 @@ public class DimensionService { @Resource private LabArtifactService artifacts; @Resource private LabScannerAssetArchive scannerArchives; @Resource private FileService infraFiles; + @Resource private cn.iocoder.yudao.module.lab.service.inspection.LabInspectionGateway inspectionGateway; @Data public static class Create { @NotBlank @Size(max=200) private String taskName; @Size(max=128) private String externalTaskNo; @@ -130,14 +131,14 @@ public class DimensionService { Long total=jdbc.queryForObject("SELECT COUNT(*)"+where,Long.class,args.toArray());args.add(size);args.add((page-1)*size); var list=rows("SELECT t.id,t.task_no,t.task_name,t.status,t.process_type,t.owner_id,t.create_time"+where+" ORDER BY t.id DESC LIMIT ? OFFSET ?",args.toArray()); for(var row:list){var units=unitSummaries(num(row.get("id")));row.put("unitCount",units.size());row.put("deliveredCount",units.stream().filter(u->"DELIVERED".equals(u.get("deliveryStage"))).count());row.put("deliveryStages",units.stream().map(u->u.get("deliveryStage")).distinct().toList());} - return map("list",list,"total",total,"comparisonConnected",false); + return map("list",list,"total",total,"comparisonIntegrated",true,"comparisonConnected",inspectionGateway!=null&&inspectionGateway.knownAvailable()); } private List> unitSummaries(long taskId){ var list=rows("SELECT u.id,u.unit_no,u.status,u.attempt_no,u.current_execution_id,e.create_time AS execution_created FROM lab_task_sample_unit u LEFT JOIN lab_execution e ON e.id=u.current_execution_id AND e.tenant_id=u.tenant_id AND e.deleted=0 WHERE u.task_id=? AND u.tenant_id=? AND u.deleted=0 ORDER BY u.unit_no",taskId,tenant()); Map> cases=new HashMap<>(),catalog=new HashMap<>();Map>> deliveries=new HashMap<>(); for(var row:rows("SELECT * FROM lab_dimension_case WHERE task_id=? AND tenant_id=? AND deleted=0",taskId,tenant()))cases.put(num(row.get("unit_id")),row); for(var row:rows("SELECT id,file_name,revision,sha256,size_bytes,source_execution_id,create_time FROM lab_dimension_file WHERE task_id=? AND tenant_id=? AND deleted=0",taskId,tenant()))catalog.put(num(row.get("id")),row); - for(var row:rows("SELECT case_id,input_json,status FROM lab_dimension_delivery WHERE task_id=? AND tenant_id=? AND deleted=0 ORDER BY id DESC",taskId,tenant()))deliveries.computeIfAbsent(num(row.get("case_id")),k->new ArrayList<>()).add(row); + for(var row:rows("SELECT id,case_id,external_no,input_json,status FROM lab_dimension_delivery WHERE task_id=? AND tenant_id=? AND deleted=0 ORDER BY id DESC",taskId,tenant()))deliveries.computeIfAbsent(num(row.get("case_id")),k->new ArrayList<>()).add(row); for(var unit:list){ var state=cases.getOrDefault(num(unit.get("id")),Map.of());String result="PREPARING"; var model=catalog.get(num(state.get("model_id")));var drawing=catalog.get(num(state.get("drawing_id")));var cloud=catalog.get(num(state.get("cloud_id"))); @@ -145,7 +146,7 @@ public class DimensionService { String signature=DigestUtil.sha256Hex(JSON.toJSONString(map("model",fileInfo(model),"drawing",fileInfo(drawing),"cloud",fileInfo(cloud)))); boolean changed=num(unit.get("current_execution_id"))>0&&(Set.of("RUNNING","PAUSED","QUEUED","STOP_PENDING").contains(unit.get("status"))||num(cloud.get("source_execution_id"))>0&&num(cloud.get("source_execution_id"))!=num(unit.get("current_execution_id"))||num(cloud.get("source_execution_id"))==0&&(unit.get("execution_created")==null||time(cloud.get("create_time")).isBefore(time(unit.get("execution_created"))))); result=changed?"SCAN_CHANGED":state.get("prepared_json")!=null&&signature.equals(JSON.parseObject(state.get("prepared_json").toString()).getString("signature"))?"WAITING_COMPARISON":"READY"; - if(!changed)for(var delivery:deliveries.getOrDefault(num(state.get("id")),List.of()))if(signature.equals(JSON.parseObject(delivery.get("input_json").toString()).getString("signature"))){result="DELIVERED".equals(delivery.get("status"))?"DELIVERED":"PENDING_CONFIRM";break;} + if(!changed)for(var delivery:deliveries.getOrDefault(num(state.get("id")),List.of()))if(signature.equals(JSON.parseObject(delivery.get("input_json").toString()).getString("signature"))&&comparisonDeliveryCurrent(delivery)){result="DELIVERED".equals(delivery.get("status"))?"DELIVERED":"PENDING_CONFIRM";break;} } unit.put("deliveryStage",result);unit.put("revision",state.getOrDefault("revision",0));unit.remove("execution_created"); } @@ -156,7 +157,7 @@ public class DimensionService { var fileList=rows("SELECT * FROM lab_dimension_file WHERE task_id=? AND tenant_id=? AND deleted=0 AND (unit_id=0 OR unit_id=?) ORDER BY id DESC",taskId,tenant(),unitId);fileList.forEach(r->r.remove("storage_path")); var outputs=rows("SELECT * FROM lab_dimension_delivery WHERE task_id=? AND unit_id=? AND tenant_id=? AND deleted=0 ORDER BY id DESC",taskId,unitId,tenant()); String signature=inputSignature(state,false); - for(var d:outputs)d.put("current",Objects.equals(JSON.parseObject(d.get("input_json").toString()).getString("signature"),signature)&&!newerScan(state)); + for(var d:outputs)d.put("current",Objects.equals(JSON.parseObject(d.get("input_json").toString()).getString("signature"),signature)&&!newerScan(state)&&comparisonDeliveryCurrent(d)); var candidates=rows("SELECT a.id,a.file_name,a.execution_id,a.size_bytes,a.sha256,a.create_time FROM lab_artifact_file a JOIN lab_execution e ON e.id=a.execution_id AND e.tenant_id=a.tenant_id AND e.deleted=0 WHERE a.task_id=? AND a.tenant_id=? AND a.deleted=0 AND a.file_status='AVAILABLE' AND a.checksum_status='MATCHED' AND e.sample_unit_id=? AND (LOWER(a.file_name) LIKE '%.ply' OR LOWER(a.file_name) LIKE '%.stl') ORDER BY a.id DESC",taskId,tenant(),unitId); for(var execution:rows("SELECT id FROM lab_execution WHERE task_id=? AND sample_unit_id=? AND tenant_id=? AND deleted=0 ORDER BY id DESC",taskId,unitId,tenant())){ long executionId=num(execution.get("id")); @@ -165,7 +166,7 @@ public class DimensionService { candidates.add(map("id","scanner:"+executionId+":"+asset.path("fileId").asText(),"file_id",asset.path("fileId").asText(),"file_name",name,"execution_id",executionId,"size_bytes",asset.path("bytes").asLong(),"source_type","SCANNER_ARCHIVE")); } } - return map("task",task,"units",unitSummaries(taskId),"case",state,"stage",stage(state),"files",fileList,"deliveries",outputs,"scanFiles",candidates,"events",rows("SELECT id,unit_id,event_type,detail_json,creator,create_time FROM lab_dimension_event WHERE task_id=? AND tenant_id=? ORDER BY id DESC LIMIT 200",taskId,tenant()),"uploadMaxBytes",files.uploadLimit(),"comparisonConnected",false); + return map("task",task,"units",unitSummaries(taskId),"case",state,"stage",stage(state),"files",fileList,"deliveries",outputs,"scanFiles",candidates,"events",rows("SELECT id,unit_id,event_type,detail_json,creator,create_time FROM lab_dimension_event WHERE task_id=? AND tenant_id=? ORDER BY id DESC LIMIT 200",taskId,tenant()),"uploadMaxBytes",files.uploadLimit(),"comparisonIntegrated",true,"comparisonConnected",inspectionGateway!=null&&inspectionGateway.knownAvailable()); } private Map file(long id){var found=rows("SELECT * FROM lab_dimension_file WHERE id=? AND tenant_id=? AND deleted=0",id,tenant());if(found.isEmpty())throw invalidParamException("文件不存在");return found.get(0);} private Map inputFile(Map state,String column,String role,boolean verify){ @@ -195,8 +196,8 @@ public class DimensionService { private String stage(Map row){ String signature=inputSignature(row,false);if(signature.isBlank())return "PREPARING"; if(newerScan(row))return "SCAN_CHANGED"; - var ds=rows("SELECT input_json,status FROM lab_dimension_delivery WHERE case_id=? AND tenant_id=? AND deleted=0 ORDER BY id DESC",row.getOrDefault("id",0),tenant()); - for(var d:ds)if(signature.equals(JSON.parseObject(d.get("input_json").toString()).getString("signature")))return "DELIVERED".equals(d.get("status"))?"DELIVERED":"PENDING_CONFIRM"; + var ds=rows("SELECT id,case_id,external_no,input_json,status FROM lab_dimension_delivery WHERE case_id=? AND tenant_id=? AND deleted=0 ORDER BY id DESC",row.getOrDefault("id",0),tenant()); + for(var d:ds)if(signature.equals(JSON.parseObject(d.get("input_json").toString()).getString("signature"))&&comparisonDeliveryCurrent(d))return "DELIVERED".equals(d.get("status"))?"DELIVERED":"PENDING_CONFIRM"; return row.get("prepared_json")!=null&&signature.equals(JSON.parseObject(row.get("prepared_json").toString()).getString("signature"))?"WAITING_COMPARISON":"READY"; } @Transactional(rollbackFor=Exception.class) @@ -208,8 +209,11 @@ public class DimensionService { updateImportedTaskProgress(req.getTaskId()); } private Long save(long taskId,long unitId,String role,String name,InputStream in,long max,String source,Long artifact,Long execution) throws IOException { + return saveAs(taskId,unitId,role,name,in,max,source,artifact,execution,actor()); + } + private Long saveAs(long taskId,long unitId,String role,String name,InputStream in,long max,String source,Long artifact,Long execution,String creator) throws IOException { var stored=files.save(role,name,in,max);long id=IdUtil.getSnowflakeNextId();Integer revision=jdbc.queryForObject("SELECT COALESCE(MAX(revision),0)+1 FROM lab_dimension_file WHERE task_id=? AND unit_id=? AND file_role=? AND tenant_id=?",Integer.class,taskId,unitId,role,tenant()); - jdbc.update("INSERT INTO lab_dimension_file(id,task_id,unit_id,file_role,revision,file_name,size_bytes,sha256,storage_path,source_type,source_artifact_id,source_execution_id,creator,tenant_id) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)",id,taskId,unitId,role,revision,name,stored.size(),stored.sha256(),stored.path(),source,artifact,execution,actor(),tenant());return id; + jdbc.update("INSERT INTO lab_dimension_file(id,task_id,unit_id,file_role,revision,file_name,size_bytes,sha256,storage_path,source_type,source_artifact_id,source_execution_id,creator,tenant_id) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)",id,taskId,unitId,role,revision,name,stored.size(),stored.sha256(),stored.path(),source,artifact,execution,creator,tenant());return id; } @Transactional(rollbackFor=Exception.class) public Long upload(long taskId,long unitId,String role,MultipartFile upload) throws IOException { @@ -285,6 +289,7 @@ public class DimensionService { var d=delivery(req.getDeliveryId());task(num(d.get("task_id")),true);var row=caseRow(num(d.get("task_id")),num(d.get("unit_id")),true);revision(row,req.getRevision()); if(!Boolean.TRUE.equals(req.getFilesConfirmed()))throw invalidParamException("请确认已核对成套成果"); if(!inputSignature(row,true).equals(JSON.parseObject(d.get("input_json").toString()).getString("signature"))||newerScan(row))throw invalidParamException("输入版本或扫描记录已变化,旧成果仅供历史查询,不能作为当前交付"); + if(!comparisonDeliveryCurrent(d))throw invalidParamException("检测计划或计算成果版本已更新,请使用最新成套成果"); verified(file(num(d.get("stl_id"))));verified(file(num(d.get("pdf_id")))); jdbc.update("UPDATE lab_dimension_delivery SET status='DELIVERED',confirmed_by=?,confirmed_at=CURRENT_TIMESTAMP WHERE id=? AND tenant_id=?",actor(),d.get("id"),tenant());jdbc.update("UPDATE lab_dimension_case SET last_delivery_id=? WHERE id=? AND tenant_id=?",d.get("id"),row.get("id"),tenant());bump(row);event(num(d.get("task_id")),num(d.get("unit_id")),"DELIVERY_CONFIRMED",map("deliveryId",d.get("id"))); updateImportedTaskProgress(num(d.get("task_id"))); @@ -311,4 +316,52 @@ public class DimensionService { event(content.taskId(),content.unitId(),"DELIVERY_PACKAGE_DOWNLOADED",map("deliveryId",content.deliveryId())); } private Map publicFile(Map f){var copy=new LinkedHashMap<>(f);copy.remove("storage_path");return copy;} + + public record ComparisonInput(long taskId,long unitId,long caseId,Long sourceExecutionId,String signature,String inputJson,String creator,Map files) {} + /** Called inside the comparison intent transaction; no engine request is made under DB locks. */ + @Transactional(rollbackFor=Exception.class) + public ComparisonInput comparisonInput(Action req) { + var task=task(req.getTaskId(),true); + if(req.getUnitId()==0)throw invalidParamException("请选择具体样件"); + var row=caseRow(req.getTaskId(),req.getUnitId(),true);revision(row,req.getRevision()); + if(newerScan(row))throw invalidParamException("扫描执行已更新或仍在运行,请等待结束并选用对应PLY"); + var snapshot=snapshot(row,true);String signature=snapshot.get("signature").toString(); + var sources=new LinkedHashMap(); + for(var pair:Map.of("model_id","target","drawing_id","drawing","cloud_id","source").entrySet()) { + var f=file(num(row.get(pair.getKey()))); + sources.put(pair.getValue(),new cn.iocoder.yudao.module.lab.service.inspection.LabInspectionGateway.StoredFile(f.get("file_name").toString(),Path.of(f.get("storage_path").toString()))); + } + snapshot.put("taskNo",task.getTaskNo());snapshot.put("taskId",String.valueOf(req.getTaskId()));snapshot.put("unitId",String.valueOf(req.getUnitId())); + String json=JSON.toJSONString(snapshot);jdbc.update("UPDATE lab_dimension_case SET prepared_json=? WHERE id=? AND tenant_id=?",json,row.get("id"),tenant());bump(row); + event(req.getTaskId(),req.getUnitId(),"COMPARISON_INPUTS_PREPARED",snapshot); + long execution=num(file(num(row.get("cloud_id"))).get("source_execution_id")); + return new ComparisonInput(req.getTaskId(),req.getUnitId(),num(row.get("id")),execution==0?null:execution,signature,json,actor(),sources); + } + public void checkComparisonAccess(long taskId,long unitId,String signature,boolean write) { + task(taskId,write);unit(taskId,unitId); + if(write){var row=caseRow(taskId,unitId,false);if(!signature.equals(inputSignature(row,false))||newerScan(row))throw invalidParamException("该比对对应历史输入或新的扫描正在执行,只允许查看历史成果");} + } + private boolean comparisonDeliveryCurrent(Map delivery) { + if(!Objects.toString(delivery.get("external_no"),"").startsWith("CMP-"))return true; + var jobs=rows("SELECT id,status,delivery_id FROM lab_dimension_comparison WHERE tenant_id=? AND case_id=? ORDER BY create_time DESC,id DESC LIMIT 1",tenant(),delivery.get("case_id")); + return !jobs.isEmpty()&&"ARCHIVED".equals(jobs.get(0).get("status"))&&num(jobs.get(0).get("delivery_id"))==num(delivery.get("id")); + } + /** Archives an immutable supplier revision, even if newer scans have made it historical. */ + @Transactional(rollbackFor=Exception.class) + public Long registerComparisonDelivery(String jobId,String engineRevision,Path stl,Path pdf,String planJson) throws IOException { + var found=rows("SELECT * FROM lab_dimension_comparison WHERE id=? AND tenant_id=? FOR UPDATE",jobId,tenant()); + if(found.isEmpty())throw invalidParamException("比对作业不存在");var job=found.get(0); + long taskId=num(job.get("task_id")),unitId=num(job.get("unit_id"));task(taskId,false);caseRow(taskId,unitId,true); + String external="CMP-"+jobId+"-"+DigestUtil.sha256Hex(engineRevision).substring(0,16); + var existed=rows("SELECT id FROM lab_dimension_delivery WHERE tenant_id=? AND case_id=? AND external_no=? AND deleted=0",tenant(),job.get("case_id"),external); + if(!existed.isEmpty())return num(existed.get(0).get("id")); + String creator=job.get("creator").toString();Long source=num(job.get("source_execution_id"))==0?null:num(job.get("source_execution_id")); + long mesh=saveAs(taskId,unitId,"RESULT_MESH","comparison-result.stl",Files.newInputStream(stl),0,"COMPARISON_ENGINE",null,source,creator); + long report=saveAs(taskId,unitId,"RESULT_REPORT","comparison-report.pdf",Files.newInputStream(pdf),0,"COMPARISON_ENGINE",null,source,creator); + var snapshot=JSON.parseObject(job.get("input_json").toString());snapshot.put("comparison",map("jobId",jobId,"engineId",job.get("engine_id"),"engineRevision",engineRevision,"options",JSON.parseObject(job.get("options_json").toString()),"measurementPlan",JSON.parse(planJson))); + long id=IdUtil.getSnowflakeNextId();jdbc.update("INSERT INTO lab_dimension_delivery(id,case_id,task_id,unit_id,input_json,stl_id,pdf_id,external_no,reason,status,creator,tenant_id) VALUES(?,?,?,?,?,?,?,?,?,'PENDING_CONFIRM',?,?)",id,job.get("case_id"),taskId,unitId,snapshot.toJSONString(),mesh,report,external,"本机计算服务自动归档;来源扫描与输入版本已冻结",creator,tenant()); + jdbc.update("UPDATE lab_dimension_case SET revision=revision+1,updater=?,update_time=CURRENT_TIMESTAMP WHERE id=? AND tenant_id=?",creator,job.get("case_id"),tenant()); + jdbc.update("INSERT INTO lab_dimension_event(id,task_id,unit_id,event_type,detail_json,creator,tenant_id) VALUES(?,?,?,?,?,?,?)",IdUtil.getSnowflakeNextId(),taskId,unitId,"COMPARISON_RESULTS_ARCHIVED",JSON.toJSONString(map("jobId",jobId,"deliveryId",id,"engineRevision",engineRevision,"sourceExecutionId",source)),creator,tenant()); + return id; + } } diff --git a/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/execution/LabAgvViewService.java b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/execution/LabAgvViewService.java index a958b37..a5d788b 100644 --- a/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/execution/LabAgvViewService.java +++ b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/execution/LabAgvViewService.java @@ -51,13 +51,14 @@ public class LabAgvViewService { target(id,robot,device);if(id==null){try{return JSONObject.of("state",views.state(robot,device),"points",new JSONArray(),"history",false);}catch(Exception e){return JSONObject.of("points",new JSONArray(),"history",false,"message","定位暂不可用:"+message(e));}} var execution=required(id);String key=key(id,robot,device);var trace=traces.get(key);if(trace==null){JSONObject file=read(id,robot,device);if(file!=null)trace=new Trace(file);} if(trace==null)return JSONObject.of("history",!active(execution),"points",new JSONArray(),"message",active(execution)?"正在等待本次执行的定位采样":"本次执行尚无已记录的AGV轨迹"); - synchronized(trace){var data=new JSONObject(trace.data);data.remove("map");data.remove("stations");if(afterAt>0){var points=new JSONArray();for(Object item:trace.data.getJSONArray("points")){var p=(JSONObject)item;if(p.getLongValue("at")>afterAt)points.add(p);}data.put("points",points);}data.put("history",!active(execution));return JSON.parseObject(data.toJSONString());} + synchronized(trace){var data=new JSONObject(trace.data);data.remove("map");data.remove("stations");var points=new JSONArray();for(Object item:trace.data.getJSONArray("points")){var p=(JSONObject)item;if(afterAt<=0||p.getLongValue("at")>afterAt)points.add(p);}data.put("points",points);data.put("history",!active(execution));return JSON.parseObject(data.toJSONString());} } public JSONObject map(Long id,String robot,String device,String version){ target(id,robot,device);JSONObject map;JSONArray stationList;String error=""; if(id==null){try{var state=views.state(robot,device);String name=state.getString("currentMap");map=views.map(robot,device,name==null?"":name);try{stationList=views.stations(robot,device,name);}catch(Exception e){stationList=new JSONArray();}}catch(Exception e){return JSONObject.of("available",false,"message","地图暂不可用:"+message(e));}} - else {var execution=required(id);var trace=traces.get(key(id,robot,device));JSONObject data;if(trace==null)data=read(id,robot,device);else synchronized(trace){data=JSON.parseObject(trace.data.toJSONString());} - map=data==null?null:data.getJSONObject("map");stationList=data==null?new JSONArray():data.getJSONArray("stations");error=data==null?"":data.getString("mapError"); + else {var execution=required(id);var trace=traces.get(key(id,robot,device)); + if(trace==null){var data=read(id,robot,device);map=data==null?null:data.getJSONObject("map");stationList=data==null?new JSONArray():data.getJSONArray("stations");error=data==null?"":data.getString("mapError");} + else synchronized(trace){map=trace.data.getJSONObject("map");stationList=trace.data.getJSONArray("stations");error=trace.data.getString("mapError");} if(map==null)return JSONObject.of("available",false,"message",error!=null&&!error.isBlank()?error:active(execution)?"正在读取本次执行的地图":"本次执行未归档地图,仍可查看已记录的定位轨迹"); } if(Objects.equals(version,map.getString("version")))return JSONObject.of("available",true,"unchanged",true,"version",version,"stations",stationList); @@ -88,7 +89,7 @@ public class LabAgvViewService { var point=new JSONObject(pose);point.put("at",state.getLongValue("receivedAt"));point.put("mapId",map);point.put("segment",trace.segment);point.put("mapEpoch",trace.data.getIntValue("mapEpoch"));points.add(point);if(points.size()>20000){var reduced=new JSONArray();for(int i=0;i0&&points.getJSONObject(i).getIntValue("segment")!=points.getJSONObject(i-1).getIntValue("segment"))reduced.add(points.get(i));if(reduced.size()>20000)reduced=new JSONArray(reduced.subList(reduced.size()-20000,reduced.size()));trace.data.put("points",reduced);trace.data.put("sampled",true);} } }else trace.segment++; - if(!trace.mapLoading&&System.currentTimeMillis()-trace.mapChecked>30000){trace.mapLoading=true;trace.mapChecked=System.currentTimeMillis();try{mapWorker.submit(()->TenantUtils.execute(1L,()->loadMap(trace,robot,device,map)));}catch(RejectedExecutionException busy){trace.mapLoading=false;}} + if(!trace.mapLoading&&System.currentTimeMillis()-trace.mapChecked>60000){trace.mapLoading=true;trace.mapChecked=System.currentTimeMillis();try{mapWorker.submit(()->TenantUtils.execute(1L,()->loadMap(trace,robot,device,map)));}catch(RejectedExecutionException busy){trace.mapLoading=false;}} }catch(Exception error){trace.data.put("message","定位读取失败:"+message(error));trace.segment++;trace.nextStateAt=System.currentTimeMillis()+Math.min(15000,1000L<5000)save(trace); } 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 new file mode 100644 index 0000000..6c48005 --- /dev/null +++ b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/inspection/LabComparisonResults.java @@ -0,0 +1,99 @@ +package cn.iocoder.yudao.module.lab.service.inspection; + +import jakarta.annotation.Resource; +import org.springframework.stereotype.Service; +import java.io.*; +import java.nio.file.*; +import java.util.*; +import java.util.zip.ZipFile; + +/** Downloads only supplier artifacts; bounded memory, disk reserve, and unambiguous STL selection. */ +@Service +public class LabComparisonResults { + @Resource private LabInspectionGateway gateway; + @Resource private LabInspectionProperties settings; + private static final long RESERVE=512L*1024*1024; + public record Pair(Path mesh,Path report,Path directory) implements AutoCloseable { + @Override public void close() throws IOException { + try(var paths=Files.list(directory)){for(Path path:paths.toList())Files.deleteIfExists(path);}Files.deleteIfExists(directory); + } + } + private Path copy(InputStream input,Path destination,long declared) throws IOException { + if(declared>Files.getFileStore(destination.getParent()).getUsableSpace()-RESERVE)throw new IOException("归档磁盘空间不足,需保留512MiB运行空间"); + long total=0; + try(input;var out=Files.newOutputStream(destination,StandardOpenOption.CREATE_NEW)) { + byte[] block=new byte[65536];int count; + while((count=input.read(block))!=-1){ + if(Thread.currentThread().isInterrupted())throw new InterruptedIOException("成果下载已中断"); + total=Math.addExact(total,count); + if(total%(8L*1024*1024)=0&&declared!=total)throw new IOException("计算成果为空或下载长度不完整");return destination; + } + private Path download(String id,String name,Path destination) throws IOException { + if(!name.matches("[a-zA-Z0-9_.-]+")||name.contains(".."))throw new IOException("计算服务返回的成果文件名无效"); + var response=gateway.forward("/api/tasks/"+id+"/files/"+name,"GET",new byte[0]); + if(response.statusCode()==404){response.body().close();return null;} + if(response.statusCode()>=400){response.body().close();throw new IOException("成果下载失败("+response.statusCode()+"):"+name);} + long length; + try{length=response.headers().firstValueAsLong("Content-Length").orElse(-1);}catch(RuntimeException e){response.body().close();throw new IOException("成果长度回执无效");} + return copy(response.body(),destination,length); + } + public Pair fetch(String engineId,Map state) throws IOException { + Path root=Path.of(settings.getStorageDirectory()).toAbsolutePath().normalize();Files.createDirectories(root); + if(Files.getFileStore(root).getUsableSpace() names=new LinkedHashSet<>();declaredMeshNames(state,names); + 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")); + if(mesh==null||pdf==null) { + Path bundle=download(engineId,"result.zip",directory.resolve("result.zip")); + if(bundle!=null)try(var zip=new ZipFile(bundle.toFile())) { + if(zip.size()>4096)throw new IOException("计算结果包条目过多,不能自动归档"); + var entries=Collections.list(zip.entries()).stream().filter(e->!e.isDirectory()).toList(); + if(mesh==null) { + var candidates=entries.stream().filter(e->e.getName().toLowerCase(Locale.ROOT).endsWith(".stl")).toList(); + if(candidates.size()!=1)throw new IOException("计算结果未提供唯一的处理后STL,请核对计算服务输出;不会用扫描原文件冒充结果"); + var entry=candidates.get(0);mesh=copy(zip.getInputStream(entry),directory.resolve("result.stl"),entry.getSize()); + } + if(pdf==null) { + var candidates=entries.stream().filter(e->e.getName().toLowerCase(Locale.ROOT).endsWith(".pdf")).toList(); + var preferred=candidates.stream().filter(e->e.getName().replace('\\','/').endsWith("/report_signed_chromatogram.pdf")||e.getName().equals("report_signed_chromatogram.pdf")).toList(); + if(preferred.size()==1)candidates=preferred; + if(candidates.size()!=1)throw new IOException("结果包未提供唯一PDF报告"); + var entry=candidates.get(0);pdf=copy(zip.getInputStream(entry),directory.resolve("report.pdf"),entry.getSize()); + } + } + } + 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); + } finally {if(!success)new Pair(mesh,pdf,directory).close();} + } + private static void validateMesh(Path mesh) throws IOException { + long size=Files.size(mesh); + try(var file=new RandomAccessFile(mesh.toFile(),"r")) { + byte[] prefix=new byte[(int)Math.min(size,8192)];file.readFully(prefix); + if(size>=84){long triangles=Integer.toUnsignedLong(java.nio.ByteBuffer.wrap(prefix,80,4).order(java.nio.ByteOrder.LITTLE_ENDIAN).getInt());if(triangles>0&&84L+50L*triangles==size)return;} + String start=new String(prefix,java.nio.charset.StandardCharsets.US_ASCII).stripLeading(); + byte[] suffix=new byte[(int)Math.min(size,8192)];file.seek(size-suffix.length);file.readFully(suffix); + String end=new String(suffix,java.nio.charset.StandardCharsets.US_ASCII); + if(start.startsWith("solid")&&start.contains("facet normal")&&start.contains("vertex")&&(start.contains("endsolid")||end.contains("endsolid")))return; + } + throw new IOException("计算服务返回的STL内容无效或网格为空"); + } + private static void declaredMeshNames(Object value,Set out) { + if(value instanceof Map map)for(var e:map.entrySet()) { + String key=e.getKey().toString();Object item=e.getValue(); + if(Set.of("result_stl","stl_file","mesh_file","filename","name").contains(key)&&item instanceof String text&&text.matches("[a-zA-Z0-9_.-]+\\.stl")&&!text.contains(".."))out.add(text); + if(Set.of("files","artifacts","outputs","result").contains(key))declaredMeshNames(item,out); + } + else if(value instanceof Collection list)for(var item:list)declaredMeshNames(item,out); + } +} 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 new file mode 100644 index 0000000..4bca874 --- /dev/null +++ b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/inspection/LabDimensionComparisonService.java @@ -0,0 +1,221 @@ +package cn.iocoder.yudao.module.lab.service.inspection; + +import cn.hutool.crypto.digest.DigestUtil; +import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils; +import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder; +import cn.iocoder.yudao.module.lab.service.dimension.DimensionService; +import com.fasterxml.jackson.databind.ObjectMapper; +import jakarta.annotation.Resource; +import jakarta.validation.constraints.*; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpStatus; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Service; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; +import org.springframework.web.server.ResponseStatusException; +import java.util.*; +import java.util.concurrent.Semaphore; +import java.util.concurrent.locks.ReentrantLock; + +/** Durable comparison intent -> supplier task -> paired local delivery. Never controls physical equipment. */ +@Service @Slf4j +public class LabDimensionComparisonService { + @Resource private JdbcTemplate jdbc; + @Resource private PlatformTransactionManager transactionManager; + @Resource private DimensionService dimensions; + @Resource private LabInspectionGateway gateway; + @Resource private LabInspectionRepository repository; + @Resource private LabInspectionTemplateService templates; + @Resource private LabComparisonResults results; + @Resource private ObjectMapper mapper; + private final Semaphore submissions=new Semaphore(2); + @org.springframework.beans.factory.annotation.Value("${lab.inspection.poll-interval-ms:15000}") private long pollIntervalMs=15000; + private java.util.concurrent.ScheduledExecutorService poller; + @jakarta.annotation.PostConstruct public void startPolling(){ + // Large result transfers must never hold the shared device recovery/stop scheduler. + poller=java.util.concurrent.Executors.newSingleThreadScheduledExecutor(r->{Thread thread=new Thread(r,"dimension-comparison-poll");thread.setDaemon(true);return thread;}); + poller.scheduleWithFixedDelay(()->{try{poll();}catch(Exception error){log.warn("尺寸比对同步暂不可用,下个周期重试:{}",error.getClass().getSimpleName());}},Math.max(1000,pollIntervalMs),Math.max(1000,pollIntervalMs),java.util.concurrent.TimeUnit.MILLISECONDS); + } + @jakarta.annotation.PreDestroy public void stopPolling(){if(poller!=null)poller.shutdownNow();} + private final ReentrantLock[] locks=java.util.stream.IntStream.range(0,64).mapToObj(i->new ReentrantLock()).toArray(ReentrantLock[]::new); + @Data @EqualsAndHashCode(callSuper=true) + public static class Start extends DimensionService.Action { + @NotBlank @Size(max=100) private String planTemplateId="auto"; + @NotNull @DecimalMin("0.000001") @DecimalMax("1000000") private Double sourceScale=1.0,targetScale=1.0; + @NotNull @DecimalMin("0.001") @DecimalMax("100") private Double tolerance=0.2; + private boolean autoReport=true,sourceClean=false,reviewCleanup=false; + private Map cleanupOptions=Map.of("selection_mode","cad","strength","normal","keep_components",1); + } + private long tenant(){long id=TenantContextHolder.getRequiredTenantId();if(id!=1)throw bad("当前检测业务仅在主租户开放");return id;} + private static ResponseStatusException bad(String text){return new ResponseStatusException(HttpStatus.BAD_REQUEST,text);} + private static long number(Object value){return value==null?0:((Number)value).longValue();} + private List> rows(String sql,Object...args){return jdbc.queryForList(sql,args);} + private Map required(String id) { + var list=rows("SELECT * FROM lab_dimension_comparison WHERE id=? AND tenant_id=?",id,tenant()); + if(list.isEmpty())throw new ResponseStatusException(HttpStatus.NOT_FOUND,"比对作业不存在");return list.get(0); + } + public Map engineJob(String engine,boolean write) { + var list=rows("SELECT * FROM lab_dimension_comparison WHERE engine_id=? AND tenant_id=?",engine,tenant()); + if(list.isEmpty())throw new ResponseStatusException(HttpStatus.NOT_FOUND,"检测任务不存在");var job=list.get(0); + dimensions.checkComparisonAccess(number(job.get("task_id")),number(job.get("unit_id")),job.get("input_signature").toString(),write); + if(write) { + var latest=latest(number(job.get("task_id")),number(job.get("unit_id"))); + if(latest==null||!latest.get("id").equals(job.get("id")))throw bad("历史比对只允许查看,请打开当前样件的最新比对"); + } + return job; + } + private Map latest(long task,long unit) { + var list=rows("SELECT * FROM lab_dimension_comparison WHERE task_id=? AND unit_id=? AND tenant_id=? ORDER BY create_time DESC,id DESC LIMIT 1",task,unit,tenant()); + return list.isEmpty()?null:list.get(0); + } + public Map latestView(long task,long unit) { + dimensions.checkComparisonAccess(task,unit,"",false);var job=latest(task,unit);return job==null?Map.of():publicJob(job); + } + public Map jobView(String engine){return publicJob(engineJob(engine,false));} + private Map publicJob(Map source) { + var result=new LinkedHashMap(source); + result.remove("submission_key"); + // Input JSON contains file IDs, hashes, revisions and names, never local disk paths. + return result; + } + private Map settings(Start req,DimensionService.ComparisonInput input) throws Exception { + var options=new LinkedHashMap(); + options.put("title","任务"+input.taskId()+" / 样件"+input.unitId()); + options.put("source_scale",req.getSourceScale().toString());options.put("target_scale",req.getTargetScale().toString()); + options.put("tolerance",req.getTolerance().toString());options.put("auto_report",req.isAutoReport()?"1":"0"); + 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 snapshot=templates.resolveUpload(tenant(),req.getPlanTemplateId(),input.files().get("target").name(),input.files().get("drawing").name()); + options.put("selected_template_id",req.getPlanTemplateId()); + options.put("plan_template_id",snapshot!=null||req.getPlanTemplateId().equals("auto")?"cad-geometry":req.getPlanTemplateId()); + if(snapshot!=null)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(!Boolean.TRUE.equals(gateway.health().get("available")))throw new ResponseStatusException(HttpStatus.SERVICE_UNAVAILABLE,"本机计算服务未就绪,请启动检测EXE后重试"); + if(!submissions.tryAcquire())throw new ResponseStatusException(HttpStatus.TOO_MANY_REQUESTS,"当前比对提交较多,请稍后重试"); + try { + Intent intent=new TransactionTemplate(transactionManager).execute(tx->{ + var input=dimensions.comparisonInput(req); + try { + var options=settings(req,input);String json=mapper.writeValueAsString(options); + String key=DigestUtil.sha256Hex(input.caseId()+":"+input.signature()+":"+json); + var existing=rows("SELECT * FROM lab_dimension_comparison WHERE tenant_id=? AND submission_key=?",tenant(),key); + if(!existing.isEmpty()) { + var prior=existing.get(0); + if(!"FAILED".equals(prior.get("status"))||prior.get("engine_id")!=null)return new Intent(prior,input,options,false); + jdbc.update("UPDATE lab_dimension_comparison SET submission_key=? WHERE id=? AND tenant_id=?",DigestUtil.sha256Hex(key+prior.get("id")),prior.get("id"),tenant()); + } + var pending=rows("SELECT id FROM lab_dimension_comparison WHERE tenant_id=? AND case_id=? AND input_signature=? AND status IN ('SUBMITTING','UNKNOWN','PROCESSING') LIMIT 1",tenant(),input.caseId(),input.signature()); + if(!pending.isEmpty())return new Intent(required(pending.get(0).get("id").toString()),input,options,false); + String id=UUID.randomUUID().toString().replace("-",""); + jdbc.update("INSERT INTO lab_dimension_comparison(id,tenant_id,task_id,unit_id,case_id,source_execution_id,submission_key,input_signature,input_json,options_json,status,creator) VALUES(?,?,?,?,?,?,?,?,?,?,'SUBMITTING',?)",id,tenant(),input.taskId(),input.unitId(),input.caseId(),input.sourceExecutionId(),key,input.signature(),input.inputJson(),json,input.creator()); + return new Intent(required(id),input,options,true); + }catch(RuntimeException e){throw e;}catch(Exception e){throw new IllegalStateException(e);} + }); + if(!intent.created())return publicJob(intent.job()); + String id=intent.job().get("id").toString(); + try { + var sent=new LinkedHashMap<>(intent.options());sent.remove("selected_template_id"); + var response=gateway.submit(sent,intent.input().files()); + var raw=gateway.json("/api/tasks","POST",response); + if(!(raw instanceof Map state))throw new IllegalStateException("计算服务未返回作业信息"); + String engine=Objects.toString(state.get("id"),""); + if(!engine.matches("[a-f0-9]{32}"))throw new IllegalStateException("计算服务已接收但未返回有效作业编号"); + new TransactionTemplate(transactionManager).execute(tx->{ + try { + jdbc.update("UPDATE lab_dimension_comparison SET engine_id=?,status='PROCESSING',last_error=NULL WHERE id=? AND tenant_id=?",engine,id,tenant()); + var inputs=mapper.readValue(intent.input().inputJson(),Map.class); + repository.insert(tenant(),engine,sent.get("title"),mapper.writeValueAsString(sent),mapper.writeValueAsString(Map.of("source",inputs.get("cloud"),"target",inputs.get("model"),"drawing",inputs.get("drawing"))),mapper.writeValueAsString(state),intent.input().creator()); + return null; + }catch(RuntimeException e){throw e;}catch(Exception e){throw new IllegalStateException(e);} + }); + observe(engine,state); + }catch(Exception error) { + boolean rejected=error instanceof ResponseStatusException e&&e.getStatusCode().value()>=400&&e.getStatusCode().value()<500; + failure(id,rejected?"FAILED":"UNKNOWN",rejected?Objects.toString(error.getMessage(),"计算服务拒绝提交"):"提交结果未确认,计算服务可能已接收;请核对服务记录,不会自动重复提交。"+Objects.toString(error.getMessage(),"")); + } + return publicJob(required(id)); + }finally{submissions.release();} + } + public void beginMutation(String engine,String action) { + 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()); + } + 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; + var job=list.get(0);String revision=LabInspectionGateway.revision(state),status=Objects.toString(state.get("status"),"processing"); + if(revision.length()>100){failure(job.get("id").toString(),"FAILED","计算服务成果版本号过长");return;} + String next="PROCESSING",message=null;Object awaiting=job.get("awaiting_revision"); + if(status.equals("error")){next="FAILED";message=Objects.toString(state.get("error"),Objects.toString(state.get("auto_measure_error"),"计算失败,请查看工作区日志"));} + else if(Set.of("review","blocked").contains(status)||status.equals("done")&&Boolean.FALSE.equals(state.get("report_ready")))next="REVIEW"; + else if(status.equals("done")) { + if(revision.isBlank()){next="ARCHIVE_ERROR";message="计算服务未返回成果版本号,暂不能成套归档";} + else if(awaiting!=null&&awaiting.toString().equals(revision)){next="REVIEW";message="等待新的报告版本,旧成果不会作为此次重新计算结果";} + else if("ARCHIVED".equals(job.get("status"))&&revision.equals(job.get("engine_revision"))&&awaiting==null)next="ARCHIVED"; + else if("ARCHIVE_ERROR".equals(job.get("status"))&&revision.equals(job.get("engine_revision"))&&awaiting==null){next="ARCHIVE_ERROR";message=Objects.toString(job.get("last_error"),"成果待归档");} + else next="ARCHIVE_PENDING"; + } + if(status.equals("done")&&!Boolean.FALSE.equals(state.get("report_ready"))&&awaiting!=null&&!revision.isBlank()&&!awaiting.toString().equals(revision))awaiting=null; + jdbc.update("UPDATE lab_dimension_comparison SET status=?,engine_revision=?,awaiting_revision=?,last_error=?,update_time=CURRENT_TIMESTAMP WHERE id=? AND tenant_id=?",next,revision,awaiting,message,job.get("id"),tenant()); + } + private void failure(String id,String status,String message) { + jdbc.update("UPDATE lab_dimension_comparison SET status=?,last_error=?,update_time=CURRENT_TIMESTAMP WHERE id=? AND tenant_id=?",status,message.substring(0,Math.min(message.length(),1900)),id,tenant()); + } + public Map savedState(String engine) throws Exception { + var job=engineJob(engine,false);var row=repository.scan(tenant(),engine); + @SuppressWarnings("unchecked") var state=(Map)mapper.readValue(Objects.toString(row.get("state_json"),"{}"),Map.class); + state.put("id",engine);state.put("inputs",mapper.readValue(Objects.toString(row.get("inputs_json"),"{}"),Map.class)); + state.put("platform_job",publicJob(job));return state; + } + public Map synchronize(String engine) throws Exception { + var job=engineJob(engine,false); + if("ARCHIVE_ERROR".equals(job.get("status")))jdbc.update("UPDATE lab_dimension_comparison SET status='ARCHIVE_PENDING',last_error=NULL WHERE id=? AND tenant_id=?",job.get("id"),tenant()); + refresh(job.get("id").toString());return savedState(engine); + } + private void refresh(String id) throws Exception { + ReentrantLock lock=locks[Math.floorMod(id.hashCode(),locks.length)];if(!lock.tryLock())return; + try { + var job=required(id);if(job.get("engine_id")==null)return;String engine=job.get("engine_id").toString(),path="/api/tasks/"+engine; + @SuppressWarnings("unchecked") var state=(Map)gateway.json(path,"GET",gateway.forward(path,"GET",new byte[0]));observe(engine,state);job=required(id); + if(!"ARCHIVE_PENDING".equals(job.get("status")))return; + String revision=LabInspectionGateway.revision(state); + try { + 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)) { + @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; + long delivery=dimensions.registerComparisonDelivery(id,revision,pair.mesh(),pair.report(),planJson); + jdbc.update("UPDATE lab_dimension_comparison SET delivery_id=?,status='ARCHIVED',last_error=NULL WHERE id=? AND tenant_id=? AND engine_revision=? AND awaiting_revision IS NULL",delivery,id,tenant(),revision); + } + }catch(Exception e){failure(id,"ARCHIVE_ERROR","计算已完成,成果尚未成套归档:"+Objects.toString(e.getMessage(),e.getClass().getSimpleName()));} + }finally{lock.unlock();} + } + public void poll() { + List> pending; + try{pending=rows("SELECT id,tenant_id FROM lab_dimension_comparison WHERE engine_id IS NOT NULL AND status IN ('PROCESSING','REVIEW','ARCHIVE_PENDING') ORDER BY update_time LIMIT 20");} + catch(Exception e){log.debug("比对作业结构尚未就绪");return;} + Long previous=TenantContextHolder.getTenantId();boolean ignore=TenantContextHolder.isIgnore(); + try { + for(var job:pending) { + TenantContextHolder.setTenantId(number(job.get("tenant_id")));TenantContextHolder.setIgnore(false); + try{refresh(job.get("id").toString());}catch(Exception e){ + jdbc.update("UPDATE lab_dimension_comparison SET last_error=?,update_time=CURRENT_TIMESTAMP WHERE id=? AND tenant_id=?",("状态同步失败:"+Objects.toString(e.getMessage(),e.getClass().getSimpleName())).substring(0,Math.min(1800,("状态同步失败:"+Objects.toString(e.getMessage(),e.getClass().getSimpleName())).length())),job.get("id"),tenant()); + } + } + } finally {TenantContextHolder.setTenantId(previous);TenantContextHolder.setIgnore(ignore);} + } + @org.springframework.context.event.EventListener(org.springframework.boot.context.event.ApplicationReadyEvent.class) + public void recoverUnconfirmedSubmissions() { + try{jdbc.update("UPDATE lab_dimension_comparison SET status='UNKNOWN',last_error='服务重启前的提交回执未确认,请核对计算服务记录;不会自动重复提交' WHERE status='SUBMITTING' AND engine_id IS NULL");} + catch(org.springframework.dao.DataAccessException missing){log.warn("尺寸比对数据结构尚未升级,需执行017增量;扫描执行不受影响");} + } +} 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 new file mode 100644 index 0000000..be58836 --- /dev/null +++ b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/inspection/LabInspectionGateway.java @@ -0,0 +1,119 @@ +package cn.iocoder.yudao.module.lab.service.inspection; + +import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder; +import com.fasterxml.jackson.databind.ObjectMapper; +import jakarta.annotation.PostConstruct; +import jakarta.annotation.Resource; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; +import org.springframework.web.server.ResponseStatusException; +import java.io.*; +import java.net.URI; +import java.net.http.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.time.Duration; +import java.util.*; + +/** Adapted from supplier 8ee5293986: task files come from controlled platform storage. */ +@Service +public class LabInspectionGateway { + @Resource private LabInspectionProperties properties; + @Resource private LabInspectionRepository repository; + @Resource private ObjectMapper mapper; + private HttpClient client; + private record Availability(boolean available,long checkedAt) {} + private volatile Availability availability=new Availability(false,0); + public boolean knownAvailable(){var state=availability;return state.available()&&System.currentTimeMillis()-state.checkedAt()<60000;} + private static final java.util.concurrent.ScheduledThreadPoolExecutor BODY_TIMEOUTS=bodyTimeouts(); + private static java.util.concurrent.ScheduledThreadPoolExecutor bodyTimeouts(){ + var executor=new java.util.concurrent.ScheduledThreadPoolExecutor(1,r->{Thread t=new Thread(r,"inspection-body-timeout");t.setDaemon(true);return t;}); + executor.setRemoveOnCancelPolicy(true);return executor; + } + public record StoredFile(String name,Path path) {} + @PostConstruct public void initialize() { + URI uri=URI.create(properties.getBaseUrl()); + if(!Set.of("http","https").contains(uri.getScheme())||uri.getHost()==null||uri.getRawUserInfo()!=null||uri.getQuery()!=null||uri.getFragment()!=null) + throw new IllegalArgumentException("lab.inspection.base-url必须是HTTP(S)计算服务地址"); + client=HttpClient.newBuilder().connectTimeout(properties.getConnectTimeout()).followRedirects(HttpClient.Redirect.NEVER).build(); + } + private HttpRequest.Builder request(String path,Duration timeout) { + return HttpRequest.newBuilder(URI.create(properties.getBaseUrl().replaceAll("/$","")+path)).timeout(timeout); + } + 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(!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)"); + } + if(!allowed)throw new ResponseStatusException(HttpStatus.NOT_FOUND,"不支持的检测接口,请从任务工作台发起比对"); + } + private HttpResponse send(HttpRequest request) { + try{var response=client.send(request,HttpResponse.BodyHandlers.ofInputStream());availability=new Availability(response.statusCode()<500,System.currentTimeMillis());return new BoundedResponse(response,new TimedBody(response.body(),properties.getRequestTimeout()));} + catch(InterruptedException e){Thread.currentThread().interrupt();throw new ResponseStatusException(HttpStatus.BAD_GATEWAY,"计算服务请求已中断",e);} + catch(IOException e){availability=new Availability(false,System.currentTimeMillis());throw new ResponseStatusException(HttpStatus.BAD_GATEWAY,"计算服务连接失败,请检查本机检测EXE",e);} + } + private static final class TimedBody extends FilterInputStream { + private final java.util.concurrent.ScheduledFuture timeout; + private volatile boolean expired; + TimedBody(InputStream source,Duration limit){super(source);timeout=BODY_TIMEOUTS.schedule(()->{expired=true;try{source.close();}catch(IOException ignored){}},Math.max(1,limit.toMillis()),java.util.concurrent.TimeUnit.MILLISECONDS);} + @Override public int read() throws IOException {if(expired)throw new InterruptedIOException("计算服务响应超时");return in.read();} + @Override public int read(byte[] bytes,int offset,int length) throws IOException {if(expired)throw new InterruptedIOException("计算服务响应超时");return in.read(bytes,offset,length);} + @Override public void close() throws IOException {timeout.cancel(false);super.close();} + } + private record BoundedResponse(HttpResponse source,InputStream body) implements HttpResponse { + public int statusCode(){return source.statusCode();}public HttpRequest request(){return source.request();} + public Optional> previousResponse(){return source.previousResponse();} + public HttpHeaders headers(){return source.headers();}public Optional sslSession(){return source.sslSession();} + public URI uri(){return source.uri();}public HttpClient.Version version(){return source.version();} + } + 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",""); + }catch(Exception error){return Map.of("available",false,"message","本机计算服务未就绪,请启动检测EXE后重试");} + } + public HttpResponse forward(String path,String method,byte[] body) { + authorize(path,method); + var builder=request(path,properties.getRequestTimeout()); + return send(method.equals("GET")?builder.GET().build():builder.header("Content-Type","application/json").POST(HttpRequest.BodyPublishers.ofByteArray(body)).build()); + } + public HttpResponse submit(Map settings,Map files) { + String boundary="Inspection"+UUID.randomUUID().toString().replace("-",""); + List parts=new ArrayList<>(); + settings.forEach((name,value)->{ + if(!name.matches("[a-zA-Z0-9_]+"))throw new IllegalArgumentException("Invalid field"); + parts.add(HttpRequest.BodyPublishers.ofString("--"+boundary+"\r\nContent-Disposition: form-data; name=\""+name+"\"\r\n\r\n"+value+"\r\n",StandardCharsets.UTF_8)); + }); + try { + for(var entry:files.entrySet()) { + if(!Set.of("source","target","drawing").contains(entry.getKey()))throw new IllegalArgumentException("Invalid file role"); + String name=entry.getValue().name().replaceAll("[\\r\\n\"\\\\/]","_"); + parts.add(HttpRequest.BodyPublishers.ofString("--"+boundary+"\r\nContent-Disposition: form-data; name=\""+entry.getKey()+"\"; filename=\""+name+"\"\r\nContent-Type: application/octet-stream\r\n\r\n",StandardCharsets.UTF_8)); + parts.add(HttpRequest.BodyPublishers.ofFile(entry.getValue().path()));parts.add(HttpRequest.BodyPublishers.ofString("\r\n")); + } + }catch(IOException e){throw new ResponseStatusException(HttpStatus.BAD_REQUEST,"选用文件不可读取,请检查平台归档",e);} + parts.add(HttpRequest.BodyPublishers.ofString("--"+boundary+"--\r\n")); + return send(request("/api/tasks",properties.getRequestTimeout()).header("Content-Type","multipart/form-data; boundary="+boundary) + .POST(HttpRequest.BodyPublishers.concat(parts.toArray(HttpRequest.BodyPublisher[]::new))).build()); + } + public Object json(String path,String method,HttpResponse response) throws IOException { + Object value; + try(var in=response.body()) { + // This is structured preview/plan metadata, not a restriction on source/result files. + byte[] bytes=in.readNBytes(32*1024*1024+1); + if(bytes.length>32*1024*1024)throw new IOException("计算服务预览数据超过当前可用处理预算"); + value=mapper.readValue(bytes,Object.class); + } + if(response.statusCode()>=400)throw new ResponseStatusException(HttpStatus.valueOf(response.statusCode()),value instanceof Map m?Objects.toString(m.get("error"),Objects.toString(m.get("message"),"计算服务处理失败")):"计算服务处理失败"); + if(path.matches("/api/tasks/[a-f0-9]{32}")&&value instanceof Map state) { + repository.state(TenantContextHolder.getRequiredTenantId(),path.split("/")[3],Objects.toString(state.get("status"),"processing"),Boolean.TRUE.equals(state.get("report_ready"))||(!Boolean.FALSE.equals(state.get("report_ready"))&&"done".equals(state.get("status"))),revision(state),mapper.writeValueAsString(value)); + } + 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)); + return value; + } + public static String revision(Map state){return Objects.toString(state.get("report_revision"),Objects.toString(state.get("revision"),""));} +} diff --git a/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/inspection/LabInspectionProperties.java b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/inspection/LabInspectionProperties.java new file mode 100644 index 0000000..0c09e64 --- /dev/null +++ b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/inspection/LabInspectionProperties.java @@ -0,0 +1,15 @@ +package cn.iocoder.yudao.module.lab.service.inspection; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; +import java.time.Duration; + +/** Supplier EXE contract. It is independent of physical device operation deadlines. */ +@Data @Component @ConfigurationProperties(prefix="lab.inspection") +public class LabInspectionProperties { + private String baseUrl="http://127.0.0.1:8769"; + private Duration connectTimeout=Duration.ofSeconds(3); + private Duration requestTimeout=Duration.ofMinutes(10); + private String storageDirectory="./.local/artifacts/inspection-transfer"; +} diff --git a/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/inspection/LabInspectionRepository.java b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/inspection/LabInspectionRepository.java new file mode 100644 index 0000000..2eb439d --- /dev/null +++ b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/inspection/LabInspectionRepository.java @@ -0,0 +1,27 @@ +package cn.iocoder.yudao.module.lab.service.inspection; + +import jakarta.annotation.Resource; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Repository; +import java.util.*; + +/** Supplier scan index, linked to the platform's task and immutable input snapshot. */ +@Repository +public class LabInspectionRepository { + @Resource private JdbcTemplate jdbc; + public boolean owns(long tenant,String id) { + return jdbc.queryForObject("SELECT COUNT(*) FROM lab_dimension_comparison WHERE tenant_id=? AND engine_id=?",Integer.class,tenant,id)>0; + } + public Map scan(long tenant,String id) { + return jdbc.queryForMap("SELECT * FROM lab_inspection_scan WHERE tenant_id=? AND id=?",tenant,id); + } + public void insert(long tenant,String id,String title,String options,String inputs,String state,String creator) { + jdbc.update("INSERT INTO lab_inspection_scan(id,tenant_id,title,settings_json,inputs_json,state_json,creator) VALUES(?,?,?,?,?,?,?)",id,tenant,title,options,inputs,state,creator); + } + public void state(long tenant,String id,String status,boolean ready,String revision,String state) { + jdbc.update("UPDATE lab_inspection_scan SET status=?,report_ready=?,report_revision=?,state_json=?,update_time=CURRENT_TIMESTAMP WHERE tenant_id=? AND id=?",status,ready,revision,state,tenant,id); + } + public void plan(long tenant,String id,String json) { + jdbc.update("UPDATE lab_inspection_scan SET plan_json=? WHERE tenant_id=? AND id=?",json,tenant,id); + } +} diff --git a/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/inspection/LabInspectionTemplateService.java b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/inspection/LabInspectionTemplateService.java new file mode 100644 index 0000000..0e5bdc1 --- /dev/null +++ b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/inspection/LabInspectionTemplateService.java @@ -0,0 +1,105 @@ +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.http.HttpStatus; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.server.ResponseStatusException; +import java.util.*; +import java.util.regex.Pattern; + +@Service +public class LabInspectionTemplateService { + @Resource private JdbcTemplate jdbc; + @Resource private ObjectMapper mapper; + private final Set seeded=java.util.concurrent.ConcurrentHashMap.newKeySet(); + private void ensureDefaults(long tenant) { + if(seeded.contains(tenant))return; + try (var stream=new org.springframework.core.io.ClassPathResource("inspection/plan-template-seeds.json").getInputStream()) { + List> seeds=mapper.readValue(stream,new TypeReference<>(){}); + for(var seed:seeds) jdbc.update("INSERT IGNORE INTO lab_inspection_template(id,tenant_id,name,description,part_numbers,enabled,rows_json,row_count,builtin_key,creator) VALUES(?,?,?,?,?,TRUE,?,?,?,?)",UUID.randomUUID().toString().replace("-",""),tenant,seed.get("name"),seed.get("description"),seed.get("partNumbers"),mapper.writeValueAsString(seed.get("rows")),((List)seed.get("rows")).size(),seed.get("builtinKey"),"system"); + seeded.add(tenant); + } catch(java.io.IOException error){throw new IllegalStateException("初始检测模板读取失败",error);} + } + public record SaveRequest(String id, String name, String description, String partNumbers, Boolean enabled, Integer revision, List> rows) {} + private static ResponseStatusException bad(String reason) { return new ResponseStatusException(HttpStatus.BAD_REQUEST,reason); } + private static String text(Object value,int limit,String label,boolean required) { + String v=Objects.toString(value,"").trim(); + if((required && v.isEmpty()) || v.length()>limit) throw bad(label+"不能为空且长度不能超过 "+limit); + return v; + } + public List> normalizeRows(List> input) { + if(input==null || input.isEmpty() || input.size()>500)throw bad("模板需包含 1–500 个检测项"); + List> rows=new ArrayList<>();Set keys=new HashSet<>(); + for(var raw:input) { + if(raw==null)throw bad("检测项格式无效"); + String name=text(raw.get("name"),120,"检测项名称",true),table=text(raw.get("table"),20,"类别",true),type=text(raw.get("type"),30,"几何类型",true),control=text(raw.get("control"),50,"控制项",true); + if(!Set.of("feature","gauge").contains(table) || !Set.of("circle","plane","cylinder","distance","hole_distance","plane_distance","point_distance").contains(type))throw bad("不支持的检测项类别或几何类型"); + if(table.equals("feature")!=Set.of("circle","plane","cylinder").contains(type))throw bad("检测项类别与几何类型不一致"); + double nominal; + try {nominal=Double.parseDouble(Objects.toString(raw.get("nominal_mm"),""));}catch(NumberFormatException error){throw bad(name+":请填写有效名义值");} + if(!Double.isFinite(nominal) || nominal<0 || nominal>10000000)throw bad(name+":名义值范围为 0–10000000 mm"); + String tol=text(raw.get("tol_text"),100,"公差",false); + if(!tol.isEmpty() && !tol.replace(" ","").matches("(?:±|\\+/-)\\d+(?:\\.\\d+)?|[+-]?\\d+(?:\\.\\d+)?/[+-]?\\d+(?:\\.\\d+)?"))throw bad(name+":公差请使用 ±0.1 或 +0.1/0 等格式"); + if(!keys.add(table+"\0"+name+"\0"+control))throw bad(name+":存在重复检测项与控制字段"); + Map row=new LinkedHashMap<>();row.put("table",table);row.put("type",type);row.put("name",name);row.put("control",control);row.put("nominal_mm",nominal);row.put("tol_text",tol);row.put("notes",text(raw.get("notes"),1000,"备注",false));rows.add(row); + } + return rows; + } + public Map page(long tenant,String name,String enabled,int page,int size) { + ensureDefaults(tenant); + String where=" WHERE tenant_id=? AND deleted=FALSE AND name LIKE ?";List args=new ArrayList<>(List.of(tenant,"%"+name+"%")); + if(!enabled.isBlank()){where+=" AND enabled=?";args.add(Boolean.parseBoolean(enabled));} + Long total=jdbc.queryForObject("SELECT COUNT(*) FROM lab_inspection_template"+where,Long.class,args.toArray());args.add(size);args.add((page-1)*size); + var list=jdbc.queryForList("SELECT id,name,description,part_numbers AS partNumbers,enabled,revision,row_count AS rowCount,builtin_key AS builtinKey,update_time AS updateTime FROM lab_inspection_template"+where+" ORDER BY update_time DESC,id LIMIT ? OFFSET ?",args.toArray()); + return Map.of("list",list,"total",total==null?0:total); + } + public Map detail(long tenant,String id) { + var found=jdbc.queryForList("SELECT id,name,description,part_numbers AS partNumbers,enabled,revision,rows_json AS rowsJson,row_count AS rowCount,builtin_key AS builtinKey FROM lab_inspection_template WHERE tenant_id=? AND id=? AND deleted=FALSE",tenant,id); + if(found.isEmpty())throw new ResponseStatusException(HttpStatus.NOT_FOUND,"检测计划模板不存在"); + var row=found.get(0); + Object flag=row.get("enabled");row.put("enabled",Boolean.TRUE.equals(flag) || flag instanceof Number n && n.intValue()!=0); + try {row.put("rows",mapper.readValue(Objects.toString(row.remove("rowsJson")),new TypeReference>>(){}));}catch(Exception e){throw new IllegalStateException("模板字段读取失败",e);} + return row; + } + @Transactional public Map save(long tenant,SaveRequest request,String creator) { + String name=text(request.name(),100,"模板名称",true),description=text(request.description(),1000,"说明",false),parts=text(request.partNumbers(),500,"零件号",false); + var rows=normalizeRows(request.rows());String json;try{json=mapper.writeValueAsString(rows);}catch(Exception e){throw bad("模板字段无法保存");} + String id=request.id();boolean enabled=Boolean.TRUE.equals(request.enabled()); + if(id==null || id.isBlank()) {id=UUID.randomUUID().toString().replace("-","");jdbc.update("INSERT INTO lab_inspection_template(id,tenant_id,name,description,part_numbers,enabled,rows_json,row_count,creator) VALUES(?,?,?,?,?,?,?,?,?)",id,tenant,name,description,parts,enabled,json,rows.size(),creator);} + else { + detail(tenant,id); + int count=jdbc.update("UPDATE lab_inspection_template SET name=?,description=?,part_numbers=?,enabled=?,rows_json=?,row_count=?,revision=revision+1,update_time=NOW() WHERE tenant_id=? AND id=? AND revision=? AND deleted=FALSE",name,description,parts,enabled,json,rows.size(),tenant,id,request.revision()); + if(count!=1)throw new ResponseStatusException(HttpStatus.CONFLICT,"模板已被修改,请重新打开后编辑"); + } + return detail(tenant,id); + } + public void remove(long tenant,String id,int revision) { + detail(tenant,id); + if(jdbc.update("UPDATE lab_inspection_template SET deleted=TRUE,enabled=FALSE,revision=revision+1,update_time=NOW() WHERE tenant_id=? AND id=? AND revision=? AND deleted=FALSE",tenant,id,revision)!=1)throw new ResponseStatusException(HttpStatus.CONFLICT,"模板已被修改,请刷新后操作"); + } + public Map snapshot(long tenant,String id) { + var row=detail(tenant,id);if(!Boolean.TRUE.equals(row.get("enabled")) && !Objects.equals(row.get("enabled"),1))throw bad("模板已停用,请重新选择"); + return Map.of("id","managed-"+id,"label",row.get("name"),"version",row.get("revision").toString(),"rows",row.get("rows"),"managed",true); + } + public Map options(long tenant) { + ensureDefaults(tenant); + var list=jdbc.queryForList("SELECT id,name,revision,row_count AS rowCount FROM lab_inspection_template WHERE tenant_id=? AND deleted=FALSE AND enabled=TRUE ORDER BY name,id",tenant); + return Map.of("templates",list.stream().map(r->Map.of("id","managed-"+r.get("id"),"label",r.get("name"),"version",r.get("revision").toString(),"automatic",true,"rowCount",r.get("rowCount"))).toList()); + } + public Map resolveUpload(long tenant,String selection,String targetName,String drawingName) { + ensureDefaults(tenant); + if(selection!=null && selection.startsWith("managed-"))return snapshot(tenant,selection.substring(8)); + if(!"auto".equals(selection))return null; + var templates=jdbc.queryForList("SELECT id,part_numbers FROM lab_inspection_template WHERE tenant_id=? AND deleted=FALSE AND enabled=TRUE AND part_numbers<>''",tenant); + List matching=new ArrayList<>();String names=Objects.toString(targetName,"")+"\n"+Objects.toString(drawingName,""); + for(var row:templates)for(String part:row.get("part_numbers").toString().split("[,,;;\\s]+")) { + if(!part.isBlank() && Pattern.compile("(?1)throw bad("图纸或数模匹配多个检测计划,请明确选择模板"); + return matching.isEmpty()?null:snapshot(tenant,matching.get(0)); + } +} diff --git a/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/master/LabFixtureFrameworkService.java b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/master/LabFixtureFrameworkService.java index 43a889f..3f81e2e 100644 --- a/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/master/LabFixtureFrameworkService.java +++ b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/master/LabFixtureFrameworkService.java @@ -41,6 +41,12 @@ public class LabFixtureFrameworkService { primary();var rows=jdbc.queryForList("SELECT id,urls_json AS urlsJson,updated_at AS updatedAt FROM lab_fixture_framework WHERE fixture_id=? AND status='READY' ORDER BY version_seq DESC LIMIT 1",fixture); return rows.isEmpty()?null:rows.get(0); } + public ScannerHttpClient.Binary file(Long fixture,String version,String fileId){ + primary();if(fixtures.getFixture(fixture)==null)throw invalidParamException("夹具不存在"); + var rows=jdbc.queryForList("SELECT urls_json AS urlsJson FROM lab_fixture_framework WHERE fixture_id=? AND id=? AND status='READY'",fixture,version); + if(rows.isEmpty()||ScannerFrameworkReferences.sources(rows.get(0).get("urlsJson")).stream().noneMatch(source->source.fileId().equals(fileId)))throw invalidParamException("该框架点文件不属于所选夹具版本"); + var binary=store.open(fileId);if(binary==null)throw invalidParamException("框架点文件不存在,请重新录入或导入");return binary; + } @Transactional(rollbackFor=Exception.class) public String importFiles(Long fixture,String expectedVersion,boolean confirmed,Object references){ primary();if(!confirmed)throw invalidParamException("请确认文件属于此夹具,允许保存为可复用框架点"); diff --git a/am-backend/yudao-module-lab/src/main/resources/inspection/plan-template-seeds.json b/am-backend/yudao-module-lab/src/main/resources/inspection/plan-template-seeds.json new file mode 100644 index 0000000..a71ef28 --- /dev/null +++ b/am-backend/yudao-module-lab/src/main/resources/inspection/plan-template-seeds.json @@ -0,0 +1,474 @@ +[ + { + "builtinKey": "family-handlebar", + "name": "方向把 41100-FB64-02000 · 图纸A版", + "description": "从已有图纸计划初始化,可维护名称、名义值、公差及检测项。", + "partNumbers": "41100-FB64-02000", + "rows": [ + { + "table": "feature", + "type": "circle", + "name": "方向把-立管外径", + "control": "直径", + "nominal_mm": 30.0, + "tol_text": "±0.2", + "notes": "图纸第1页:右视图立管Φ30" + }, + { + "table": "feature", + "type": "circle", + "name": "方向把-立管内径", + "control": "直径", + "nominal_mm": 21.0, + "tol_text": "+0.1/0", + "notes": "图纸第1页:右视图立管Φ21" + }, + { + "table": "feature", + "type": "circle", + "name": "方向把-F截面孔径", + "control": "直径", + "nominal_mm": 10.0, + "tol_text": "+0.1/0", + "notes": "图纸第1页:F-F截面Φ10,区分端面/配合孔位置" + }, + { + "table": "feature", + "type": "circle", + "name": "方向把-F截面外径", + "control": "直径", + "nominal_mm": 21.1, + "tol_text": "+0.1/0", + "notes": "图纸第1页:F-F截面Φ21.1" + }, + { + "table": "feature", + "type": "circle", + "name": "方向把-左把管孔径", + "control": "直径", + "nominal_mm": 5.2, + "tol_text": "+0.1/0", + "notes": "图纸第1页:A向旋转视图,左端Φ5.2" + }, + { + "table": "feature", + "type": "circle", + "name": "方向把-右把管孔径", + "control": "直径", + "nominal_mm": 5.2, + "tol_text": "+0.1/0", + "notes": "图纸第1页:B向旋转视图,右端Φ5.2" + }, + { + "table": "feature", + "type": "circle", + "name": "方向把-支架安装孔径", + "control": "直径", + "nominal_mm": 6.8, + "tol_text": "+0.1/0", + "notes": "图纸第1页:俯视图2-Φ6.8,两个孔需分别复核" + }, + { + "table": "gauge", + "type": "distance", + "name": "方向把-支架安装孔心距", + "control": "孔距", + "nominal_mm": 211.0, + "tol_text": "±1", + "notes": "图纸第1页:俯视图左右支架孔心距211" + }, + { + "table": "gauge", + "type": "distance", + "name": "方向把-立管定位高度", + "control": "长度", + "nominal_mm": 165.0, + "tol_text": "0/-1", + "notes": "图纸第1页:右侧视图165,自定位中心至下孔中心的投影尺寸" + }, + { + "table": "gauge", + "type": "distance", + "name": "方向把-支架侧向尺寸", + "control": "长度", + "nominal_mm": 41.5, + "tol_text": "±1", + "notes": "图纸第1页:右视图41.5,规定投影方向" + } + ] + }, + { + "builtinKey": "family-fork", + "name": "前叉 401Y0-Q610-02GH5 · 图纸A版", + "description": "从已有图纸计划初始化,可维护名称、名义值、公差及检测项。", + "partNumbers": "401Y0-Q610-02GH5", + "rows": [ + { + "table": "feature", + "type": "circle", + "name": "前叉-轴孔直径", + "control": "直径", + "nominal_mm": 12.1, + "tol_text": "+0.2/0", + "notes": "图纸第1页:剖视图,左右叉端轴孔;重复孔需分别复核" + }, + { + "table": "feature", + "type": "circle", + "name": "前叉-安装孔直径", + "control": "直径", + "nominal_mm": 8.2, + "tol_text": "+0.2/0", + "notes": "图纸第1页:剖视图,2-Φ8.2;重复孔需分别复核" + }, + { + "table": "feature", + "type": "circle", + "name": "前叉-立管端外径", + "control": "直径", + "nominal_mm": 23.8, + "tol_text": "0/-0.2", + "notes": "图纸第1页:主视图,立管左端Φ23.8" + }, + { + "table": "feature", + "type": "circle", + "name": "前叉-立管外径", + "control": "直径", + "nominal_mm": 25.0, + "tol_text": "+0.2/0", + "notes": "图纸第1页:主视图,立管Φ25" + }, + { + "table": "feature", + "type": "circle", + "name": "前叉-内管外径", + "control": "直径", + "nominal_mm": 27.0, + "tol_text": "-0.02/-0.05", + "notes": "图纸第1页:剖视图,Φ27配合外径" + }, + { + "table": "gauge", + "type": "distance", + "name": "前叉-立管段长390", + "control": "长度", + "nominal_mm": 390.0, + "tol_text": "±1", + "notes": "图纸第1页:主视图,立管端面至连接基准面的轴向尺寸" + }, + { + "table": "gauge", + "type": "distance", + "name": "前叉-立管段长340", + "control": "长度", + "nominal_mm": 340.0, + "tol_text": "±1", + "notes": "图纸第1页:主视图,定位截面至连接基准面的轴向尺寸" + }, + { + "table": "gauge", + "type": "distance", + "name": "前叉-叉腿纵向383", + "control": "长度", + "nominal_mm": 383.0, + "tol_text": "±2.5", + "notes": "图纸第1页:主视图,连接端基准至轴孔中心的投影长度;不是左右管间距" + }, + { + "table": "gauge", + "type": "distance", + "name": "前叉-安装孔心距45", + "control": "孔距", + "nominal_mm": 45.0, + "tol_text": "±0.1", + "notes": "图纸第1页:主视图,两个M6安装孔轴心距;需核对螺纹轴的几何提取" + }, + { + "table": "gauge", + "type": "distance", + "name": "前叉-E向安装孔心距90", + "control": "孔距", + "nominal_mm": 90.0, + "tol_text": "±0.5", + "notes": "图纸第1页:E向视图,同侧安装孔轴心距" + } + ] + }, + { + "builtinKey": "family-wheel", + "name": "前轮 311L0-R560-00000 · 图纸B版", + "description": "从已有图纸计划初始化,可维护名称、名义值、公差及检测项。", + "partNumbers": "311L0-R560-00000", + "rows": [ + { + "table": "feature", + "type": "circle", + "name": "前轮-中心通孔", + "control": "直径", + "nominal_mm": 28.0, + "tol_text": "", + "notes": "图纸第1页:F-F剖面Φ28" + }, + { + "table": "feature", + "type": "circle", + "name": "前轮-轴承座A", + "control": "直径", + "nominal_mm": 32.0, + "tol_text": "-0.025/-0.050", + "notes": "图纸第1页:F-F剖面,A基准轴承座" + }, + { + "table": "feature", + "type": "circle", + "name": "前轮-轴承座B", + "control": "直径", + "nominal_mm": 32.0, + "tol_text": "-0.025/-0.050", + "notes": "图纸第1页:F-F剖面,B基准轴承座;与A为不同位置" + }, + { + "table": "feature", + "type": "circle", + "name": "前轮-轮辋外径", + "control": "直径", + "nominal_mm": 332.0, + "tol_text": "", + "notes": "图纸第1页:F-F外轮廓Φ332,需正确截面" + }, + { + "table": "feature", + "type": "circle", + "name": "前轮-标定直径", + "control": "直径", + "nominal_mm": 304.0, + "tol_text": "", + "notes": "图纸第1页:F-F标定直径Φ304,需按标定轮廓测量" + }, + { + "table": "feature", + "type": "circle", + "name": "前轮-螺栓通孔", + "control": "直径", + "nominal_mm": 10.5, + "tol_text": "", + "notes": "图纸第1页:F-F中3-Φ10.5;不可与3-M8-6H混用" + }, + { + "table": "feature", + "type": "circle", + "name": "前轮-轮毂外径", + "control": "直径", + "nominal_mm": 50.5, + "tol_text": "", + "notes": "图纸第1页:F-F中Φ50.5,不能绑定轮辋" + }, + { + "table": "gauge", + "type": "distance", + "name": "前轮-轮辋总宽", + "control": "长度", + "nominal_mm": 80.0, + "tol_text": "+1/-0.5", + "notes": "图纸第1页:F-F总宽,两侧轮辋外缘" + }, + { + "table": "gauge", + "type": "distance", + "name": "前轮-轮辋内宽", + "control": "长度", + "nominal_mm": 63.5, + "tol_text": "+1/-0.5", + "notes": "图纸第1页:F-F内宽,两侧规定截面" + }, + { + "table": "gauge", + "type": "distance", + "name": "前轮-压装完成宽度", + "control": "长度", + "nominal_mm": 62.0, + "tol_text": "±0.2", + "notes": "图纸第1页:压装完成放大图,轴承外端面间距;不是任意CAD平行面" + }, + { + "table": "gauge", + "type": "distance", + "name": "前轮-轴向总长", + "control": "长度", + "nominal_mm": 98.0, + "tol_text": "0/-0.2", + "notes": "图纸第1页:F-F轴向总长度" + } + ] + }, + { + "builtinKey": "family-rack", + "name": "后衣架 510T0-FB91-00000 · 图纸A版", + "description": "从已有图纸计划初始化,可维护名称、名义值、公差及检测项。", + "partNumbers": "510T0-FB91-00000", + "rows": [ + { + "table": "feature", + "type": "circle", + "name": "后衣架-圆形流水孔", + "control": "直径", + "nominal_mm": 5.2, + "tol_text": "", + "notes": "图纸第1页:俯视图Φ5.2流水孔,多个位置需分别复核" + }, + { + "table": "gauge", + "type": "distance", + "name": "后衣架-前安装孔心距", + "control": "孔距", + "nominal_mm": 202.0, + "tol_text": "±1", + "notes": "图纸第1页:俯视图左端两安装孔中心距202" + }, + { + "table": "gauge", + "type": "distance", + "name": "后衣架-前横梁孔心距", + "control": "孔距", + "nominal_mm": 80.0, + "tol_text": "±0.2", + "notes": "图纸第1页:俯视图前横梁上下安装孔中心距80" + }, + { + "table": "gauge", + "type": "distance", + "name": "后衣架-后横梁孔心距", + "control": "孔距", + "nominal_mm": 138.0, + "tol_text": "±0.2", + "notes": "图纸第1页:俯视图后横梁上下安装孔中心距138" + }, + { + "table": "gauge", + "type": "distance", + "name": "后衣架-侧面安装孔心距", + "control": "孔距", + "nominal_mm": 20.0, + "tol_text": "±0.2", + "notes": "图纸第1页:右侧视图安装板两孔心距20" + }, + { + "table": "gauge", + "type": "distance", + "name": "后衣架-左侧投影高度", + "control": "长度", + "nominal_mm": 147.0, + "tol_text": "±1", + "notes": "图纸第1页:下侧视图标注147,方向与投影基准需确认" + }, + { + "table": "gauge", + "type": "distance", + "name": "后衣架-安装段投影长度", + "control": "长度", + "nominal_mm": 50.8, + "tol_text": "±1", + "notes": "图纸第1页:下侧视图50.8,按规定投影方向" + }, + { + "table": "gauge", + "type": "distance", + "name": "后衣架-框架总宽参考", + "control": "长度", + "nominal_mm": 229.4, + "tol_text": "", + "notes": "图纸第1页:俯视图总宽229.4;未注公差不自动套用" + }, + { + "table": "gauge", + "type": "distance", + "name": "后衣架-侧向深度参考", + "control": "长度", + "nominal_mm": 130.0, + "tol_text": "", + "notes": "图纸第1页:右侧视图130;按规定方向" + } + ] + }, + { + "builtinKey": "family-shock", + "name": "后减震 404J0-FB25-00GH7 · 图纸未标注版 · 无配套扫描", + "description": "从已有图纸计划初始化,可维护名称、名义值、公差及检测项。", + "partNumbers": "404J0-FB25-00GH7", + "rows": [ + { + "table": "feature", + "type": "circle", + "name": "后减震-安装孔直径", + "control": "直径", + "nominal_mm": 10.1, + "tol_text": "+0.2/0", + "notes": "图纸第1页:总剖面两端安装孔;需两端分别复核" + }, + { + "table": "feature", + "type": "circle", + "name": "后减震-弹簧外径", + "control": "直径", + "nominal_mm": 43.5, + "tol_text": "±0.5", + "notes": "图纸第1页:总剖面弹簧包络外径,不能当单个簧丝截面拟合" + }, + { + "table": "feature", + "type": "circle", + "name": "后减震-簧丝直径", + "control": "直径", + "nominal_mm": 7.5, + "tol_text": "±0.1", + "notes": "图纸第1页:总剖面,明确为涂装前尺寸" + }, + { + "table": "gauge", + "type": "distance", + "name": "后减震-安装孔心距", + "control": "孔距", + "nominal_mm": 200.0, + "tol_text": "±1.5", + "notes": "图纸第1页:两端安装孔中心距离" + }, + { + "table": "gauge", + "type": "distance", + "name": "后减震-主体长度", + "control": "长度", + "nominal_mm": 145.0, + "tol_text": "±1.5", + "notes": "图纸第1页:剖视图规定端面之间主体长度" + }, + { + "table": "gauge", + "type": "distance", + "name": "后减震-左端头宽度", + "control": "长度", + "nominal_mm": 21.0, + "tol_text": "0/-0.2", + "notes": "图纸第1页:左端头两端面宽度" + }, + { + "table": "gauge", + "type": "distance", + "name": "后减震-右端头宽度", + "control": "长度", + "nominal_mm": 21.0, + "tol_text": "0/-0.2", + "notes": "图纸第1页:右端头两端面宽度" + }, + { + "table": "gauge", + "type": "distance", + "name": "后减震-右段长度", + "control": "长度", + "nominal_mm": 30.0, + "tol_text": "±1.5", + "notes": "图纸第1页:剖面右段标注30" + } + ] + } +] \ No newline at end of file diff --git a/am-backend/yudao-server/src/main/resources/application.yaml b/am-backend/yudao-server/src/main/resources/application.yaml index 9f6a9bd..74815c1 100644 --- a/am-backend/yudao-server/src/main/resources/application.yaml +++ b/am-backend/yudao-server/src/main/resources/application.yaml @@ -330,3 +330,12 @@ yudao: message-bus: type: redis debug: false +--- +lab: + inspection: + # Supplier EXE defaults; comparison work is separate from physical device waits. + base-url: ${INSPECTION_PYTHON_BASE_URL:http://127.0.0.1:8769} + connect-timeout: ${INSPECTION_CONNECT_TIMEOUT:3s} + request-timeout: ${INSPECTION_REQUEST_TIMEOUT:10m} + poll-interval-ms: ${INSPECTION_POLL_INTERVAL_MS:15000} + storage-directory: ${INSPECTION_STORAGE_DIRECTORY:${lab.artifact.nas-root:./.local/artifacts}/inspection-transfer} diff --git a/am-web/src/api/lab/inspection/index.ts b/am-web/src/api/lab/inspection/index.ts new file mode 100644 index 0000000..b8a7401 --- /dev/null +++ b/am-web/src/api/lab/inspection/index.ts @@ -0,0 +1,33 @@ +import request from '@/config/axios' +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 templates = () => request.get({ url: `${base}/templates/options` }) +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 }) +export const removeTemplate = (id: string, revision: number) => + request.delete({ url: `${base}/templates/${id}`, params: { revision } }) +export const state = (id: string) => request.get({ url: `${root}/tasks/${id}` }) +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}` }) +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 templateFile = (id: string) => + request.download({ url: `${root}/plan/templates/${encodeURIComponent(id)}` }) +export function saveBlob(blob: Blob, name: string) { + const url = URL.createObjectURL(blob), + a = document.createElement('a') + a.href = url + a.download = name + a.click() + setTimeout(() => URL.revokeObjectURL(url), 1000) +} diff --git a/am-web/src/api/lab/master/fixture/index.ts b/am-web/src/api/lab/master/fixture/index.ts index f539a54..2457d9f 100644 --- a/am-web/src/api/lab/master/fixture/index.ts +++ b/am-web/src/api/lab/master/fixture/index.ts @@ -1,6 +1,7 @@ import request from '@/config/axios' export const frameworkDefinition = () => request.get({ url: '/lab/master/fixture/framework/definition' }) export const getFramework = (fixtureId: number | string) => request.get({ url: '/lab/master/fixture/framework/get', params: { fixtureId } }) +export const downloadFramework = (fixtureId: number | string, version: string, fileId: string) => request.download({ url: '/lab/master/fixture/framework/file', params: { fixtureId, version, fileId }, timeout: 180000 }) export const syncFramework = (fixtureId: number | string) => request.post({ url: '/lab/master/fixture/framework/sync', params: { fixtureId } }) export const startFramework = (data: any) => request.post({ url: '/lab/master/fixture/framework/start', data }) export const stopFramework = (fixtureId: number | string) => request.post({ url: '/lab/master/fixture/framework/stop', params: { fixtureId } }) diff --git a/am-web/src/api/lab/scan-task/agvView.ts b/am-web/src/api/lab/scan-task/agvView.ts index 13e606c..ff325cb 100644 --- a/am-web/src/api/lab/scan-task/agvView.ts +++ b/am-web/src/api/lab/scan-task/agvView.ts @@ -1,5 +1,5 @@ import request from '@/config/axios' const base = '/lab/execution/agv-view' -export const agvTargets = (params: any, signal?: AbortSignal) => request.get({ url: base + '/targets', params, signal }) -export const agvState = (params: any, signal?: AbortSignal) => request.get({ url: base + '/state', params, signal }) -export const agvMap = (params: any, signal?: AbortSignal) => request.get({ url: base + '/map', params, signal, timeout: 15000 }) +export const agvTargets = (params: any, signal?: AbortSignal) => request.get({ url: base + '/targets', params, signal, silentError: true }) +export const agvState = (params: any, signal?: AbortSignal) => request.get({ url: base + '/state', params, signal, silentError: true }) +export const agvMap = (params: any, signal?: AbortSignal) => request.get({ url: base + '/map', params, signal, timeout: 15000, silentError: true }) diff --git a/am-web/src/config/axios/service.ts b/am-web/src/config/axios/service.ts index 40d0851..80e4c37 100644 --- a/am-web/src/config/axios/service.ts +++ b/am-web/src/config/axios/service.ts @@ -146,6 +146,9 @@ service.interceptors.response.use( return Promise.reject(msg) } else if (isPlatformUnauthorized(data) && canRefreshRequest(config)) { return replayAuthenticatedRequest(service, config) + } else if ((config as InternalAxiosRequestConfig & { silentError?: boolean }).silentError && !isPlatformUnauthorized(data) && code !== 0 && code !== 200) { + // Optional map views handle their own fallback; authentication still follows the normal path. + return Promise.reject(new Error(msg)) } else if (code === 500) { ElMessage.error(t('sys.api.errMsg500')) return Promise.reject(new Error(msg)) @@ -183,6 +186,7 @@ service.interceptors.response.use( return replayAuthenticatedRequest(service, error.config) } return rejectRequestFailure(error, (failure: AxiosError) => { + if ((failure.config as (InternalAxiosRequestConfig & { silentError?: boolean }) | undefined)?.silentError && failure.response?.status !== 401) return const error = failure console.log('err' + error) // for debug let { message } = error diff --git a/am-web/src/router/modules/remaining.ts b/am-web/src/router/modules/remaining.ts index 74609b7..145979b 100644 --- a/am-web/src/router/modules/remaining.ts +++ b/am-web/src/router/modules/remaining.ts @@ -40,7 +40,8 @@ const remainingRouter: AppRouteRecordRaw[] = [ { path: 'tasks', name: 'DimensionTasks', component: () => import('@/views/lab/dimension/index.vue'), meta: { title: '全部任务', hidden: true, canTo: true } }, { path: 'mine', name: 'DimensionMine', component: () => import('@/views/lab/dimension/index.vue'), meta: { title: '我的任务', hidden: true, canTo: true } }, { path: 'results', name: 'DimensionResults', component: () => import('@/views/lab/dimension/index.vue'), meta: { title: '最终成果', hidden: true, canTo: true } }, - { path: 'workbench/:id', name: 'DimensionWorkbench', component: () => import('@/views/lab/dimension/workbench.vue'), meta: { title: '检测任务工作台', hidden: true, canTo: true, activeMenu: '/lab/dimension/tasks' } } + { path: 'workbench/:id', name: 'DimensionWorkbench', component: () => import('@/views/lab/dimension/workbench.vue'), meta: { title: '检测任务工作台', hidden: true, canTo: true, activeMenu: '/lab/dimension/tasks' } }, + { path: 'inspection-templates', name: 'LabInspectionTemplates', component: () => import('@/views/lab/inspection/templates.vue'), meta: { title: '检测计划', hidden: true, canTo: true, activeMenu: '/lab/dimension/tasks' } } ] }, ...cmvrRoutes, diff --git a/am-web/src/views/lab/dimension/ComparisonPanel.vue b/am-web/src/views/lab/dimension/ComparisonPanel.vue new file mode 100644 index 0000000..1950f85 --- /dev/null +++ b/am-web/src/views/lab/dimension/ComparisonPanel.vue @@ -0,0 +1,144 @@ + + + diff --git a/am-web/src/views/lab/dimension/workbench.vue b/am-web/src/views/lab/dimension/workbench.vue index a8b2375..3b904c7 100644 --- a/am-web/src/views/lab/dimension/workbench.vue +++ b/am-web/src/views/lab/dimension/workbench.vue @@ -2,9 +2,10 @@