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.
This commit is contained in:
lixiaolong 2026-11-12 10:24:55 +08:00
parent 0a5a083e48
commit c903364fa2
46 changed files with 5234 additions and 97 deletions

View File

@ -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;

View File

@ -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<String,Object> 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<String,Object> 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<InputStream> 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<String,Object>)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,"检测数据格式无效,请检查检测计划或计算服务返回内容");}
}

View File

@ -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<Object> 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<Object> options(){return CommonResult.success(service.options(TenantContextHolder.getRequiredTenantId()));}
@GetMapping("/{id}") @PreAuthorize("@ss.hasPermission('lab:result:query')")
public CommonResult<Object> detail(@PathVariable String id){return CommonResult.success(service.detail(TenantContextHolder.getRequiredTenantId(),id));}
@PostMapping("/save") @PreAuthorize("@ss.hasPermission('lab:result:confirm')")
public CommonResult<Object> 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<Object> remove(@PathVariable String id,@RequestParam int revision){service.remove(TenantContextHolder.getRequiredTenantId(),id,revision);return CommonResult.success(true);}
@ExceptionHandler(ResponseStatusException.class)
public CommonResult<Object> error(ResponseStatusException e){return CommonResult.error(e.getStatusCode().value(),e.getReason());}
}

View File

@ -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<org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody> 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()));}

View File

@ -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<Map<String,Object>> 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<Long,Map<String,Object>> cases=new HashMap<>(),catalog=new HashMap<>();Map<Long,List<Map<String,Object>>> 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<String,Object> 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<String,Object> inputFile(Map<String,Object> state,String column,String role,boolean verify){
@ -195,8 +196,8 @@ public class DimensionService {
private String stage(Map<String,Object> 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<String,Object> publicFile(Map<String,Object> 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<String,cn.iocoder.yudao.module.lab.service.inspection.LabInspectionGateway.StoredFile> 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<String,cn.iocoder.yudao.module.lab.service.inspection.LabInspectionGateway.StoredFile>();
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<String,Object> 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;
}
}

View File

@ -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;i<points.size();i++)if(i%2==0||i==points.size()-1||i>0&&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<<Math.min(4,trace.failures++));}
if(System.currentTimeMillis()-trace.saved>5000)save(trace);
}

View File

@ -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)<count&&Files.getFileStore(destination.getParent()).getUsableSpace()<RESERVE)throw new IOException("归档磁盘余量不足");
out.write(block,0,count);
}
}
if(total==0||declared>=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()<RESERVE)throw new IOException("归档磁盘空间不足");
Path directory=Files.createTempDirectory(root,"result-");Path mesh=null,pdf=null;
boolean success=false;
try {
Set<String> 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<String> 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);
}
}

View File

@ -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<String,Object> 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<Map<String,Object>> rows(String sql,Object...args){return jdbc.queryForList(sql,args);}
private Map<String,Object> 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<String,Object> 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<String,Object> 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<String,Object> latestView(long task,long unit) {
dimensions.checkComparisonAccess(task,unit,"",false);var job=latest(task,unit);return job==null?Map.of():publicJob(job);
}
public Map<String,Object> jobView(String engine){return publicJob(engineJob(engine,false));}
private Map<String,Object> publicJob(Map<String,Object> source) {
var result=new LinkedHashMap<String,Object>(source);
result.remove("submission_key");
// Input JSON contains file IDs, hashes, revisions and names, never local disk paths.
return result;
}
private Map<String,String> settings(Start req,DimensionService.ComparisonInput input) throws Exception {
var options=new LinkedHashMap<String,String>();
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<String,Object> job,DimensionService.ComparisonInput input,Map<String,String> options,boolean created) {}
public Map<String,Object> 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<String,Object> savedState(String engine) throws Exception {
var job=engineJob(engine,false);var row=repository.scan(tenant(),engine);
@SuppressWarnings("unchecked") var state=(Map<String,Object>)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<String,Object> 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<String,Object>)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<String,Object>)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<Map<String,Object>> 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增量;扫描执行不受影响");}
}
}

View File

@ -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<InputStream> 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<InputStream> source,InputStream body) implements HttpResponse<InputStream> {
public int statusCode(){return source.statusCode();}public HttpRequest request(){return source.request();}
public Optional<HttpResponse<InputStream>> previousResponse(){return source.previousResponse();}
public HttpHeaders headers(){return source.headers();}public Optional<javax.net.ssl.SSLSession> sslSession(){return source.sslSession();}
public URI uri(){return source.uri();}public HttpClient.Version version(){return source.version();}
}
public Map<String,Object> 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<InputStream> 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<InputStream> submit(Map<String,String> settings,Map<String,StoredFile> files) {
String boundary="Inspection"+UUID.randomUUID().toString().replace("-","");
List<HttpRequest.BodyPublisher> 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<InputStream> 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"),""));}
}

View File

@ -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";
}

View File

@ -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<String,Object> 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);
}
}

View File

@ -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<Long> 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<Map<String,Object>> 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<Map<String,Object>> 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<Map<String,Object>> normalizeRows(List<Map<String,Object>> input) {
if(input==null || input.isEmpty() || input.size()>500)throw bad("模板需包含 1–500 个检测项");
List<Map<String,Object>> rows=new ArrayList<>();Set<String> 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<String,Object> 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<String,Object> 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<Object> 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<String,Object> 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<List<Map<String,Object>>>(){}));}catch(Exception e){throw new IllegalStateException("模板字段读取失败",e);}
return row;
}
@Transactional public Map<String,Object> 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<String,Object> 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<String,Object> 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<String,Object> 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<String> 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("(?<![A-Z0-9])"+Pattern.quote(part)+"(?![A-Z0-9])",Pattern.CASE_INSENSITIVE).matcher(names).find()){matching.add(row.get("id").toString());break;}
}
if(matching.size()>1)throw bad("图纸或数模匹配多个检测计划,请明确选择模板");
return matching.isEmpty()?null:snapshot(tenant,matching.get(0));
}
}

View File

@ -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("请确认文件属于此夹具,允许保存为可复用框架点");

View File

@ -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"
}
]
}
]

View File

@ -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}

View File

@ -0,0 +1,33 @@
import request from '@/config/axios'
const base = '/lab/inspection',
root = `${base}/api`
export const health = () => request.get<any>({ url: `${base}/health`, timeout: 10000 })
export const comparison = (taskId: string, unitId: string, signal?: AbortSignal) =>
request.get<any>({ url: `${base}/comparison`, params: { taskId, unitId }, signal })
export const startComparison = (data: any) => request.post<any>({ 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<Blob>({ url: `${root}/tasks/${id}/files/${name}` })
export const templateFile = (id: string) =>
request.download<Blob>({ 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)
}

View File

@ -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<Blob>({ 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 } })

View File

@ -1,5 +1,5 @@
import request from '@/config/axios'
const base = '/lab/execution/agv-view'
export const agvTargets = (params: any, signal?: AbortSignal) => request.get<any[]>({ url: base + '/targets', params, signal })
export const agvState = (params: any, signal?: AbortSignal) => request.get<any>({ url: base + '/state', params, signal })
export const agvMap = (params: any, signal?: AbortSignal) => request.get<any>({ url: base + '/map', params, signal, timeout: 15000 })
export const agvTargets = (params: any, signal?: AbortSignal) => request.get<any[]>({ url: base + '/targets', params, signal, silentError: true })
export const agvState = (params: any, signal?: AbortSignal) => request.get<any>({ url: base + '/state', params, signal, silentError: true })
export const agvMap = (params: any, signal?: AbortSignal) => request.get<any>({ url: base + '/map', params, signal, timeout: 15000, silentError: true })

View File

@ -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

View File

@ -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,

View File

@ -0,0 +1,144 @@
<template>
<section class="comparison-panel">
<div class="comparison-heading">
<div><h3>尺寸比对</h3><span class="secondary">自动使用本任务选定的数模、PDF和扫描PLY。</span></div>
<div class="comparison-buttons">
<el-tag :type="health.available ? 'success' : 'info'">{{ health.available ? '计算服务就绪' : '计算服务未就绪' }}</el-tag>
<el-button :loading="loading" @click="refresh(true)">刷新状态</el-button>
<el-button v-hasPermi="['lab:result:query']" @click="router.push('/lab/dimension/inspection-templates')">维护检测计划</el-button>
</div>
</div>
<el-alert v-if="error" :title="error" type="error" :closable="false" />
<el-alert v-else-if="!health.available" :title="health.message || '请先启动本机检测EXE,再刷新状态。'" type="info" :closable="false" />
<el-form label-position="top" class="comparison-options" :disabled="busy">
<el-form-item label="检测计划">
<el-select v-model="options.planTemplateId" filterable class="plan-select">
<el-option label="按图纸及完整零件号自动匹配" value="auto" />
<el-option v-for="item in catalog" :key="item.id" :value="item.id" :label="`${item.label} · V${item.version}`" />
<el-option label="CAD几何检测(无图纸计划)" value="cad-geometry" />
</el-select>
</el-form-item>
<el-collapse><el-collapse-item title="单位与处理设置" name="options">
<div class="comparison-fields">
<el-form-item label="扫描数据单位"><el-select v-model="options.sourceScale"><el-option v-for="item in units" :key="item.value" :label="item.label" :value="item.value" /></el-select></el-form-item>
<el-form-item label="标准数模单位"><el-select v-model="options.targetScale"><el-option v-for="item in units" :key="item.value" :label="item.label" :value="item.value" /></el-select></el-form-item>
<el-form-item label="表面偏差阈值(mm)"><el-input-number v-model="options.tolerance" :min="0.001" :max="100" :precision="3" /></el-form-item>
</div>
<el-checkbox v-model="options.autoReport">计算后自动生成报告</el-checkbox>
<el-checkbox v-model="options.sourceClean">扫描数据已清理,仅含被测零件</el-checkbox>
<el-checkbox v-model="options.reviewCleanup" :disabled="options.sourceClean">对齐前先人工确认点云清理</el-checkbox>
</el-collapse-item></el-collapse>
</el-form>
<div class="comparison-buttons gap">
<el-button type="primary" :loading="busy" :disabled="!ready || dirty || sourceChanged || !health.available || pendingSameInput" v-hasPermi="['lab:data:upload']" @click="start">{{ busy ? '正在提交文件' : '开始尺寸比对' }}</el-button>
<el-button v-if="job.engine_id" type="primary" plain @click="expanded = true">打开比对工作区</el-button>
<el-button v-if="job.engine_id && ['ARCHIVE_ERROR', 'ARCHIVE_PENDING'].includes(job.status)" :loading="syncing" v-hasPermi="['lab:data:upload']" @click="sync">重试成果归档</el-button>
<span v-if="dirty" class="secondary">请先保存选用的资料版本。</span>
<span v-else-if="sourceChanged" class="secondary">扫描记录已更新,请先关联本次PLY。</span>
</div>
<div v-if="job.id" class="comparison-status">
<div class="comparison-heading"><strong>{{ labels[job.status] || job.status }}</strong><span class="secondary">{{ sameInput ? '对应当前输入' : '历史比对,输入版本已更新' }}</span></div>
<el-progress v-if="['SUBMITTING','PROCESSING'].includes(job.status)" :percentage="50" :indeterminate="true" :show-text="false" />
<p v-if="job.last_error" class="comparison-error">{{ job.last_error }}</p>
<p v-else-if="job.status === 'ARCHIVED'">STL与PDF已成套归档,可在下方核对、查看并确认交付。</p>
<p v-else-if="job.status === 'REVIEW'">打开工作区确认清理、测量项或生成新版报告。</p>
<p v-else-if="job.status === 'UNKNOWN'">提交回执未确认,请核对计算服务记录。系统不会自动重复提交。</p>
<p class="secondary">比对作业 {{ job.id }}<span v-if="job.source_execution_id"> · 来源扫描 {{ job.source_execution_id }}</span><span v-if="job.engine_revision"> · 成果版本 {{ job.engine_revision }}</span></p>
</div>
<el-dialog v-model="expanded" title="尺寸比对工作区" width="min(1600px, 97vw)" top="2vh" destroy-on-close append-to-body :before-close="closeWorkspace">
<InspectionWorkbench v-if="job.engine_id" ref="workspace" :key="job.engine_id" :record-id="job.engine_id" @changed="workspaceChanged" @history="closeWorkspace(() => expanded = false)" />
</el-dialog>
</section>
</template>
<script setup lang="ts">
import * as Api from '@/api/lab/inspection'
import { onBeforeUnmount, watch, ref, reactive, computed, defineAsyncComponent } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import '@/views/lab/inspection/inspection.scss'
import { comparisonPollInterval } from '@/views/lab/scan-task/workbenchPolling.mjs'
const InspectionWorkbench = defineAsyncComponent(() => import('@/views/lab/inspection/InspectionWorkbench.vue'))
const props = defineProps<{ taskId: string; unitId: string; revision: number; ready: boolean; dirty: boolean; sourceChanged: boolean; active: boolean; inputs: { modelId: any; drawingId: any; cloudId: any } }>()
const emit = defineEmits<{ changed: [] }>()
const router = useRouter(), job = ref<any>({}), health = ref<any>({}), catalog = ref<any[]>([]), error = ref(''), loading = ref(false), busy = ref(false), syncing = ref(false), expanded = ref(false), workspace = ref<any>()
const options = reactive({ planTemplateId: 'auto', sourceScale: 1, targetScale: 1, tolerance: 0.2, autoReport: true, sourceClean: false, reviewCleanup: false })
const units = [{value: 1,label:'毫米 mm'},{value:1000,label:'米 m'},{value:0.001,label:'微米 μm'}]
const labels: Record<string,string> = {SUBMITTING:'正在提交资料',UNKNOWN:'提交结果待核对',PROCESSING:'计算处理中',REVIEW:'待人工核对',ARCHIVE_PENDING:'计算完成,正在归档',ARCHIVE_ERROR:'计算完成,成果归档待处理',ARCHIVED:'成果已成套归档',FAILED:'比对失败'}
const sameInput = computed(() => {
// Historical snapshots stored Snowflake IDs as JSON integers; preserve them before parsing.
try { const frozen = JSON.parse((job.value.input_json || '{}').replace(/"id"\s*:\s*(\d{16,})(?=\s*[,}])/g, '"id":"$1"')); return String(frozen.model?.id || '') === String(props.inputs.modelId || '') && String(frozen.drawing?.id || '') === String(props.inputs.drawingId || '') && String(frozen.cloud?.id || '') === String(props.inputs.cloudId || '') }
catch { return false }
})
const pendingSameInput = computed(() => sameInput.value && ['SUBMITTING','UNKNOWN','PROCESSING','REVIEW','ARCHIVE_PENDING','ARCHIVE_ERROR'].includes(job.value.status))
let timer: ReturnType<typeof setTimeout> | undefined, generation = 0, abort: AbortController | undefined
let lastDelivery = ''
let suspended=false
function schedulePoll(token:number){clearTimeout(timer);const delay=comparisonPollInterval(job.value.status);if(delay&&token===generation&&props.active&&!suspended&&!document.hidden)timer=setTimeout(()=>refresh(),delay)}
async function refresh(withHealth = false) {
if (!props.active || !props.unitId || suspended || document.hidden || loading.value) return
const current = generation
loading.value = true
error.value = ''
try {
const [currentJob, state, plans] = await Promise.all([Api.comparison(props.taskId,props.unitId,abort?.signal),withHealth ? Api.health() : Promise.resolve(null),withHealth ? Api.templates() : Promise.resolve(null)])
if (current !== generation) return
job.value = currentJob || {}
if (state) health.value = state
if (plans) catalog.value = plans.templates || []
const delivery = String(job.value.delivery_id || '')
if (delivery && lastDelivery && delivery !== lastDelivery) emit('changed')
if (delivery && !lastDelivery) emit('changed')
lastDelivery = delivery
} catch (e: any) { if (current === generation && !abort?.signal.aborted) error.value = e?.message || '读取比对状态失败' }
finally { if(current === generation) { loading.value = false;schedulePoll(current) } }
}
watch(() => [props.taskId,props.unitId,props.active], async () => {
generation++; abort?.abort(); abort = new AbortController(); clearTimeout(timer); loading.value=false;job.value = {}; lastDelivery = ''
if (props.active && props.unitId && props.unitId !== '0') await refresh(true)
},{immediate:true})
async function start() {
if (busy.value) return
const token = generation
busy.value = true; error.value = ''
try {
const started = await Api.startComparison({taskId:props.taskId,unitId:props.unitId,revision:props.revision,...options})
if (token !== generation) return
job.value = started
schedulePoll(token)
emit('changed')
if (job.value.engine_id) expanded.value = true
} catch(e:any) { if(token === generation) { error.value = e?.message || '提交失败,请刷新状态后核对'; await refresh() } }
finally { busy.value = false }
}
async function sync() {
if (syncing.value || !job.value.engine_id) return
syncing.value = true
try { await Api.sync(job.value.engine_id); await refresh(); emit('changed'); ElMessage.success('已更新归档状态') }
catch(e:any) { error.value = e?.message || '归档尚未完成' }
finally { syncing.value = false }
}
async function workspaceChanged() { await refresh(); emit('changed') }
async function canLeave() { return !expanded.value || !workspace.value || await workspace.value.confirmLeave() }
async function closeWorkspace(done: () => void) { if(await canLeave()) { done(); await workspaceChanged() } }
defineExpose({ canLeave })
function visibilityChanged(){if(document.hidden)clearTimeout(timer);else if(props.active&&comparisonPollInterval(job.value.status))void refresh()}
onMounted(()=>document.addEventListener('visibilitychange',visibilityChanged))
onActivated(()=>{suspended=false;if(props.active)void refresh()})
onDeactivated(()=>{suspended=true;clearTimeout(timer);generation++;abort?.abort();abort=new AbortController();loading.value=false})
onBeforeUnmount(() => { generation++; clearTimeout(timer); abort?.abort();document.removeEventListener('visibilitychange',visibilityChanged) })
</script>
<style scoped>
.comparison-panel { margin: 16px 0 24px; }
.comparison-heading { display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap; }
.comparison-heading h3 { margin: 0 0 6px; }
.comparison-buttons { display:flex;align-items:center;gap:10px;flex-wrap:wrap; }
.comparison-options { margin-top:18px; }
.plan-select { max-width:620px; }
.comparison-fields { display:grid;grid-template-columns:repeat(3,minmax(140px,1fr));gap:16px; }
.comparison-status { padding:14px 0;border-top:1px solid var(--el-border-color-lighter); }
.comparison-status p { margin:10px 0; }
.comparison-error { color:var(--el-color-warning);white-space:pre-wrap; }
.secondary { color:var(--el-text-color-secondary);font-size:12px;overflow-wrap:anywhere; }
.gap { margin-top:16px; }
@media(max-width:700px) { .comparison-fields { grid-template-columns:1fr; } }
</style>

View File

@ -2,9 +2,10 @@
<ContentWrap
v-loading="loading && !data"
class="task-workbench"
:body-style="{ padding: '20px 24px' }"
:body-style="{ padding: '20px 24px', overflow: 'visible' }"
>
<template v-if="data">
<div ref="pageStart" />
<div class="task-heading"
><div
><el-button link @click="router.push('/lab/dimension/tasks')">‹ 任务列表</el-button
@ -52,6 +53,11 @@
title="此历史任务没有逐件扫描记录。原任务、执行和报告仍可从原入口查看;新任务支持逐件资料和交付。"
:closable="false"
/>
<div ref="sectionAnchor" />
<nav ref="sectionNavigation" class="workbench-switcher" role="tablist" aria-label="任务工作台">
<div class="section-buttons"><button v-for="section in sections" :key="section.value" type="button" role="tab" :aria-selected="tab === section.value" :tabindex="tab === section.value ? 0 : -1" :class="{ selected: tab === section.value }" @click="switchSection(section.value)" @keydown.right.prevent="nextSection(1)" @keydown.left.prevent="nextSection(-1)">{{ section.label }}</button></div>
<el-button text size="small" @click="pageStart?.scrollIntoView({ block: 'start', behavior: 'smooth' })">回到顶部</el-button>
</nav>
<el-tabs v-model="tab" class="workbench-nav">
<el-tab-pane v-if="data.task.processType === 'SCAN_ONLY'" label="扫描准备" name="prepare" />
<el-tab-pane v-if="data.task.processType === 'SCAN_ONLY'" label="扫描执行" name="scan" />
@ -170,7 +176,7 @@
</el-tab-pane>
<el-tab-pane label="比对与成果" name="delivery">
<el-alert
title="第三方尺寸比对接口待接入,本平台不会自动发送或伪造比对结果。可先确认输入资料;已在线下完成比对时,由有权限人员成套登记真实STL和PDF。"
title="使用本任务的数模、PDF和扫描PLY进行尺寸比对,生成的STL与报告自动成套归档。扫描执行不依赖比对服务。"
:closable="false"
class="gap"
/>
@ -179,14 +185,14 @@
selectedName(r.key) || '尚未选用'
}}</el-descriptions-item></el-descriptions
>
<ComparisonPanel ref="comparisonPanel" :task-id="taskId" :unit-id="String(data.case.unit_id || '0')" :revision="data.case.revision" :ready="allSelected" :dirty="dirty" :source-changed="data.stage === 'SCAN_CHANGED'" :active="tab === 'delivery'" :inputs="{modelId:data.case.model_id,drawingId:data.case.drawing_id,cloudId:data.case.cloud_id}" @changed="load()" />
<div class="actions"
><el-button
type="primary"
:loading="busy"
:disabled="busy || dirty || !allSelected || data.stage === 'SCAN_CHANGED'"
v-hasPermi="['lab:data:upload']"
@click="prepare"
>确认资料,准备尺寸比对</el-button
>仅固定输入版本(线下比对)</el-button
><el-button
:disabled="
busy ||
@ -201,7 +207,7 @@
<p class="secondary">{{
dirty
? '请先在资料页确认选用版本。'
: '准备操作只固定本次输入版本,不调用设备或第三方接口。'
: '在线比对直接点击“开始尺寸比对”;线下比对可固定输入,再手工成套登记真实成果。'
}}</p>
<el-table :data="data.deliveries"
><el-table-column label="成果版本" min-width="170"
@ -219,7 +225,7 @@
></el-table-column
><el-table-column label="来源" min-width="160"
><template #default="{ row }"
>人工登记外部结果<div class="secondary">{{ row.reason }}</div></template
>{{ String(row.external_no || '').startsWith('CMP-') ? '本机计算服务' : '人工登记外部结果' }}<div class="secondary">{{ row.reason }}</div></template
></el-table-column
><el-table-column label="成果" min-width="190"
><template #default="{ row }"
@ -370,11 +376,13 @@ const ScanWorkbench = defineAsyncComponent(() => import('@/views/lab/scan-task/i
const ModelViewer = defineAsyncComponent(
() => import('@/views/lab/scan-task/ScannerModelViewer.vue')
)
const ComparisonPanel = defineAsyncComponent(() => import('./ComparisonPanel.vue'))
const comparisonPanel = ref<any>()
const route = useRoute(),
router = useRouter(),
message = useMessage(),
taskId = computed(() => String(route.params.id))
const data = ref<any>(),
const data = shallowRef<any>(),
cloudNotice = ref(''),
unitId = ref(''),
tab = ref('prepare'),
@ -388,6 +396,11 @@ const scanWorkbench = ref<any>(),
scanView = ref('prepare'),
scanSummary = ref<any>()
const isScanSection = computed(() => ['prepare', 'scan'].includes(tab.value))
const sectionNavigation=ref<HTMLElement>()
const sectionAnchor=ref<HTMLElement>(),pageStart=ref<HTMLElement>()
const sections=computed(()=>[...(data.value?.task.processType==='SCAN_ONLY'?[{value:'prepare',label:'扫描准备'},{value:'scan',label:'扫描执行'}]:[]),{value:'materials',label:'比对资料'},{value:'delivery',label:'比对与成果'},{value:'trace',label:'操作追溯'}])
async function switchSection(value:string){if(tab.value===value)return;tab.value=value;await nextTick();sectionAnchor.value?.scrollIntoView({block:'start',behavior:'instant'})}
async function nextSection(offset:number){const list=sections.value,index=list.findIndex(section=>section.value===tab.value);await switchSection(list[(index+offset+list.length)%list.length].value);sectionNavigation.value?.querySelector<HTMLButtonElement>('[aria-selected="true"]')?.focus({preventScroll:true})}
function updateScanSummary(value: any) {
scanSummary.value = value
}
@ -485,6 +498,7 @@ async function load(preserve = false) {
}
}
async function mayDiscard() {
if (comparisonPanel.value && !(await comparisonPanel.value.canLeave())) return false
if (!dirty.value) return true
return ElMessageBox.confirm(
'尚有未确认的版本选择,是否放弃这些选择并继续?',
@ -581,7 +595,7 @@ async function prepare() {
revision: data.value.case.revision
})
await load()
message.success('输入版本已固定,等待尺寸比对接口接入或登记真实外部成果')
message.success('输入版本已固定,可开始尺寸比对或登记线下真实成果')
})
}
const resultVisible = ref(false),
@ -746,10 +760,17 @@ onBeforeUnmount(() => {
display: none;
}
.workbench-nav {
margin-top: 18px;
margin-top: 0;
}
.task-workbench { overflow: visible; }
.workbench-switcher { position:sticky;top:0;z-index:8;display:flex;align-items:center;justify-content:space-between;gap:12px;background:var(--el-bg-color);border-bottom:1px solid var(--el-border-color-lighter);margin-top:18px;margin-bottom:16px;padding:4px 0; }
.section-buttons { display:flex;gap:20px;overflow-x:auto;min-width:0; }
.section-buttons button { flex-shrink:0;border:0;border-bottom:2px solid transparent;background:none;color:var(--el-text-color-regular);padding:12px 2px;font-size:14px;cursor:pointer; }
.section-buttons button.selected { color:var(--el-color-primary);border-bottom-color:var(--el-color-primary); }
.section-buttons button:focus-visible { outline:2px solid var(--el-color-primary);outline-offset:-2px; }
.workbench-switcher>.el-button { flex-shrink:0; }
.workbench-nav :deep(.el-tabs__header) {
margin-bottom: 16px;
display:none;
}
.workbench-nav :deep(.el-tabs__item) {
height: 46px;

View File

@ -1,7 +1,7 @@
<template>
<el-alert
class="mb-12px"
title="此页保存旧报告流程中的报告记录。尺寸比对返回的PDF在“最终成果”中查看;尚未接入尺寸比对时,不会自动生成报告。"
title="此页保存旧报告流程中的报告记录。尺寸比对生成的PDF请在任务的“比对与成果”或“最终成果”中查看。"
type="info"
:closable="false"
/>

View File

@ -0,0 +1,568 @@
<template>
<section class="inspect-panel clean-panel">
<div class="clean-heading"
><div
><h3>点云处理工作区</h3
><p>在扫描原始坐标系中调整规则。先预览保留 / 排除点,再确认并重新对齐。</p></div
><el-button :loading="loading" :disabled="busy" @click="load">重新读取</el-button></div
>
<el-alert v-if="error" :title="error" type="error" show-icon @close="error = ''" />
<el-alert
v-if="blocked"
title="检测计划有未保存修改,请先保存计划,再应用点云处理。"
type="warning"
:closable="false"
/>
<div class="clean-layout">
<aside class="clean-controls">
<el-collapse v-model="sections"
><el-collapse-item title="自动生成清理方案" name="auto"
><el-form label-position="top" size="small" :disabled="busy || loading"
><el-form-item label="主体选择方式"
><el-select v-model="auto.selection_mode"
><el-option value="cad" label="匹配设计 CAD 主体" /><el-option
value="largest"
label="按点数保留连通主体" /></el-select></el-form-item
><el-form-item label="处理强度"
><el-radio-group v-model="auto.strength"
><el-radio-button value="gentle">温和</el-radio-button
><el-radio-button value="normal">标准</el-radio-button
><el-radio-button value="aggressive">强力</el-radio-button></el-radio-group
></el-form-item
><el-form-item label="去噪系数(越小越严格)"
><el-input-number
v-model="auto.denoise_std"
:min="1"
:max="10"
:step="0.5"
:precision="1"
placeholder="使用强度预设"
clearable /></el-form-item
><el-form-item label="连通距离 / mm"
><el-input-number
v-model="auto.connect_radius_mm"
:min="0.01"
:max="100"
:precision="2"
placeholder="留空自动估计"
clearable /></el-form-item
><el-form-item label="保留主体数量"
><el-input-number
v-model="auto.keep_components"
:min="1"
:max="20"
:disabled="auto.selection_mode === 'cad'" /></el-form-item
><div class="inspect-sub"
>CAD 模式按几何匹配选择主体;按点数模式可保留多个分离零件区域。</div
><el-button
type="primary"
plain
class="w-full mt-12px"
:loading="busy"
@click="suggest"
>生成方案并预览</el-button
></el-form
></el-collapse-item
></el-collapse
>
<div class="clean-rule-heading"
><strong>处理规则 · {{ rules.length }} / 50</strong
><el-button link :disabled="busy" @click="restore">恢复原始点云</el-button></div
>
<div class="clean-add"
><el-select v-model="newType" size="small" :disabled="busy"
><el-option
v-for="item in ruleTypes"
:key="item.type"
:value="item.type"
:label="item.label" /></el-select
><el-button size="small" :disabled="busy || rules.length >= 50" @click="addRule"
>添加规则</el-button
></div
>
<div class="clean-rule-list"
><article v-for="(r, i) in rules" :key="i" class="clean-rule"
><div class="clean-rule-title"
><strong>{{ i + 1 }}. {{ ruleName(r.type) }}</strong
><el-button link :disabled="busy || i === 0" @click="move(i, -1)">↑</el-button
><el-button link :disabled="busy || i === rules.length - 1" @click="move(i, 1)"
>↓</el-button
><el-button link type="danger" :disabled="busy" @click="rules.splice(i, 1)"
>移除</el-button
></div
>
<el-form label-position="top" size="small" :disabled="busy">
<template v-if="r.type === 'isolated'"
><el-form-item label="统计邻域点数"
><el-input-number v-model="r.neighbors" :min="3" :max="100" /></el-form-item
><el-form-item label="标准差倍数"
><el-input-number
v-model="r.std"
:min="1"
:max="10"
:step="0.5"
:precision="1" /></el-form-item
></template>
<template v-else-if="r.type === 'radius_outlier'"
><el-form-item label="邻域半径 / mm"
><el-input-number
v-model="r.radius"
:min="0.01"
:max="100"
:precision="2" /></el-form-item
><el-form-item label="半径内最少相邻点"
><el-input-number v-model="r.min_neighbors" :min="1" :max="100" /></el-form-item
></template>
<template v-else-if="r.type === 'largest'"
><el-form-item label="连通距离 / mm"
><el-input-number
v-model="r.radius"
:min="0.01"
:max="100"
:precision="2" /></el-form-item
><el-form-item label="保留主体数量"
><el-input-number v-model="r.keep" :min="1" :max="20" /></el-form-item
></template>
<template v-else-if="r.type === 'box'"
><el-radio-group v-model="r.mode"
><el-radio value="keep">保留框内</el-radio
><el-radio value="remove">删除框内</el-radio></el-radio-group
><div class="clean-axis" v-for="(axis, k) in ['X', 'Y', 'Z']" :key="axis"
><span>{{ axis }}</span
><el-input-number v-model="r.min[k]" :controls="false" :precision="3" /><span
>至</span
><el-input-number v-model="r.max[k]" :controls="false" :precision="3" /></div
></template>
<template v-else-if="r.type === 'polygon'"
><el-form-item label="投影平面"
><el-select v-model="r.plane"
><el-option
v-for="p in ['xy', 'xz', 'yz']"
:key="p"
:value="p"
:label="p.toUpperCase()" /></el-select></el-form-item
><el-radio-group v-model="r.mode"
><el-radio value="keep">保留内部</el-radio
><el-radio value="remove">删除内部</el-radio></el-radio-group
><el-form-item label="顶点坐标 / mm(JSON 数组)"
><el-input
v-model="r.verticesText"
type="textarea"
:rows="4"
placeholder="[[0,0],[10,0],[10,10],[0,10]]" /></el-form-item
></template>
<div v-else class="inspect-sub"
>CAD 主体编号:{{
r.component_ids?.join(', ')
}}。修改前置规则后,请重新生成自动方案。</div
>
</el-form> </article
><el-empty
v-if="!rules.length"
description="未设置排除规则,保留原始点云"
:image-size="60"
/></div>
</aside>
<div class="clean-preview">
<div class="clean-metrics"
><div
><small>原始点数</small><strong>{{ data.total?.toLocaleString() || '—' }}</strong></div
><div
><small>保留点数</small><strong>{{ data.kept?.toLocaleString() || '—' }}</strong></div
><div
><small>排除点数</small
><strong>{{
data.total != null ? (data.total - data.kept).toLocaleString() : '—'
}}</strong></div
><div
><small>保留比例</small
><strong>{{
data.total ? ((data.kept / data.total) * 100).toFixed(1) + '%' : '—'
}}</strong></div
></div
>
<el-alert
v-if="!validPreview"
title="规则已有修改,请重新预览后确认。"
type="warning"
:closable="false"
/>
<InspectionViewer
:points="keptPoints"
:excluded="removedPoints"
:total="data.kept || 0"
frame="source_mm"
cleanup
:loading="loading || busy"
:pick="readPoint ? '点击扫描点读取原始坐标' : ''"
@point="coordinate"
@cancel="readPoint = false"
/>
<div class="clean-preview-tools"
><el-checkbox v-model="showRemoved">显示排除点</el-checkbox
><el-button size="small" @click="readPoint = !readPoint">{{
readPoint ? '取消读取坐标' : '读取扫描点坐标'
}}</el-button
><code v-if="lastPoint">{{ lastPoint.map((v) => v.toFixed(3)).join(', ') }} mm</code></div
>
<el-table
v-if="data.actions?.audit?.length"
:data="data.actions.audit"
size="small"
max-height="230"
><el-table-column label="步骤" width="65"
><template #default="s">{{ s.$index + 1 }}</template></el-table-column
><el-table-column label="处理操作" min-width="130"
><template #default="s">{{ ruleName(s.row.action.type) }}</template></el-table-column
><el-table-column prop="before" label="处理前" /><el-table-column
prop="removed"
label="本步排除" /><el-table-column prop="retained" label="保留"
/></el-table>
<div class="inspect-sub mt-12px"
>预览按照完整原始点云计算保留结果,窗口最多显示 24,000
个采样点。规则只排除原始点,正式对齐使用确认后保留的点云。</div
>
</div>
</div>
<div class="clean-footer"
><span class="inspect-sub"
>{{ validPreview ? '当前预览可应用' : '修改规则后需重新预览' }} ·
应用后重新配准、测量并按任务设置生成报告</span
><el-button :loading="busy" :disabled="loading" @click="preview">预览清理结果</el-button
><el-button
v-hasPermi="['lab:result:confirm']"
type="primary"
:loading="busy"
:disabled="!validPreview || loading || blocked"
@click="apply"
>确认点云并重新计算</el-button
></div
>
</section>
</template>
<script setup lang="ts">
import * as Api from '@/api/lab/inspection'
import { ElMessageBox } from 'element-plus'
import InspectionViewer from './InspectionViewer.vue'
import type { Vec3 } from './geometry'
const props = defineProps<{ recordId: string; blocked?: boolean }>(),
emit = defineEmits<{ applied: [state: any]; dirty: [dirty: boolean] }>()
const data = shallowRef<any>({}),
rules = ref<any[]>([]),
newType = ref('isolated'),
loading = ref(false),
busy = ref(false),
error = ref(''),
sections = ref(['auto']),
signature = ref(''),
showRemoved = ref(true),
readPoint = ref(false),
lastPoint = ref<Vec3>()
const auto = reactive<any>({
selection_mode: 'cad',
strength: 'normal',
denoise_std: undefined,
connect_radius_mm: undefined,
keep_components: 1
})
const saved = ref('[]'),
recipeDirty = computed(() => JSON.stringify(rules.value) !== saved.value)
watch(recipeDirty, (value) => emit('dirty', value))
const ruleTypes = [
{ type: 'isolated', label: '统计离群点去噪' },
{ type: 'radius_outlier', label: '半径离群点去噪' },
{ type: 'largest', label: '连通主体选择' },
{ type: 'box', label: '空间包围框裁剪' },
{ type: 'polygon', label: '投影多边形裁剪' }
]
const validPreview = computed(
() => signature.value === JSON.stringify(rules.value) && data.value.total != null
),
keptPoints = computed(
() => data.value.points?.filter((_: any, i: number) => data.value.retained[i]) || []
),
removedPoints = computed(() =>
showRemoved.value
? data.value.points?.filter((_: any, i: number) => !data.value.retained[i]) || []
: []
)
const ruleName = (type: string) =>
ruleTypes.find((r) => r.type === type)?.label ||
(type === 'cad_components' ? 'CAD 主体匹配' : type)
const clone = (value: any) => JSON.parse(JSON.stringify(value))
function editable(actions: any[]) {
return actions.map((r) => ({
...r,
...(r.type === 'isolated' ? { neighbors: r.neighbors || 20 } : {}),
...(r.type === 'polygon' ? { verticesText: JSON.stringify(r.vertices) } : {})
}))
}
async function load() {
if (recipeDirty.value) {
try {
await ElMessageBox.confirm('重新读取会放弃未应用的点云处理规则。', '重新读取')
} catch {
return
}
}
loading.value = true
error.value = ''
try {
data.value = await Api.get(props.recordId, 'preview')
rules.value = editable(data.value.actions?.actions || [])
signature.value = JSON.stringify(rules.value)
saved.value = signature.value
} catch (e: any) {
error.value = e?.message || '读取原始点云失败'
} finally {
loading.value = false
}
}
async function run(fn: () => Promise<void>) {
if (busy.value) return
busy.value = true
error.value = ''
try {
await fn()
} catch (e: any) {
error.value = e?.message || String(e)
} finally {
busy.value = false
}
}
function actions() {
return rules.value.map((rule) => {
const r = clone(rule)
if (r.type === 'polygon') {
try {
r.vertices = JSON.parse(r.verticesText)
} catch {
throw new Error('投影多边形顶点需为有效 JSON 数组')
}
delete r.verticesText
}
return r
})
}
function addRule() {
const b = data.value.bounds || [
[0, 0, 0],
[10, 10, 10]
],
type = newType.value
rules.value.push(
type === 'isolated'
? { type, std: 3, neighbors: 20 }
: type === 'radius_outlier'
? { type, radius: 1, min_neighbors: 5 }
: type === 'largest'
? { type, radius: 2, keep: 1 }
: type === 'box'
? { type, mode: 'keep', min: [...b[0]], max: [...b[1]] }
: {
type,
plane: 'xy',
mode: 'keep',
verticesText: JSON.stringify([
[b[0][0], b[0][1]],
[b[1][0], b[0][1]],
[b[1][0], b[1][1]],
[b[0][0], b[1][1]]
])
}
)
}
function move(i: number, by: number) {
;[rules.value[i], rules.value[i + by]] = [rules.value[i + by], rules.value[i]]
}
function restore() {
rules.value = []
readPoint.value = false
}
const preview = () =>
run(async () => {
const result = await Api.post(props.recordId, 'cleanup', {
revision: data.value.revision ?? data.value.state?.revision,
actions: actions(),
dry_run: true
})
data.value = result
signature.value = JSON.stringify(rules.value)
})
const suggest = () =>
run(async () => {
const result = await Api.post(props.recordId, 'cleanup/auto', {
...auto,
base_actions: [],
revision: data.value.revision ?? data.value.state?.revision,
dry_run: true
})
rules.value = editable(result.actions.actions)
data.value = result
signature.value = JSON.stringify(rules.value)
})
const apply = () =>
run(async () => {
if (props.blocked) throw new Error('检测计划有未保存修改,请先保存计划')
if (!validPreview.value) throw new Error('请先预览当前规则')
const result = await Api.post(props.recordId, 'cleanup', {
revision: data.value.revision ?? data.value.state?.revision,
actions: actions()
})
saved.value = JSON.stringify(rules.value)
emit('applied', result)
})
function coordinate(p: Vec3) {
lastPoint.value = p
readPoint.value = false
}
onMounted(load)
</script>
<style scoped>
.clean-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 20px;
margin-bottom: 20px;
}
.clean-heading h3 {
font-size: 17px;
margin: 0 0 8px;
}
.clean-heading p {
font-size: 12px;
color: var(--el-text-color-secondary);
margin: 0;
line-height: 1.7;
}
.clean-layout {
display: grid;
grid-template-columns: 310px minmax(0, 1fr);
gap: 24px;
}
.clean-controls {
border: 1px solid var(--el-border-color-lighter);
border-radius: 10px;
padding: 14px;
min-width: 0;
}
.clean-controls .el-input-number,
.clean-controls .el-select {
width: 100%;
}
.clean-controls :deep(.el-form-item) {
margin-bottom: 13px;
}
.clean-rule-heading,
.clean-rule-title,
.clean-add {
display: flex;
align-items: center;
gap: 8px;
}
.clean-rule-heading {
justify-content: space-between;
margin: 20px 0 12px;
font-size: 13px;
}
.clean-add {
margin-bottom: 12px;
}
.clean-add .el-select {
min-width: 0;
}
.clean-rule-list {
max-height: 620px;
overflow: auto;
}
.clean-rule {
border: 1px solid var(--el-border-color-lighter);
border-radius: 8px;
padding: 12px;
margin-bottom: 12px;
background: var(--el-fill-color-lighter);
}
.clean-rule-title {
font-size: 12px;
margin-bottom: 13px;
}
.clean-rule-title strong {
margin-right: auto;
}
.clean-rule-title .el-button + .el-button {
margin-left: 0;
}
.clean-axis {
display: flex;
align-items: center;
gap: 5px;
margin: 10px 0;
font-size: 11px;
}
.clean-axis .el-input-number {
min-width: 0;
width: 100px;
}
.clean-preview {
min-width: 0;
}
.clean-metrics {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 12px;
margin-bottom: 18px;
}
.clean-metrics > div {
padding: 15px 12px;
border-radius: 8px;
background: var(--el-fill-color-lighter);
}
.clean-metrics small {
font-size: 11px;
color: var(--el-text-color-secondary);
display: block;
margin-bottom: 8px;
}
.clean-metrics strong {
font-size: 18px;
}
.clean-preview-tools {
display: flex;
align-items: center;
gap: 14px;
flex-wrap: wrap;
margin: 14px 0;
font-size: 12px;
}
.clean-footer {
border-top: 1px solid var(--el-border-color-lighter);
padding-top: 18px;
margin-top: 20px;
display: flex;
align-items: center;
gap: 12px;
flex-wrap: wrap;
}
.clean-footer > span {
margin-right: auto;
}
.clean-panel .el-alert {
margin-bottom: 15px;
}
@media (max-width: 1050px) {
.clean-layout {
grid-template-columns: minmax(0, 1fr);
}
.clean-controls {
max-height: 550px;
overflow: auto;
}
.clean-rule-list {
max-height: 360px;
}
.clean-metrics {
grid-template-columns: repeat(2, 1fr);
}
}
</style>

View File

@ -0,0 +1,628 @@
<template>
<section class="model-viewer">
<div class="viewer-toolbar">
<el-radio-group v-model="layer" size="small" aria-label="模型显示图层">
<el-radio-button value="overlay">{{ cleanup ? '清理预览' : '叠加对比' }}</el-radio-button>
<el-radio-button value="scan">{{ cleanup ? '仅保留点' : '扫描点云' }}</el-radio-button>
<el-radio-button v-if="!cleanup" value="cad" :disabled="!hasCad">设计数模</el-radio-button>
</el-radio-group>
<el-checkbox v-if="hasThermal && !cleanup" v-model="heat">报告偏差热力图</el-checkbox>
<div class="viewer-camera">
<el-button size="small" @click="fit()">适应窗口</el-button>
<el-button size="small" @click="view('front')">正视</el-button>
<el-button size="small" @click="view('side')">侧视</el-button>
<el-button size="small" @click="view('top')">俯视</el-button>
<el-button size="small" :disabled="!markers.length" @click="fit(true)"
>定位选中项</el-button
>
</div>
</div>
<div ref="host" class="viewer-stage" :class="{ 'is-picking': !!pick }" v-loading="loading">
<canvas
ref="canvas"
tabindex="0"
aria-label="三维模型交互视图"
@pointerdown="down"
@pointermove="move"
@pointerup="up"
@pointercancel="drag = null"
@pointerleave="leave"
@wheel.prevent="wheel"
@dblclick="fit()"
@contextmenu.prevent
/>
<div class="viewer-legend"
><span v-if="layer !== 'cad'"
><i class="scan-dot" :style="hasThermal && heat ? { background: '#4daf4a' } : {}" />{{
hasThermal && heat ? '偏差点云' : '扫描点云'
}}</span
><span v-if="layer !== 'scan' && hasCad"><i class="cad-dot" />设计数模</span
><span v-if="cleanup && layer === 'overlay' && excluded.length"
><i style="background: #fa6b7b" />排除点</span
><span v-if="markers.length"><i class="bind-dot" />当前绑定</span></div
>
<div class="viewer-frame">{{
frame === 'target_mm' ? '设计坐标系 · mm' : '扫描原始坐标系 · mm'
}}</div>
<div v-if="!loading && !points.length && !hasCad" class="viewer-empty"
><Icon icon="ep:box" :size="38" /><strong>{{ emptyMessage || '三维数据尚未就绪' }}</strong
><span>处理完成后会自动加载,可点击重新加载重试。</span></div
>
<div v-if="pick" class="viewer-pick-banner"
><strong>{{ pick }}</strong
><el-button size="small" @click="$emit('cancel')">取消(Esc)</el-button></div
>
<div v-if="hover && pick" class="viewer-coordinate"
>{{ hover.p.map((v) => v.toFixed(3)).join(' , ') }} mm
<span v-if="hasThermal && hover.index != null">
· 偏差 {{ thermal.values[hover.index]?.toFixed(3) }} mm</span
></div
>
<div v-if="hasThermal && heat && layer !== 'cad'" class="viewer-colorbar"
><strong>法向投影偏差 / mm</strong
><div class="viewer-colorbar-scale"
><div class="viewer-ramp" :style="{ background: gradient }" /><div class="viewer-ticks"
><span>≥ {{ thermal.max_mm.toFixed(3) }}</span
><span>{{ (thermal.max_mm / 2).toFixed(3) }}</span
><span>0.000</span><span>{{ (thermal.min_mm / 2).toFixed(3) }}</span
><span>≤ {{ thermal.min_mm.toFixed(3) }}</span></div
></div
><small>与报告使用同一色标</small></div
>
<div class="viewer-axis">X <span>Y</span> <em>Z</em></div>
</div>
<footer class="viewer-footer"
><span>左键拖动旋转 · 右键 / Shift 拖动平移 · 滚轮缩放 · 双击复位</span
><span
>{{ points.length.toLocaleString() }} 个显示点 / {{ total.toLocaleString() }} 个保留点</span
></footer
>
</section>
</template>
<script setup lang="ts">
import { nearestPoint, xyz, type Vec3, type ScreenPoint } from './geometry'
const props = withDefaults(
defineProps<{
points: Vec3[]
reference?: Vec3[]
mesh?: { vertices: Vec3[]; triangles: number[][] }
frame?: string
total?: number
loading?: boolean
emptyMessage?: string
hint?: any
seeds?: Vec3[]
pick?: string
cleanup?: boolean
excluded?: Vec3[]
thermal?: any
}>(),
{
reference: () => [],
frame: 'target_mm',
total: 0,
pick: '',
seeds: () => [],
excluded: () => [],
cleanup: false
}
)
const emit = defineEmits<{ point: [point: Vec3]; cancel: [] }>()
const host = ref<HTMLDivElement>(),
canvas = ref<HTMLCanvasElement>(),
layer = ref('overlay'),
heat = ref(true),
hover = shallowRef<ScreenPoint>(),
drag = shallowRef<any>(null)
const hasCad = computed(() => !!props.mesh?.triangles?.length || !!props.reference.length)
const hasThermal = computed(
() =>
props.thermal?.values?.length === props.points.length &&
props.points.length > 0 &&
props.thermal?.colors?.length === props.points.length
)
const gradient = computed(
() =>
`linear-gradient(to top, ${(props.thermal?.stops || []).map(([at, color]: any[]) => `${color} ${at * 100}%`).join(',')})`
)
const markers = computed(() =>
[
props.hint?.approx_center_mm || props.hint?.point_a || props.hint?.point_a_mm,
props.hint?.point_b || props.hint?.point_b_mm,
...props.seeds
].filter(xyz)
)
let center: Vec3 = [0, 0, 0],
span = 1,
ax = -0.45,
ay = 0.6,
scale = 1,
pan = [0, 0],
hits: ScreenPoint[] = [],
width = 800,
height = 510,
raf = 0,
observer: ResizeObserver | undefined
const requestDraw = () => {
cancelAnimationFrame(raf)
raf = requestAnimationFrame(draw)
}
function fit(local = false) {
const selected = local ? markers.value : []
const data = selected.length
? selected
: [...props.points, ...props.excluded, ...(props.mesh?.vertices || props.reference)]
if (!data.length) return
const low = [Infinity, Infinity, Infinity],
high = [-Infinity, -Infinity, -Infinity]
for (const p of data)
for (let k = 0; k < 3; k++) {
low[k] = Math.min(low[k], p[k])
high[k] = Math.max(high[k], p[k])
}
center = low.map((v, i) => (v + high[i]) / 2) as Vec3
span = Math.max(
...high.map((v, i) => v - low[i]),
selected.length ? Math.max(4, Number(props.hint?.radius_mm || 0) * 3) : 1
)
if (selected.length) span *= 1.8
pan = [0, 0]
scale = 1
requestDraw()
}
function project(p: Vec3): ScreenPoint {
const [x, y, z] = p.map((v, i) => v - center[i]),
u = x * Math.cos(ay) + z * Math.sin(ay),
v = -x * Math.sin(ay) + z * Math.cos(ay),
f = ((Math.min(width, height) * 0.77) / span) * scale
return {
x: width / 2 + pan[0] + u * f,
y: height / 2 + pan[1] - (y * Math.cos(ax) - v * Math.sin(ax)) * f,
z: y * Math.sin(ax) + v * Math.cos(ax),
p
}
}
function draw() {
const el = canvas.value
if (!el || !host.value) return
width = host.value.clientWidth
height = host.value.clientHeight
if (!width || !height) return
const dpr = Math.min(window.devicePixelRatio || 1, 2)
el.width = Math.round(width * dpr)
el.height = Math.round(height * dpr)
const ctx = el.getContext('2d')
if (!ctx) return
ctx.scale(dpr, dpr)
ctx.clearRect(0, 0, width, height)
ctx.strokeStyle = 'rgba(135,157,183,.10)'
ctx.lineWidth = 1
for (let x = (width / 2) % 40; x < width; x += 40) {
ctx.beginPath()
ctx.moveTo(x, 0)
ctx.lineTo(x, height)
ctx.stroke()
}
for (let y = (height / 2) % 40; y < height; y += 40) {
ctx.beginPath()
ctx.moveTo(0, y)
ctx.lineTo(width, y)
ctx.stroke()
}
hits = []
if (props.cleanup && layer.value === 'overlay') {
ctx.fillStyle = '#fa6b7b88'
for (const p of props.excluded) {
const q = project(p)
ctx.fillRect(q.x, q.y, 1.5, 1.5)
}
}
if (layer.value !== 'scan') {
if (props.mesh?.triangles?.length) {
const vs = props.mesh.vertices.map(project)
const faces = props.mesh.triangles
.map((t) => t.map((i) => vs[i]))
.sort((a, b) => a[0].z + a[1].z + a[2].z - (b[0].z + b[1].z + b[2].z))
for (const t of faces) {
if (
t.every((p) => p.x < 0) ||
t.every((p) => p.x > width) ||
t.every((p) => p.y < 0) ||
t.every((p) => p.y > height)
)
continue
const nz = Math.abs(
(t[1].x - t[0].x) * (t[2].y - t[0].y) - (t[1].y - t[0].y) * (t[2].x - t[0].x)
)
const shade = Math.round(135 + Math.min(1, nz / 100) * 35)
ctx.fillStyle =
layer.value === 'cad'
? `rgba(${shade},${shade + 15},${shade + 30},0.96)`
: 'rgba(88,109,129,0.18)'
ctx.beginPath()
ctx.moveTo(t[0].x, t[0].y)
ctx.lineTo(t[1].x, t[1].y)
ctx.lineTo(t[2].x, t[2].y)
ctx.closePath()
ctx.fill()
}
} else {
ctx.fillStyle = '#9aacc2'
for (const p of props.reference) {
const q = project(p)
ctx.fillRect(q.x, q.y, 1.8, 1.8)
}
}
}
if (layer.value !== 'cad') {
const sorted = props.points
.map((p, index) => ({ ...project(p), index }))
.sort((a, b) => a.z - b.z)
ctx.fillStyle = layer.value === 'overlay' ? '#32c4cf' : '#4abfd5'
for (const p of sorted) {
if (p.x < 0 || p.x > width || p.y < 0 || p.y > height) continue
if (hasThermal.value && heat.value) ctx.fillStyle = props.thermal.colors[p.index]
ctx.fillRect(p.x - 1, p.y - 1, pickSize(), pickSize())
hits.push(p)
}
}
const mark = (p: Vec3, label: string) => {
const q = project(p)
ctx.beginPath()
ctx.arc(q.x, q.y, 6, 0, Math.PI * 2)
ctx.fillStyle = '#ffb24d'
ctx.fill()
ctx.strokeStyle = '#172c43'
ctx.lineWidth = 2
ctx.stroke()
ctx.font = '600 12px sans-serif'
ctx.fillStyle = '#fff'
ctx.fillText(label, q.x + 10, q.y - 8)
}
const h = props.hint || {},
a = h.approx_center_mm || h.point_a || h.point_a_mm,
b = h.point_b || h.point_b_mm
if (xyz(a)) mark(a, xyz(b) ? 'A' : '中心')
if (xyz(b)) {
mark(b, 'B')
if (xyz(a)) {
const p = project(a),
q = project(b)
ctx.strokeStyle = '#ffb24d'
ctx.setLineDash([5, 4])
ctx.beginPath()
ctx.moveTo(p.x, p.y)
ctx.lineTo(q.x, q.y)
ctx.stroke()
ctx.setLineDash([])
}
}
props.seeds.forEach((p, i) => mark(p, `P${i + 1}`))
const normal = h.normal || h.approx_normal,
radius = h.radius_mm || h.approx_radius_mm
if (xyz(a) && xyz(normal) && radius > 0) {
const length = Math.hypot(...normal),
n = normal.map((v) => v / length),
ref = Math.abs(n[0]) < 0.8 ? [1, 0, 0] : [0, 1, 0]
let u = [
n[1] * ref[2] - n[2] * ref[1],
n[2] * ref[0] - n[0] * ref[2],
n[0] * ref[1] - n[1] * ref[0]
],
l = Math.hypot(...u)
u = u.map((v) => v / l)
const v = [n[1] * u[2] - n[2] * u[1], n[2] * u[0] - n[0] * u[2], n[0] * u[1] - n[1] * u[0]]
ctx.beginPath()
for (let i = 0; i <= 96; i++) {
const t = (i * Math.PI) / 48,
p = project(a.map((x, k) => x + radius * (u[k] * Math.cos(t) + v[k] * Math.sin(t))) as Vec3)
if (i === 0) ctx.moveTo(p.x, p.y)
else ctx.lineTo(p.x, p.y)
}
ctx.strokeStyle = '#ffb24d'
ctx.lineWidth = 2
ctx.stroke()
}
if (hover.value && props.pick) {
ctx.strokeStyle = '#fff'
ctx.lineWidth = 2
ctx.beginPath()
ctx.arc(hover.value.x, hover.value.y, 9, 0, Math.PI * 2)
ctx.stroke()
}
}
function pickSize() {
return props.pick ? 2.5 : 1.8
}
function position(e: PointerEvent | WheelEvent) {
const r = canvas.value!.getBoundingClientRect()
return [e.clientX - r.left, e.clientY - r.top]
}
function down(e: PointerEvent) {
const [x, y] = position(e)
canvas.value?.focus()
canvas.value?.setPointerCapture(e.pointerId)
drag.value = { x, y, startX: x, startY: y, moved: false, pan: e.button === 2 || e.shiftKey }
}
function move(e: PointerEvent) {
const [x, y] = position(e),
d = drag.value
if (d) {
const dx = x - d.x,
dy = y - d.y
if (Math.hypot(x - d.startX, y - d.startY) > 4) d.moved = true
if (d.moved) {
if (d.pan) {
pan[0] += dx
pan[1] += dy
} else {
ay += dx * 0.008
ax += dy * 0.008
}
hover.value = undefined
requestDraw()
}
d.x = x
d.y = y
} else if (props.pick) {
hover.value = nearestPoint(hits, x, y)
requestDraw()
}
}
function up(e: PointerEvent) {
const d = drag.value
drag.value = null
if (!d || d.moved || !props.pick || e.button !== 0) return
const [x, y] = position(e),
nearest = nearestPoint(hits, x, y)
if (nearest) emit('point', nearest.p)
}
function leave() {
if (!drag.value) {
hover.value = undefined
requestDraw()
}
}
function wheel(e: WheelEvent) {
const old = scale
scale = Math.min(100, Math.max(0.05, scale * Math.exp(-e.deltaY * 0.001)))
const [x, y] = position(e)
pan = [
x - width / 2 - ((x - width / 2 - pan[0]) * scale) / old,
y - height / 2 - ((y - height / 2 - pan[1]) * scale) / old
]
requestDraw()
}
function view(kind: string) {
ax = kind === 'top' ? Math.PI / 2 : 0
ay = kind === 'side' ? Math.PI / 2 : 0
requestDraw()
}
watch(
() => [props.points, props.reference, props.mesh],
() => nextTick(() => fit())
)
watch(() => [props.hint, props.seeds], requestDraw, { deep: true })
watch([layer, heat], requestDraw)
watch(() => props.thermal, requestDraw)
watch(
() => props.pick,
() => {
if (props.pick) {
if (layer.value === 'cad') layer.value = 'scan'
canvas.value?.focus()
}
hover.value = undefined
requestDraw()
}
)
onMounted(() => {
observer = new ResizeObserver(requestDraw)
if (host.value) observer.observe(host.value)
fit()
})
onBeforeUnmount(() => {
observer?.disconnect()
cancelAnimationFrame(raf)
})
defineExpose({ fit })
</script>
<style scoped>
.model-viewer {
border: 1px solid var(--el-border-color-lighter);
border-radius: 10px;
overflow: hidden;
min-width: 0;
}
.viewer-toolbar {
padding: 12px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
flex-wrap: wrap;
background: var(--el-bg-color);
}
.viewer-camera {
display: flex;
gap: 6px;
flex-wrap: wrap;
}
.viewer-camera .el-button + .el-button {
margin-left: 0;
}
.viewer-stage {
position: relative;
background: radial-gradient(ellipse at center, #111d2b, #050b12);
height: 510px;
min-height: 340px;
}
.viewer-colorbar {
position: absolute;
right: 20px;
top: 62px;
pointer-events: none;
padding: 13px 12px;
border-radius: 8px;
background: #05101cdb;
border: 1px solid #a8baca24;
color: #dbe9f7;
font-size: 11px;
}
.viewer-colorbar strong {
display: block;
font-size: 11px;
font-weight: 500;
margin-bottom: 12px;
}
.viewer-colorbar-scale {
display: flex;
gap: 9px;
justify-content: center;
}
.viewer-ramp {
width: 17px;
height: 200px;
border: 1px solid #c9dbed50;
border-radius: 3px;
}
.viewer-ticks {
display: flex;
flex-direction: column;
justify-content: space-between;
font: 11px monospace;
}
.viewer-colorbar small {
display: block;
color: #94acc5;
font-size: 10px;
margin-top: 11px;
}
.viewer-stage canvas {
width: 100%;
height: 100%;
display: block;
touch-action: none;
cursor: grab;
outline: none;
}
.viewer-stage canvas:focus-visible {
outline: 2px solid #65c9ff;
outline-offset: -2px;
}
.viewer-stage.is-picking canvas {
cursor: crosshair;
}
.viewer-legend {
position: absolute;
top: 17px;
left: 18px;
display: flex;
gap: 18px;
color: #cbd9e6;
font-size: 12px;
pointer-events: none;
}
.viewer-legend span {
display: flex;
gap: 6px;
align-items: center;
}
.viewer-legend i {
height: 7px;
width: 7px;
border-radius: 50%;
}
.scan-dot {
background: #32c4cf;
}
.cad-dot {
background: #a8b9cd;
}
.bind-dot {
background: #ffb24d;
}
.viewer-frame {
position: absolute;
right: 18px;
top: 17px;
font-size: 11px;
color: #a7bbcf;
pointer-events: none;
}
.viewer-axis {
position: absolute;
bottom: 16px;
right: 18px;
color: #ef7e86;
word-spacing: 8px;
font: 600 12px monospace;
pointer-events: none;
}
.viewer-axis span {
color: #8bd5ac;
}
.viewer-axis em {
color: #70b7ff;
font-style: normal;
}
.viewer-empty {
position: absolute;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
gap: 14px;
color: #afc2d6;
pointer-events: none;
}
.viewer-empty span {
font-size: 12px;
}
.viewer-pick-banner {
position: absolute;
top: 48px;
left: 50%;
transform: translateX(-50%);
background: #183f56ed;
border: 1px solid #39758e;
border-radius: 8px;
padding: 9px 14px;
display: flex;
align-items: center;
gap: 15px;
color: #fff;
white-space: nowrap;
font-size: 12px;
}
.viewer-coordinate {
position: absolute;
bottom: 18px;
left: 18px;
color: #e3f5ff;
font: 12px monospace;
pointer-events: none;
}
.viewer-footer {
display: flex;
justify-content: space-between;
gap: 14px;
flex-wrap: wrap;
padding: 11px 14px;
font-size: 11px;
color: var(--el-text-color-secondary);
background: var(--el-fill-color-lighter);
}
@media (max-width: 900px) {
.viewer-stage {
height: 440px;
}
.viewer-frame {
top: 40px;
}
.viewer-pick-banner {
top: 66px;
}
}
</style>

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,25 @@
export const statusText = (s: string) =>
({
processing: '计算中',
created: '待处理',
done: '计算完成',
blocked: '诊断结果',
error: '处理失败',
review: '待确认点云'
})[s] ||
s ||
'—'
export const dateText = (value: any) =>
value == null
? '—'
: typeof value === 'number'
? new Date(value).toLocaleString()
: String(value).replace('T', ' ').slice(0, 19)
export const inputName = (row: any, role: string) => {
try {
return JSON.parse(row.inputsJson || '{}')[role]?.name || '—'
} catch {
return '—'
}
}
export const fileSize = (n: number) => (n ? `${(n / 1024 / 1024).toFixed(2)} MB` : '—')

View File

@ -0,0 +1,65 @@
export type Vec3 = [number, number, number]
export const xyz = (v: any): v is Vec3 =>
Array.isArray(v) && v.length === 3 && v.every((n) => typeof n === 'number' && Number.isFinite(n))
export const clone = <T>(v: T): T => JSON.parse(JSON.stringify(v))
const sub = (a: Vec3, b: Vec3): Vec3 => a.map((n, i) => n - b[i]) as Vec3
const cross = (a: Vec3, b: Vec3): Vec3 => [
a[1] * b[2] - a[2] * b[1],
a[2] * b[0] - a[0] * b[2],
a[0] * b[1] - a[1] * b[0]
]
const dot = (a: Vec3, b: Vec3) => a.reduce((s, n, i) => s + n * b[i], 0)
export const distance = (a: Vec3, b: Vec3) => Math.hypot(...sub(a, b))
export function circleThrough(points: Vec3[]) {
if (points.length !== 3 || !points.every(xyz)) throw new Error('请选择三个有效圆周点')
const [a, b, c] = points,
u = sub(b, a),
v = sub(c, a),
w = cross(u, v),
w2 = dot(w, w)
if (
distance(a, b) < 0.01 ||
distance(a, c) < 0.01 ||
distance(b, c) < 0.01 ||
w2 < dot(u, u) * dot(v, v) * 1e-6
)
throw new Error('三个点太近或接近共线,请换三个分散的圆周点')
const p = cross(v, w),
q = cross(w, u)
const center = a.map((n, i) => n + (dot(u, u) * p[i] + dot(v, v) * q[i]) / (2 * w2)) as Vec3
return { center, normal: w.map((n) => n / Math.sqrt(w2)) as Vec3, radius: distance(a, center) }
}
export function hintPoints(h: any = {}): Vec3[] {
return [
h.approx_center_mm || h.approx_center,
h.point_a || h.point_a_mm,
h.point_b || h.point_b_mm
].filter(xyz)
}
export function applyHint(row: any, hint: any) {
row.geometry_hint = clone(hint)
row.geometry_hint_json = JSON.stringify(hint)
const a = hint.approx_center_mm || hint.point_a || [null, null, null],
b = hint.point_b || [null, null, null]
;[row.approx_x, row.approx_y, row.approx_z] = a
;[row.point_bx, row.point_by, row.point_bz] = b
for (const key of ['measured_mm', 'trial_measured_mm', 'inspection_result', 'fit_confidence'])
row[key] = null
row.measurement_status = '待重测'
row.measurement_reason = '绑定已修改,请保存并重新测量'
}
export type ScreenPoint = { x: number; y: number; z: number; p: Vec3; index?: number }
export function nearestPoint(hits: ScreenPoint[], x: number, y: number, radius = 16) {
let nearest: ScreenPoint | undefined,
best = radius
for (const h of hits) {
const d = Math.hypot(h.x - x, h.y - y)
if (d > radius) continue
if (!nearest || d < best - 1.5 || (Math.abs(d - best) <= 1.5 && h.z > nearest.z)) {
nearest = h
best = d
}
}
return nearest
}

View File

@ -0,0 +1,281 @@
.inspect-page {
--inspect-accent: var(--el-color-primary);
max-width: 1540px;
margin: 0 auto;
padding: 8px 4px 28px;
color: var(--el-text-color-primary);
}
.inspect-header {
padding: 8px 0 24px;
}
.inspect-kicker {
font-size: 11px;
letter-spacing: 1.7px;
font-weight: 700;
color: var(--el-color-primary);
margin-bottom: 10px;
}
.inspect-title-line {
display: flex;
align-items: center;
justify-content: space-between;
gap: 20px;
}
.inspect-title-line h1 {
font-size: 26px;
line-height: 1.3;
font-weight: 650;
margin: 0 0 10px;
letter-spacing: -0.5px;
}
.inspect-title-line p {
margin: 0;
color: var(--el-text-color-secondary);
font-size: 14px;
}
.inspect-panel {
background: var(--el-bg-color);
border: 1px solid var(--el-border-color-lighter);
border-radius: 12px;
padding: 24px;
margin-bottom: 20px;
}
.inspect-panel-head {
display: flex;
align-items: center;
gap: 12px;
margin-bottom: 24px;
}
.inspect-section-no {
height: 30px;
width: 30px;
border-radius: 8px;
background: var(--el-color-primary-light-9);
color: var(--el-color-primary);
font-weight: 700;
display: grid;
place-items: center;
font-size: 12px;
}
.inspect-panel-head h2 {
font-size: 16px;
font-weight: 600;
margin: 0 0 4px;
}
.inspect-sub {
font-size: 12px;
color: var(--el-text-color-secondary);
line-height: 1.6;
}
.inspect-layout {
display: grid;
grid-template-columns: minmax(0, 1fr) 290px;
gap: 24px;
align-items: start;
}
.inspect-files {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 14px;
}
.inspect-file {
border: 1px dashed var(--el-border-color);
border-radius: 10px;
padding: 18px 12px;
min-height: 162px;
text-align: center;
transition:
border-color 0.2s,
background 0.2s;
}
.inspect-file:hover {
border-color: var(--el-color-primary);
background: var(--el-fill-color-lighter);
}
.inspect-file.is-ready {
border-style: solid;
border-color: var(--el-color-primary-light-7);
background: var(--el-color-primary-light-9);
}
.inspect-file .el-upload {
width: 100%;
display: block;
}
.inspect-file .file-icon {
display: inline-flex;
padding: 10px;
border-radius: 10px;
background: var(--el-fill-color-light);
color: var(--el-color-primary);
margin-bottom: 12px;
}
.inspect-file strong {
display: block;
font-size: 14px;
font-weight: 600;
margin-bottom: 9px;
}
.inspect-file .filename {
font-size: 12px;
color: var(--el-text-color-regular);
word-break: break-all;
min-height: 32px;
line-height: 1.5;
}
.inspect-file .file-hint {
font-size: 11px;
letter-spacing: 0.4px;
color: var(--el-text-color-secondary);
margin-top: 10px;
}
.inspect-aside {
position: sticky;
top: 14px;
}
.inspect-aside h3 {
font-size: 15px;
margin: 0 0 20px;
}
.inspect-process {
display: flex;
gap: 12px;
margin-bottom: 24px;
}
.inspect-process .step-num {
flex: none;
width: 25px;
height: 25px;
border-radius: 50%;
display: grid;
place-items: center;
font-size: 11px;
font-weight: 700;
background: var(--el-color-primary-light-9);
color: var(--el-color-primary);
}
.inspect-process strong {
font-size: 13px;
display: block;
margin: 2px 0 5px;
}
.inspect-note {
padding: 14px;
background: var(--el-fill-color-lighter);
border-radius: 8px;
font-size: 12px;
line-height: 1.8;
color: var(--el-text-color-secondary);
}
.inspect-submit {
display: flex;
justify-content: space-between;
align-items: center;
gap: 16px;
padding: 18px 24px;
background: var(--el-bg-color);
border: 1px solid var(--el-border-color-lighter);
border-radius: 12px;
}
.inspect-form .el-form-item {
margin-bottom: 22px;
}
.inspect-form .el-select,
.inspect-form .el-input-number {
width: 100%;
}
.inspect-search {
display: flex;
gap: 12px;
flex-wrap: wrap;
align-items: center;
}
.inspect-table-title {
display: flex;
align-items: center;
gap: 10px;
}
.inspect-table-icon {
height: 36px;
width: 36px;
display: grid;
place-items: center;
border-radius: 9px;
background: var(--el-color-primary-light-9);
color: var(--el-color-primary);
flex: none;
}
.inspect-record-title {
font-weight: 500;
line-height: 1.5;
}
.inspect-code {
font-size: 11px;
color: var(--el-text-color-placeholder);
font-family: ui-monospace, monospace;
margin-top: 4px;
}
.inspect-page .el-table {
--el-table-header-bg-color: var(--el-fill-color-lighter);
--el-table-row-hover-bg-color: var(--el-color-primary-light-9);
}
.inspect-page .el-table th.el-table__cell {
height: 46px;
color: var(--el-text-color-secondary);
font-weight: 500;
}
.inspect-page .el-table td.el-table__cell {
padding: 15px 0;
}
.inspect-empty {
padding: 30px;
}
.inspect-badge {
border: 1px solid var(--el-border-color-light);
border-radius: 20px;
padding: 6px 12px;
color: var(--el-text-color-secondary);
font-size: 12px;
white-space: nowrap;
}
.inspect-report-frame {
width: 100%;
height: 76vh;
border: 0;
background: #f3f5f8;
}
.inspect-page .el-alert {
margin-bottom: 18px;
}
.inspect-page .el-pagination {
margin-top: 20px;
justify-content: flex-end;
}
.inspect-page .el-table .el-button + .el-button {
margin-left: 10px;
}
@media (max-width: 1100px) {
.inspect-layout {
grid-template-columns: minmax(0, 1fr);
}
.inspect-aside {
display: none;
}
}
@media (max-width: 750px) {
.inspect-files {
grid-template-columns: 1fr;
}
.inspect-title-line {
align-items: flex-start;
}
.inspect-title-line h1 {
font-size: 22px;
}
.inspect-panel {
padding: 18px;
}
.inspect-submit {
align-items: flex-start;
flex-direction: column;
}
}

View File

@ -0,0 +1,527 @@
<template>
<main class="inspect-page">
<header class="inspect-header"
><div class="inspect-kicker">检测计划模板</div
><div class="inspect-title-line"
><div
><h1>检测计划模板</h1
><p>维护模板名称、检测项与公差,统一新建检测和计划调整的检测依据。</p></div
><el-button @click="$router.back()">返回任务</el-button><el-button type="primary" v-hasPermi="['lab:result:confirm']" @click="edit()"
><Icon icon="ep:plus" class="mr-6px" />新建模板</el-button
></div
></header
>
<el-alert v-if="error" :title="error" type="error" show-icon @close="error = ''" />
<section class="inspect-panel inspect-search"
><el-input
v-model="query.name"
placeholder="搜索模板名称"
clearable
style="width: 280px"
@keyup.enter="search"
><template #prefix><Icon icon="ep:search" /></template></el-input
><el-select v-model="query.enabled" clearable placeholder="全部状态" style="width: 150px"
><el-option label="已启用" value="true" /><el-option
label="已停用"
value="false" /></el-select
><el-button type="primary" plain @click="search">查询</el-button
><el-button @click="reset">重置</el-button
><span class="inspect-sub ml-auto">共 {{ total }} 个模板</span></section
>
<section class="inspect-panel"
><el-table :data="list" v-loading="loading"
><el-table-column label="模板名称" min-width="270"
><template #default="s"
><div class="inspect-table-title"
><span class="inspect-table-icon"><Icon icon="ep:document-copy" :size="20" /></span
><div
><strong>{{ s.row.name }}</strong
><div class="inspect-sub">{{ s.row.description || '—' }}</div></div
></div
></template
></el-table-column
><el-table-column
prop="partNumbers"
label="自动匹配零件号"
min-width="200"
show-overflow-tooltip
/><el-table-column prop="rowCount" label="检测项" width="90" /><el-table-column
label="版本"
width="85"
><template #default="s">V{{ s.row.revision }}</template></el-table-column
><el-table-column label="状态" width="100"
><template #default="s"
><el-tag :type="s.row.enabled ? 'success' : 'info'">{{
s.row.enabled ? '已启用' : '已停用'
}}</el-tag></template
></el-table-column
><el-table-column label="更新时间" width="175"
><template #default="s">{{ dateText(s.row.updateTime) }}</template></el-table-column
><el-table-column label="操作" fixed="right" width="240"
><template #default="s"
><el-button link type="primary" @click="edit(s.row)">{{
writable ? '编辑字段' : '查看'
}}</el-button
><el-button link v-hasPermi="['lab:result:confirm']" @click="edit(s.row, true)"
>复制</el-button
><el-button link @click="exportTemplate(s.row)">导出</el-button
><el-button
link
type="danger"
v-hasPermi="['lab:result:confirm']"
@click="remove(s.row)"
>删除</el-button
></template
></el-table-column
><template #empty
><el-empty description="暂无检测计划模板"
><el-button type="primary" v-hasPermi="['lab:result:confirm']" @click="edit()"
>新建模板</el-button
></el-empty
></template
></el-table
><Pagination
:total="total"
v-model:page="query.pageNo"
v-model:limit="query.pageSize"
@pagination="load"
/></section>
<el-drawer
v-model="drawer"
:title="model.id ? '维护检测计划模板' : '新建检测计划模板'"
size="min(96vw, 1320px)"
:before-close="close"
destroy-on-close
>
<div v-loading="editing"
><el-alert
v-if="editError"
:title="editError"
type="error"
show-icon
:closable="false"
/><el-alert
title="保存后会更新模板版本。已经建立的检测任务继续使用当时的计划;需要更新时可在任务中重新载入模板。"
type="info"
:closable="false"
/>
<el-form
ref="form"
:model="model"
label-position="top"
:disabled="saving || !writable"
class="template-form"
><el-row :gutter="20"
><el-col :span="14"
><el-form-item
label="模板名称"
prop="name"
:rules="[{ required: true, message: '请输入模板名称', trigger: 'blur' }]"
><el-input
v-model="model.name"
maxlength="100"
show-word-limit
placeholder="如:管类零件尺寸检测" /></el-form-item></el-col
><el-col :span="6"
><el-form-item label="状态"
><el-switch
v-model="model.enabled"
active-text="启用"
inactive-text="停用" /></el-form-item></el-col
><el-col :span="4"
><el-form-item label="当前版本"
><el-tag>{{
model.id ? 'V' + model.revision : '首次保存 V1'
}}</el-tag></el-form-item
></el-col
></el-row
><el-form-item label="自动匹配零件号"
><el-input
v-model="model.partNumbers"
maxlength="500"
placeholder="可填写多个完整零件号,以逗号分隔;留空时由操作员手动选择模板" /></el-form-item
><el-form-item label="模板说明"
><el-input
v-model="model.description"
maxlength="1000"
type="textarea"
:rows="2"
placeholder="适用零件、图纸版本或检测要求" /></el-form-item
></el-form>
<div class="template-items-heading"
><div
><h3
>检测项与字段内容 <el-tag size="small">{{ model.rows.length }} 项</el-tag></h3
><p>按行维护名称、几何类型、控制项、名义值、公差与备注。尺寸单位为 mm。</p></div
><div class="template-tools" v-if="writable"
><el-button @click="jsonInput?.click()" :disabled="saving">导入 JSON</el-button
><el-button
type="primary"
plain
@click="addRow"
:disabled="saving || model.rows.length >= 500"
><Icon icon="ep:plus" class="mr-4px" />添加检测项</el-button
><input ref="jsonInput" type="file" accept=".json" hidden @change="importJson" /></div
></div>
<el-table :data="model.rows" border max-height="500" class="template-fields"
><el-table-column type="index" label="序号" width="60" /><el-table-column
label="检测项名称"
min-width="180"
><template #default="s"
><el-input
v-model="s.row.name"
maxlength="120"
:disabled="!writable || saving"
placeholder="如:中心孔直径" /></template></el-table-column
><el-table-column label="几何类型" width="150"
><template #default="s"
><el-select
v-model="s.row.type"
:disabled="!writable || saving"
@change="changeType(s.row)"
><el-option
v-for="o in types"
:key="o.value"
:value="o.value"
:label="o.label" /></el-select></template></el-table-column
><el-table-column label="控制项" width="125"
><template #default="s"
><el-select
v-model="s.row.control"
filterable
allow-create
default-first-option
:disabled="!writable || saving"
><el-option
v-for="v in ['直径', '长度', '孔距', '面距', '点间距', '平面度', '圆柱度']"
:key="v"
:value="v"
:label="v" /></el-select></template></el-table-column
><el-table-column label="名义 / mm" width="155"
><template #default="s"
><el-input-number
v-model="s.row.nominal_mm"
:min="0"
:max="10000000"
:precision="4"
:controls="false"
:disabled="!writable || saving"
style="width: 100%" /></template></el-table-column
><el-table-column label="公差" width="135"
><template #default="s"
><el-input
v-model="s.row.tol_text"
:disabled="!writable || saving"
placeholder="±0.1 / +0.1/0" /></template></el-table-column
><el-table-column label="备注" min-width="180"
><template #default="s"
><el-input
v-model="s.row.notes"
:disabled="!writable || saving"
type="textarea"
:autosize="{ minRows: 1, maxRows: 3 }"
maxlength="1000"
placeholder="测量位置、图纸标注等" /></template></el-table-column
><el-table-column v-if="writable" label="操作" width="160" fixed="right"
><template #default="s"
><el-button link :disabled="saving || s.$index === 0" @click="moveRow(s.$index, -1)"
>上移</el-button
><el-button
link
:disabled="saving || s.$index === model.rows.length - 1"
@click="moveRow(s.$index, 1)"
>下移</el-button
><el-button
link
type="danger"
:disabled="saving"
@click="model.rows.splice(s.$index, 1)"
>移除</el-button
></template
></el-table-column
><template #empty><el-empty description="点击添加检测项,开始定义模板字段" /></template
></el-table>
<p class="inspect-sub mt-12px"
>公差可留空;支持
±0.1、+0.025/0、+1/-0.5。未设置公差的检测项保留测量值,显示“未设公差”。</p
></div
>
<template #footer
><div class="template-footer"
><span class="inspect-sub">{{ dirty ? '有修改待保存' : '模板内容已同步' }}</span
><el-button :disabled="saving" @click="close(() => (drawer = false))">关闭</el-button
><el-button
v-if="writable"
type="primary"
:loading="saving"
:disabled="editing"
@click="save"
>保存模板</el-button
></div
></template
>
</el-drawer>
</main>
</template>
<script setup lang="ts">
import * as Api from '@/api/lab/inspection'
import { ElMessage, ElMessageBox } from 'element-plus'
import { dateText } from './display'
import { checkPermi } from '@/utils/permission'
import './inspection.scss'
defineOptions({ name: 'LabInspectionTemplates' })
const writable = computed(() => checkPermi(['lab:result:confirm'])),
list = ref<any[]>([]),
total = ref(0),
loading = ref(false),
error = ref(''),
drawer = ref(false),
editing = ref(false),
saving = ref(false),
editError = ref(''),
form = ref(),
jsonInput = ref<HTMLInputElement>(),
baseline = ref('')
const model = ref<any>({ name: '', description: '', partNumbers: '', enabled: true, rows: [] }),
dirty = computed(() => JSON.stringify(model.value) !== baseline.value),
query = reactive({ name: '', enabled: '', pageNo: 1, pageSize: 20 })
const types = [
{ value: 'circle', label: '圆 / 孔 / 管径' },
{ value: 'distance', label: '长度 / 距离' },
{ value: 'hole_distance', label: '孔心距' },
{ value: 'plane_distance', label: '平行面距' },
{ value: 'point_distance', label: '扫描点间距' },
{ value: 'plane', label: '平面' },
{ value: 'cylinder', label: '圆柱' }
]
let sequence = 0
async function load() {
const owner = ++sequence
loading.value = true
try {
const data = await Api.templatePage({ ...query })
if (owner === sequence) {
list.value = data.list
total.value = data.total
error.value = ''
}
} catch (e: any) {
if (owner === sequence) error.value = e?.message || '模板查询失败'
} finally {
if (owner === sequence) loading.value = false
}
}
function search() {
query.pageNo = 1
void load()
}
function reset() {
query.name = ''
query.enabled = ''
search()
}
async function edit(row?: any, copy = false) {
editing.value = true
editError.value = ''
try {
const data = row
? await Api.templateDetail(row.id)
: { name: '', description: '', partNumbers: '', enabled: true, rows: [] }
if (copy) {
delete data.id
delete data.revision
delete data.builtinKey
data.name = (data.name + ' · 副本').slice(0, 100)
data.partNumbers = ''
data.enabled = false
}
model.value = JSON.parse(JSON.stringify(data))
baseline.value = JSON.stringify(model.value)
drawer.value = true
} catch (e: any) {
error.value = e?.message || '读取模板失败'
} finally {
editing.value = false
}
}
function addRow() {
model.value.rows.push({
table: 'feature',
type: 'circle',
name: '检测项 ' + (model.value.rows.length + 1),
control: '直径',
nominal_mm: null,
tol_text: '',
notes: ''
})
}
function changeType(row: any) {
const feature = ['circle', 'plane', 'cylinder'].includes(row.type)
row.table = feature ? 'feature' : 'gauge'
row.control = {
circle: '直径',
plane: '平面度',
cylinder: '圆柱度',
distance: '长度',
hole_distance: '孔距',
plane_distance: '面距',
point_distance: '点间距'
}[row.type]
}
function moveRow(index: number, offset: number) {
const rows = model.value.rows
;[rows[index], rows[index + offset]] = [rows[index + offset], rows[index]]
}
async function close(done: () => void) {
if (saving.value) return
if (dirty.value) {
try {
await ElMessageBox.confirm('当前模板有未保存修改,是否放弃修改并关闭?', '关闭模板', {
confirmButtonText: '放弃修改',
cancelButtonText: '继续编辑'
})
} catch {
return
}
}
done()
}
async function save() {
if (saving.value) return
editError.value = ''
try {
await form.value.validate()
if (!model.value.rows.length) throw new Error('请至少添加一个检测项')
for (const [i, row] of model.value.rows.entries()) {
if (!row.name?.trim() || row.nominal_mm == null || !Number.isFinite(Number(row.nominal_mm)))
throw new Error(`第 ${i + 1} 项:请填写名称和有效名义值`)
}
saving.value = true
model.value = await Api.saveTemplate(model.value)
baseline.value = JSON.stringify(model.value)
ElMessage.success('模板已保存,版本 V' + model.value.revision)
await load()
} catch (e: any) {
editError.value = e?.message || '请检查模板名称与检测项字段'
} finally {
saving.value = false
}
}
async function remove(row: any) {
try {
await ElMessageBox.confirm(
`删除模板「${row.name}」?已有检测任务和报告继续保留。`,
'删除模板',
{ type: 'warning' }
)
await Api.removeTemplate(row.id, row.revision)
ElMessage.success('模板已删除')
await load()
} catch (e: any) {
if (e !== 'cancel' && e !== 'close') error.value = e?.message || '删除失败'
}
}
async function exportTemplate(row: any) {
try {
const data = await Api.templateDetail(row.id)
Api.saveBlob(
new Blob(
[
JSON.stringify(
{
schema_version: 1,
unit: 'mm',
name: data.name,
description: data.description,
partNumbers: data.partNumbers,
rows: data.rows
},
null,
2
)
],
{ type: 'application/json;charset=utf-8' }
),
data.name + '-V' + data.revision + '.json'
)
} catch (e: any) {
error.value = e?.message || '导出失败'
}
}
async function importJson(e: Event) {
const input = e.target as HTMLInputElement,
file = input.files?.[0]
if (!file) return
try {
if (file.size > 2 * 1024 * 1024) throw new Error('模板 JSON 不得超过 2 MB')
const data = JSON.parse(await file.text())
const rows = Array.isArray(data) ? data : data.rows
if (!Array.isArray(rows) || !rows.length || rows.length > 500)
throw new Error('JSON 需包含 1–500 个检测项 rows')
if (dirty.value) await ElMessageBox.confirm('导入会替换当前字段内容,是否继续?', '导入模板')
model.value.rows = rows
if (!model.value.name && data.name) model.value.name = data.name
editError.value = ''
} catch (e: any) {
if (e !== 'cancel' && e !== 'close') editError.value = e?.message || 'JSON 模板无效'
} finally {
input.value = ''
}
}
onMounted(load)
</script>
<style scoped>
.template-form {
margin-top: 22px;
}
.template-items-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
margin: 12px 0 18px;
}
.template-items-heading h3 {
font-size: 15px;
margin: 0 0 8px;
}
.template-items-heading p {
margin: 0;
color: var(--el-text-color-secondary);
font-size: 12px;
}
.template-tools {
display: flex;
gap: 10px;
flex-wrap: wrap;
}
.template-tools .el-button + .el-button {
margin-left: 0;
}
.template-footer {
display: flex;
align-items: center;
gap: 10px;
}
.template-footer > span {
margin-right: auto;
}
.template-footer .el-button + .el-button {
margin-left: 0;
}
.template-fields :deep(.el-table__cell) {
padding: 10px 0;
}
.template-fields :deep(.el-button + .el-button) {
margin-left: 6px;
}
.inspect-table-title strong {
font-weight: 500;
}
@media (max-width: 800px) {
.template-items-heading {
align-items: flex-start;
flex-direction: column;
}
}
</style>

View File

@ -1,16 +1,20 @@
<template>
<Dialog v-model="visible" title="夹具框架点" width="760px">
<Dialog v-model="visible" title="夹具框架点" width="760px" :scroll="true" max-height="65vh">
<div class="heading">{{ fixture?.fixtureName }} <el-tag :type="data.current?.id ? 'success' : 'warning'">{{ data.current?.id ? '可复用' : '未配置' }}</el-tag></div>
<p class="hint">导入已有文件或现场扫描录入,后续任务选择此夹具即可复用。更新成功后使用新版本,失败保留原数据。</p>
<el-alert v-if="data.current?.id" type="success" :closable="false" :title="'当前版本:' + data.current.id.slice(0,8) + ' · ' + formatDate(data.current.updatedAt)" />
<div v-if="currentFileNames.length" class="current-files">当前文件:{{ currentFileNames.join('、') }}</div>
<section v-if="frameworkFiles.length" ref="filesPanel" class="framework-files">
<div class="files-heading"><strong>{{ selectedFramework?.id === data.current?.id ? '当前框架点文件' : '历史框架点文件' }}</strong><el-button v-if="selectedFramework?.id !== data.current?.id" link type="primary" @click="selectedVersion=''">返回当前版本</el-button><el-button plain size="small" @click="copyFiles(frameworkFiles)">复制框架点信息</el-button></div>
<div v-for="file in frameworkFiles" :key="file.fileId" class="framework-file"><span class="file-name" :title="file.name">{{ file.name }}</span><span class="hint">{{ sizeText(file.bytes) }}</span><el-button link type="primary" v-hasPermi="['lab:data:download']" :loading="downloading === file.fileId" :disabled="!!downloading" @click="downloadFile(file)">下载</el-button><el-button link type="primary" @click="copyFiles([file])">复制信息</el-button></div>
<p class="hint">复制内容包含文件地址、名称、大小和校验值,可用于工作流参数;下载读取平台已保存文件。</p>
</section>
<el-alert v-if="latest?.message" type="warning" :closable="false" :title="latest.message" />
<template v-if="running">
<el-alert :title="stopping ? '终止中,请等待设备释放' : '正在录入框架点,请在扫描工作站完成采集,系统将自动保存结果'" type="info" :closable="false" />
<el-button type="danger" plain :loading="stopping" :disabled="stopping" @click="stop">终止录入</el-button>
<el-button v-if="canManage" type="danger" plain :loading="stopping" :disabled="stopping" @click="stop">终止录入</el-button>
<ScannerLiveView v-if="visible && previewRecording && previewEndedFor !== String(previewRecording.id)" :key="previewRecording.id" :execution-id="previewRecording.id" execution-no="夹具框架点录入" status="RUNNING" scope="fixture" :active="visible && running" @ended="id => previewEndedFor = id" />
</template>
<template v-else>
<template v-else-if="canManage">
<el-radio-group v-model="entryMode" :disabled="busy || uploading || loading" class="entry-mode" @change="modeChanged">
<el-radio-button value="local">导入本地文件</el-radio-button><el-radio-button value="capture">现场扫描录入</el-radio-button>
</el-radio-group>
@ -28,11 +32,12 @@
</template>
</template>
<el-table v-if="data.history?.length" :data="data.history" size="small" class="history">
<el-table-column label="更新时间" prop="createdAt" :formatter="dateFormatter" min-width="170" />
<el-table-column label="来源" width="100"><template #default="{row}">{{ row.instanceId ? '扫描录入' : row.status === 'READY' ? '本地导入' : '扫描录入' }}</template></el-table-column>
<el-table-column label="状态" width="110"><template #default="{row}">{{ ({READY:'已保存',RUNNING:'录入中',FAILED:'未成功'})[row.status] || row.status }}</template></el-table-column>
<el-table-column label="版本" width="100"><template #default="{row}">{{row.id.slice(0,8)}}</template></el-table-column>
<el-table-column label="说明" prop="message" min-width="150" />
<el-table-column label="更新时间" prop="createdAt" :formatter="dateFormatter" min-width="160" />
<el-table-column label="来源" width="85"><template #default="{row}">{{ row.instanceId ? '扫描录入' : row.status === 'READY' ? '本地导入' : '扫描录入' }}</template></el-table-column>
<el-table-column label="状态" width="85"><template #default="{row}">{{ ({READY:'已保存',RUNNING:'录入中',FAILED:'未成功'})[row.status] || row.status }}</template></el-table-column>
<el-table-column label="版本" width="90"><template #default="{row}">{{row.id.slice(0,8)}}</template></el-table-column>
<el-table-column label="说明" prop="message" min-width="120" />
<el-table-column label="文件" width="100"><template #default="{row}"><el-button v-if="row.status === 'READY'" link type="primary" @click="showFiles(row.id)">下载 / 复制</el-button></template></el-table-column>
</el-table>
</Dialog>
</template>
@ -45,6 +50,9 @@ import FrameworkLocalUpload from '@/cmvr/common/components/FrameworkLocalUpload.
import { localFrameworkFiles } from '@/cmvr/common/utils/frameworkLocalFiles.mjs'
import { activeFixtureRecording } from '@/views/lab/scan-task/scannerPreviewTarget.mjs'
import { getResourceRoles } from '@/cmvr/common/utils/flowResources'
import { useClipboard } from '@vueuse/core'
import { checkPermi } from '@/utils/permission'
import download from '@/utils/download'
const message=useMessage()
const emit=defineEmits(['updated'])
const visible=ref(false),busy=ref(false),stopping=ref(false),confirmed=ref(false)
@ -52,8 +60,16 @@ const entryMode=ref('local'),localFiles=ref<any[]>([]),uploading=ref(false),impo
const definitionError=ref(''),definitionLoading=ref(false)
const fixture=ref<any>(),data=ref<any>({}),definition=ref<any>({}),assignments=ref<any[]>([]),roles=ref<any[]>([])
const resourceEditor=ref<any>()
const selectedVersion=ref(''),downloading=ref(''),filesPanel=ref<HTMLElement>()
const canManage=computed(()=>checkPermi(['lab:fixture:update']))
const {copy}=useClipboard({legacy:true})
const selectedFramework=computed(()=>selectedVersion.value?data.value.history?.find((row:any)=>row.id===selectedVersion.value)||data.value.current:data.value.current)
const frameworkFiles=computed(()=>{try{return localFrameworkFiles(selectedFramework.value?.urlsJson||'[]')}catch{return []}})
const sizeText=(size:number)=>size<1024?`${size} B`:size<1048576?`${(size/1024).toFixed(1)} KB`:`${(size/1048576).toFixed(1)} MiB`
const copyFiles=async(files:any[])=>{try{await copy(JSON.stringify(files,null,2));message.success('框架点信息已复制')}catch{message.warning('复制失败,请允许浏览器访问剪贴板后重试')}}
const downloadFile=async(file:any)=>{if(downloading.value)return;downloading.value=file.fileId;try{download.file(await Api.downloadFramework(fixture.value.id,selectedFramework.value.id,file.fileId),file.name)}finally{downloading.value=''}}
const showFiles=async(id:string)=>{selectedVersion.value=id;await nextTick();filesPanel.value?.scrollIntoView({block:'nearest',behavior:'smooth'})}
const latest=computed(()=>data.value.history?.[0])
const currentFileNames=computed(()=>{try{return JSON.parse(data.value.current?.urlsJson||'[]').map((file:any)=>file.name).filter(Boolean)}catch{return []}})
const running=computed(()=>data.value.history?.some((r:any)=>r.status==='RUNNING'))
const previewRecording=computed(()=>activeFixtureRecording(data.value.history))
const previewEndedFor=ref('')
@ -61,7 +77,7 @@ let timer:ReturnType<typeof setTimeout>|undefined
const generation=ref(0)
const refresh=async(sync=false)=>{
const g=generation.value,id=fixture.value.id
const result=sync ? await Api.syncFramework(id) : await Api.getFramework(id)
const result=sync && canManage.value ? await Api.syncFramework(id) : await Api.getFramework(id)
if(g!==generation.value||!visible.value)return
const previous=data.value.current?.id
data.value=result
@ -71,10 +87,10 @@ const refresh=async(sync=false)=>{
if(running.value)timer=setTimeout(()=>refresh(true).catch(()=>{ message.warning('录入状态刷新失败,请关闭后重新打开查看') }),2000)
}
const open=async(row:any)=>{
generation.value++;fixture.value=row;data.value={};visible.value=true;confirmed.value=false;assignments.value=[];stopping.value=false
generation.value++;fixture.value=row;data.value={};selectedVersion.value='';visible.value=true;confirmed.value=false;assignments.value=[];stopping.value=false
entryMode.value='local';localFiles.value=[];uploading.value=false;importConfirmed.value=false;definition.value={};definitionError.value='';definitionLoading.value=false
const g=generation.value;loading.value=true
try{await refresh(true)}catch(e){if(g===generation.value)visible.value=false;throw e}finally{if(g===generation.value)loading.value=false}
try{await refresh()}catch(e){if(g===generation.value)visible.value=false;throw e}finally{if(g===generation.value)loading.value=false}
}
const modeChanged=async()=>{
if(entryMode.value!=='capture'||definition.value.caseName||definitionLoading.value)return
@ -122,5 +138,5 @@ defineExpose({open})
<style scoped>
.heading{display:flex;align-items:center;gap:12px;font-weight:600;font-size:16px}.hint{color:var(--el-text-color-secondary);line-height:1.7}.actions{display:flex;justify-content:flex-end;gap:8px;margin-top:20px}.history{margin-top:24px}.el-alert{margin:12px 0}
.entry-mode{margin:16px 0}.confirmation{margin-top:16px}
.current-files{font-size:12px;color:var(--el-text-color-regular);line-height:1.8;overflow-wrap:anywhere}
.framework-files{border:1px solid var(--el-border-color-lighter);border-radius:6px;padding:12px;margin:12px 0}.files-heading,.framework-file{display:flex;align-items:center;gap:10px;flex-wrap:wrap}.files-heading{justify-content:space-between;margin-bottom:8px}.framework-file{border-top:1px solid var(--el-border-color-lighter);padding:8px 0}.file-name{flex:1;min-width:120px;overflow-wrap:anywhere}.framework-files .hint{font-size:12px;margin:4px 0}
</style>

View File

@ -25,6 +25,8 @@
<el-table-column label="样品名称" prop="sampleName" />
<el-table-column label="零件号" prop="partNo" />
</el-table>
<div class="mb-8px mt-20px font-bold">夹具框架点</div>
<div class="flex items-center gap-12px"><el-tag :type="framework.current?.id ? 'success' : 'warning'">{{ framework.current?.id ? '可复用' : '未配置' }}</el-tag><el-button link type="primary" @click="frameworkRef.open(detail)">查看 / 下载 / 复制</el-button></div>
<div class="mb-8px mt-20px font-bold">扫描轨迹</div>
<div class="flex items-center gap-12px">
<el-tag :type="detail.trajectoryStatus === 'LINKED' ? 'success' : 'info'">{{ detail.trajectoryStatus === 'LINKED' ? '已关联 · V' + detail.trajectoryVersion : '未关联' }}</el-tag>
@ -35,13 +37,16 @@
<MasterAttachmentPanel v-if="detail.id" biz-type="FIXTURE" :biz-id="detail.id" />
</ContentWrap>
<FixtureTrajectory ref="trajectoryRef" @updated="load" />
<FixtureFramework ref="frameworkRef" @updated="load" />
</template>
<script lang="ts" setup>
import { DICT_TYPE } from '@/utils/dict'
import * as FixtureApi from '@/api/lab/master/fixture'
import MasterAttachmentPanel from '../components/MasterAttachmentPanel.vue'
import FixtureTrajectory from './FixtureTrajectory.vue'
import FixtureFramework from './FixtureFramework.vue'
const trajectoryRef = ref()
const frameworkRef=ref(),framework=shallowRef<any>({})
defineOptions({ name: 'LabFixtureDetail' })
const route = useRoute()
@ -51,7 +56,7 @@ const detail = ref<FixtureApi.LabFixtureVO>({} as FixtureApi.LabFixtureVO)
const load = async () => {
loading.value = true
try {
detail.value = await FixtureApi.getFixture(String(route.params.id))
const [fixture,points]=await Promise.all([FixtureApi.getFixture(String(route.params.id)),FixtureApi.getFramework(String(route.params.id))]);detail.value=fixture;framework.value=points
} finally {
loading.value = false
}

View File

@ -50,7 +50,7 @@
<el-table-column label="操作" align="center" width="390" fixed="right">
<template #default="scope">
<el-button link type="primary" @click="goDetail(scope.row.id)">详情</el-button>
<el-button link type="primary" v-hasPermi="['lab:fixture:update']" @click="frameworkRef.open(scope.row)">夹具框架点</el-button>
<el-button link type="primary" v-hasPermi="['lab:fixture:query']" @click="frameworkRef.open(scope.row)">夹具框架点</el-button>
<el-button link type="primary" v-hasPermi="['lab:fixture:query']" @click="trajectoryRef.open(scope.row)">扫描轨迹</el-button>
<el-button link type="primary" v-hasPermi="['lab:fixture:update']" @click="openForm('update', scope.row.id)">编辑</el-button>
<el-button

View File

@ -1,16 +1,15 @@
<template>
<section v-if="targets.length || !hideEmpty" class="agv-view" aria-label="AGV地图与轨迹">
<header class="agv-toolbar">
<strong>{{ history ? '本次执行轨迹' : 'AGV实时地图' }}</strong>
<strong>{{ history ? '本次执行轨迹' : polling.stateMs ? 'AGV实时地图' : 'AGV地图预览' }}</strong>
<el-select v-if="targets.length > 1" v-model="selected" aria-label="查看AGV" style="width:260px"><el-option v-for="t in targets" :key="targetKey(t)" :value="targetKey(t)" :label="`${t.name || t.deviceId} · ${t.robotId}`" /></el-select>
<span v-else class="agv-caption">{{ target ? `${target.name || target.deviceId} · ${target.robotId}` : '尚未分配AGV' }}</span>
<el-tag v-if="target" :type="healthy ? 'success' : 'info'">{{ history ? '历史记录' : healthy ? '定位已更新' : '等待有效定位' }}</el-tag>
<el-tag v-if="target" :type="healthy ? 'success' : 'info'">{{ history ? '历史记录' : !polling.stateMs ? '准备预览' : healthy ? '定位已更新' : '等待有效定位' }}</el-tag>
<span class="agv-spacer" /><el-button v-if="target" size="small" @click="fit">适应地图</el-button>
<el-button v-if="target" size="small" :loading="loading" @click="refresh(true)">刷新</el-button>
<el-button v-if="target || robotIds || executionId" size="small" :loading="loading || targetsLoading" @click="manualRefresh">刷新</el-button>
</header>
<template v-if="target">
<p class="agv-caption">地图:{{ state?.currentMap || map?.mapId || '等待地图' }}<template v-if="pose"> · X {{ pose.x.toFixed(3) }} m · Y {{ pose.y.toFixed(3) }} m · 朝向 {{ ((pose.theta || 0) * 180 / Math.PI).toFixed(1) }}°</template><template v-if="state?.currentStation"> · 当前站点 {{ state.currentStation }}</template></p>
<el-alert v-if="error || data.message || data.archiveError" :title="error || data.message || data.archiveError" type="warning" :closable="false" />
<div ref="surface" class="agv-surface">
<canvas ref="canvas" role="img" aria-label="地图、站点、导航目标及已走轨迹" @wheel.prevent="zoom" @pointerdown="panStart" @pointermove="panMove" @pointerup="panEnd" @pointercancel="panEnd" />
<div v-if="!map && !points.length" class="agv-placeholder">{{ mapMessage || (loading ? '正在读取地图和定位…' : '等待地图;定位可用后将显示当前位置') }}</div>
@ -24,6 +23,7 @@
<script setup lang="ts">
import { agvTargets, agvState, agvMap } from '@/api/lab/scan-task/agvView'
import { finitePoint, assignmentRobots, mapCorners, viewTransform, navigationTargets, mergeAgvPoints } from './agvMap.mjs'
import { agvPollingPolicy } from './workbenchPolling.mjs'
const props=withDefaults(defineProps<{executionId?:string|number;status?:string;assignments?:any[];flowData?:any;active?:boolean;hideEmpty?:boolean;providedTargets?:any[]}>(),{active:true,hideEmpty:false,assignments:()=>[]})
const emit=defineEmits(['targets-change'])
const targets=ref<any[]>([]), selected=ref(''),data=ref<any>({}),map=shallowRef<any>(),points=shallowRef<any[]>([]),error=ref(''),mapMessage=ref(''),loading=ref(false)
@ -31,19 +31,24 @@ const surface=ref<HTMLElement>(),canvas=ref<HTMLCanvasElement>(),state=computed(
const history=computed(()=>data.value.history || !!props.executionId && ['SUCCEEDED','FAILED','CANCELLED'].includes(props.status || ''))
const healthy=computed(()=>!history.value && !error.value && !data.value.message && state.value?.connected && state.value?.localized && Date.now()-(state.value?.receivedAt || 0)<8000)
const pose=computed(()=>finitePoint(state.value?.pose)?state.value.pose:undefined),updatedAt=computed(()=>state.value?.receivedAt?new Date(state.value.receivedAt).toLocaleTimeString():''),plan=computed(()=>navigationTargets(props.flowData,map.value?.stations || [],props.assignments,target.value))
let generation=0,controller:AbortController|undefined,timer:any,observer:ResizeObserver|undefined,image:HTMLImageElement|undefined,frame=0,pan:any,view:any,manual=false,lastMapAt=0,suspended=false,nextPollAt=0,failures=0
let generation=0,controller:AbortController|undefined,timer:any,observer:ResizeObserver|undefined,image:HTMLImageElement|undefined,frame=0,pan:any,view:any,manual=false,lastMapAt=0,suspended=false,nextPollAt=0,failures=0,snapshotRead=false,targetsLoaded=false,targetsLoading=false
const polling=computed(()=>agvPollingPolicy(props.executionId,props.status))
const robotIds=computed(()=>assignmentRobots(props.assignments).join(',')),scopeKey=computed(()=>String(props.executionId || '')+'|'+robotIds.value)
function params(){return {...(props.executionId?{executionId:props.executionId}:{}),robotId:target.value?.robotId,deviceId:target.value?.deviceId}}
async function loadTargets(){
if(!props.executionId&&!robotIds.value&&!props.providedTargets?.length){targetsLoaded=true;targets.value=[];return}
if(targetsLoading)return
targetsLoading=true
const token=++generation;controller?.abort();controller=new AbortController();error.value='';
try{const list=props.providedTargets || await agvTargets(props.executionId?{executionId:props.executionId}:{robotIds:robotIds.value},controller.signal);if(token!==generation)return;targets.value=list || [];if(!targets.value.some(t=>targetKey(t)===selected.value))selected.value=targets.value[0]?targetKey(targets.value[0]):'';emit('targets-change',targets.value)}catch(e:any){if(token===generation&&!controller?.signal.aborted)error.value=e.message || 'AGV列表读取失败'}
loading.value=false
try{const list=props.providedTargets || await agvTargets(props.executionId?{executionId:props.executionId}:{robotIds:robotIds.value},controller.signal);if(token!==generation)return;targetsLoaded=true;targets.value=list || [];if(!targets.value.some(t=>targetKey(t)===selected.value))selected.value=targets.value[0]?targetKey(targets.value[0]):'';emit('targets-change',targets.value)}catch(e:any){if(token===generation&&!controller?.signal.aborted){targetsLoaded=true;error.value=e.message || 'AGV列表读取失败'}}finally{if(token===generation)targetsLoading=false}
}
async function refresh(force=false){
if(!target.value || !props.active || suspended || document.hidden || loading.value || !force&&Date.now()<nextPollAt)return
if(!target.value || !props.active || suspended || document.hidden || loading.value || !force&&(!polling.value.stateMs&&snapshotRead || Date.now()<nextPollAt))return
const token=generation;loading.value=true;const signal=controller?.signal
try{const value=await agvState({...params(),afterAt:points.value.at(-1)?.at || 0},signal);if(token!==generation)return;if(value.state&&state.value?.currentMap!==value.state.currentMap){map.value=undefined;image=undefined;view=undefined;lastMapAt=0;manual=false}data.value={...value,state:value.state || state.value};error.value='';if(value.message){nextPollAt=Date.now()+Math.min(15000,1000*2**Math.min(4,failures++))}else{failures=0;nextPollAt=0}points.value=mergeAgvPoints(points.value,value.points);scheduleDraw()
if(force || Date.now()-lastMapAt>5000){lastMapAt=Date.now();try{const next=await agvMap({...params(),version:map.value?.version},signal);if(token!==generation)return;if(next.available&&!next.unchanged){map.value=next;mapMessage.value='';const nextImage=new Image();nextImage.onload=()=>{if(token===generation&&map.value?.version===next.version){image=nextImage;if(!manual)fit();else scheduleDraw()}};nextImage.src=next.image}else if(next.available&&next.unchanged&&map.value&&Array.isArray(next.stations)){map.value={...map.value,stations:next.stations}}else if(!next.available)mapMessage.value=next.message || '地图暂不可用'}catch(e:any){if(token===generation&&!signal?.aborted)mapMessage.value=e.message || '地图读取失败,可继续查看定位轨迹'}}
}catch(e:any){if(token===generation&&!signal?.aborted){error.value=e.message || '定位读取失败';nextPollAt=Date.now()+Math.min(15000,1000*2**Math.min(4,failures++))}}finally{if(token===generation)loading.value=false}
try{const value=await agvState({...params(),afterAt:points.value.at(-1)?.at || 0},signal);if(token!==generation)return;if(value.state&&state.value?.currentMap!==value.state.currentMap){map.value=undefined;image=undefined;view=undefined;lastMapAt=0;manual=false}data.value={...value,state:value.state || state.value};error.value='';if(value.message){nextPollAt=Date.now()+Math.max(polling.value.stateMs,Math.min(60000,3000*2**Math.min(5,failures++)))}else{failures=0;nextPollAt=Date.now()+polling.value.stateMs}points.value=mergeAgvPoints(points.value,value.points);scheduleDraw()
if(force || !lastMapAt || Date.now()-lastMapAt>=polling.value.mapMs){lastMapAt=Date.now();try{const next=await agvMap({...params(),version:map.value?.version},signal);if(token!==generation)return;if(next.available&&!next.unchanged){map.value=next;mapMessage.value='';const nextImage=new Image();nextImage.onload=()=>{if(token===generation&&map.value?.version===next.version){image=nextImage;if(!manual)fit();else scheduleDraw()}};nextImage.src=next.image}else if(next.available&&next.unchanged&&map.value&&Array.isArray(next.stations)){map.value={...map.value,stations:next.stations}}}catch{/* Optional map failures stay silent; keep the last usable map. */}}
}catch(e:any){if(token===generation&&!signal?.aborted){error.value=e.message || '定位读取失败';nextPollAt=Date.now()+Math.max(polling.value.stateMs,Math.min(60000,3000*2**Math.min(5,failures++)))}}finally{if(token===generation){loading.value=false;if(!signal?.aborted)snapshotRead=true}}
}
function scheduleDraw(){if(!frame)frame=requestAnimationFrame(()=>{frame=0;draw()})}
function currentMapPoint(p:any){return (!state.value?.currentMap || p.mapId===state.value.currentMap) && (p.mapEpoch || 0)===(data.value.mapEpoch || 0)}
@ -64,18 +69,19 @@ function zoom(e:WheelEvent){if(!view)return;manual=true;const rect=canvas.value!
function panStart(e:PointerEvent){if(!view)return;manual=true;pan={x:e.clientX,y:e.clientY,v:{...view}};canvas.value?.setPointerCapture(e.pointerId)}
function panMove(e:PointerEvent){if(pan){view={...pan.v,x:pan.v.x+e.clientX-pan.x,y:pan.v.y+e.clientY-pan.y};scheduleDraw()}}
function panEnd(){pan=undefined}
function reset(){generation++;controller?.abort();controller=new AbortController();loading.value=false;data.value={};map.value=undefined;image=undefined;points.value=[];error.value='';mapMessage.value='';lastMapAt=0;nextPollAt=0;failures=0;view=undefined;manual=false;scheduleDraw();if(props.active)refresh()}
watch(scopeKey,()=>{selected.value='';targets.value=[];reset();if(props.active)loadTargets()},{immediate:true})
watch(selected,reset)
watch(()=>props.providedTargets,()=>{if(props.active)loadTargets()})
watch(()=>props.active,active=>{if(active){if(!targets.value.length)loadTargets();else refresh(true)}else{generation++;controller?.abort();controller=new AbortController();loading.value=false}})
watch(()=>props.status,()=>{if(props.active)refresh(true)})
function reset(){generation++;controller?.abort();controller=new AbortController();loading.value=false;data.value={};map.value=undefined;image=undefined;points.value=[];error.value='';mapMessage.value='';lastMapAt=0;nextPollAt=0;failures=0;snapshotRead=false;view=undefined;manual=false;scheduleDraw();if(props.active)refresh()}
watch(scopeKey,()=>{selected.value='';targets.value=[];targetsLoaded=false;targetsLoading=false;reset();if(props.active)loadTargets()},{immediate:true})
watch(selected,value=>{if(value)reset()})
watch(()=>JSON.stringify(props.providedTargets?.map(t=>[t.robotId,t.deviceId,t.name])),()=>{targetsLoaded=false;if(props.active)loadTargets()})
watch(()=>props.active,active=>{if(active){if(!targetsLoaded)loadTargets();else refresh()}else{generation++;controller?.abort();controller=new AbortController();loading.value=false;targetsLoading=false}})
watch(()=>props.status,()=>{snapshotRead=false;nextPollAt=0;if(props.active)refresh()})
watch([plan,pose],()=>{if(!manual&&!map.value)fit();else scheduleDraw()})
onMounted(()=>{observer=new ResizeObserver(()=>{if(!manual)fit();else scheduleDraw()});if(surface.value)observer.observe(surface.value);timer=setInterval(()=>{if(!history.value)refresh()},1000)})
onMounted(()=>{observer=new ResizeObserver(()=>{if(!manual)fit();else scheduleDraw()});if(surface.value)observer.observe(surface.value);timer=setInterval(()=>{if(polling.value.stateMs&&!history.value)refresh()},1000)})
watch(surface,(el)=>{observer?.disconnect();if(el)observer?.observe(el)})
onActivated(()=>{suspended=false;if(props.active)refresh(true)})
onDeactivated(()=>{suspended=true;generation++;controller?.abort();controller=new AbortController();loading.value=false})
onActivated(()=>{suspended=false;if(props.active){if(!targetsLoaded)loadTargets();else refresh()}})
onDeactivated(()=>{suspended=true;generation++;controller?.abort();controller=new AbortController();loading.value=false;targetsLoading=false})
onBeforeUnmount(()=>{generation++;controller?.abort();clearInterval(timer);observer?.disconnect();if(frame)cancelAnimationFrame(frame)})
async function manualRefresh(){if(!target.value){targetsLoaded=false;await loadTargets()}else await refresh(true)}
</script>
<style scoped>
.agv-view{padding:12px 0;min-width:0;color:var(--el-text-color-primary)}.agv-toolbar{display:flex;align-items:center;gap:10px;flex-wrap:wrap}.agv-spacer{flex:1}.agv-caption{font-size:12px;line-height:1.7;color:var(--el-text-color-secondary);overflow-wrap:anywhere;margin:8px 0}.agv-surface{position:relative;height:420px;min-height:280px;background:var(--el-fill-color-light);border:1px solid var(--el-border-color-lighter);border-radius:8px;overflow:hidden}.agv-surface canvas{display:block;width:100%;height:100%;touch-action:none;cursor:grab}.agv-placeholder{position:absolute;top:45%;left:10%;width:80%;text-align:center;pointer-events:none;color:var(--el-text-color-secondary)}.agv-legend{position:absolute;bottom:10px;left:12px;display:flex;flex-wrap:wrap;gap:12px;padding:6px 10px;border-radius:5px;background:var(--el-bg-color);font-size:12px;pointer-events:none}.agv-legend span{display:flex;align-items:center;gap:5px}.agv-legend i{width:9px;height:9px;border-radius:50%;display:inline-block}.station{background:#477cd6}.target{background:#d18c22}.trail{background:#18a47a}.robot{background:#2771ed}

View File

@ -147,7 +147,7 @@ const executionAssignments = computed(() => { const value=props.execution?.runPa
const terminal = computed(() =>
['SUCCEEDED', 'FAILED', 'CANCELLED'].includes(props.execution?.status || '')
)
const nativeLogs = ref<any[]>([])
const nativeLogs = shallowRef<any[]>([])
const loading = ref(false)
const error = ref('')
const now = ref(Date.now())
@ -194,17 +194,17 @@ const progressStatus = computed(() =>
: undefined
)
let generation = 0
let pending: { id: string; token: number } | undefined
let pending: { id: string; token: number; status?: string } | undefined
let controller: AbortController | undefined
let suspended = false
async function load(force = false) {
const id = props.execution?.id
if (!id || (!force && pending?.id === String(id))) return
if (!id || !props.active || suspended || document.hidden || pending?.id === String(id) && (!force || pending.status === props.execution?.status)) return
const token = ++generation
controller?.abort()
controller = new AbortController()
const signal = controller.signal
pending = { id: String(id), token }
pending = { id: String(id), token, status: props.execution?.status }
loading.value = true
error.value = ''
try {
@ -280,10 +280,10 @@ const timer = setInterval(() => {
props.active &&
!suspended &&
!document.hidden &&
['RUNNING', 'QUEUED', 'PREPARING', 'PAUSED'].includes(props.execution?.status || '')
['RUNNING', 'QUEUED', 'PREPARING', 'PAUSED', 'STOPPING'].includes(props.execution?.status || '')
)
load()
}, 2000)
}, 3000)
const clock = setInterval(() => {
if (props.active && !suspended && !document.hidden && !terminal.value) now.value = Date.now()
}, 1000)

View File

@ -19,9 +19,12 @@ const ScannerModelPanel = defineAsyncComponent(() => import('./ScannerModelPanel
const props = withDefaults(defineProps<{ executionId: string | number; executionNo?: string; status?: string; active?: boolean; assignments?:any[];flowData?:any;activeAction?:string }>(), { active: true,assignments:()=>[] })
const targets=ref<any[]>([]),manualTab=ref(false)
let targetGeneration=0,targetController:AbortController|undefined
let targetsFor='',targetLoading=false
const initialTab = () => ['SUCCEEDED', 'FAILED', 'CANCELLED'].includes(props.status || '') ? 'model' : 'live'
const tab = ref(initialTab())
watch(() => props.executionId, async () => { tab.value = initialTab();manualTab.value=false;targets.value=[];const token=++targetGeneration;targetController?.abort();targetController=new AbortController();try{const rows=await agvTargets({executionId:props.executionId},targetController.signal);if(token!==targetGeneration)return;targets.value=rows || [];if(targets.value.length&&!manualTab.value)tab.value='agv'}catch{/* Scanner views remain available if AGV metadata cannot be read. */} },{immediate:true})
async function loadTargets(){if(!props.active||!props.executionId||targetLoading||targetsFor===String(props.executionId))return;targetLoading=true;const token=++targetGeneration;targetController?.abort();targetController=new AbortController();try{const rows=await agvTargets({executionId:props.executionId},targetController.signal);if(token!==targetGeneration)return;targets.value=rows||[];targetsFor=String(props.executionId);if(targets.value.length&&!manualTab.value)tab.value='agv'}catch{/* Scanner views remain available if AGV metadata cannot be read. */}finally{if(token===targetGeneration)targetLoading=false}}
watch(() => props.executionId, () => { tab.value=initialTab();manualTab.value=false;targets.value=[];targetsFor='';targetLoading=false;targetGeneration++;targetController?.abort();void loadTargets() },{immediate:true})
watch(()=>props.active,active=>{if(active)void loadTargets();else{targetGeneration++;targetController?.abort();targetLoading=false}})
watch(()=>props.activeAction,action=>{if(!manualTab.value&&props.active){if(action?.startsWith('AGV_')&&targets.value.length)tab.value='agv';else if(action?.startsWith('SCANNER_'))tab.value='live'}})
watch(() => props.status, () => { if (tab.value === 'live' && initialTab() === 'model') tab.value = 'model' })
onBeforeUnmount(()=>{targetGeneration++;targetController?.abort()})

View File

@ -41,8 +41,10 @@ export function navigationTargets(flow, stations = [], assignments = [], target)
return {points,branched,unresolved}
}
export function mergeAgvPoints(previous, incoming, limit = 20000) {
const points=previous.slice(), keys=new Set(points.map(p=>`${p.at}:${p.segment}`))
for(const p of incoming || [])if(finitePoint(p) && !keys.has(`${p.at}:${p.segment}`)){points.push(p);keys.add(`${p.at}:${p.segment}`)}
if(!incoming?.length)return previous
let points=previous
const keys=new Set(previous.map(p=>`${p.at}:${p.segment}`))
for(const p of incoming)if(finitePoint(p) && !keys.has(`${p.at}:${p.segment}`)){if(points===previous)points=previous.slice();points.push(p);keys.add(`${p.at}:${p.segment}`)}
if(points.length<=limit)return points
return points.filter((p,i)=>i%2===0 || i===points.length-1 || i>0&&p.segment!==points[i-1].segment).slice(-limit)
}

View File

@ -248,6 +248,7 @@
<el-form-item label="测试用例(方法号)" required
><el-select
v-model="form.testCaseId"
:loading="catalogLoading"
filterable
class="!w-full"
@change="changeCase"
@ -574,7 +575,7 @@
</el-collapse-item>
</el-collapse>
<div class="hint mt-12px"
>执行完成只表示扫描流程已结束;本期不包含覆盖完整性判断、检测结论和报告。</div
>执行完成只表示扫描流程已结束;尺寸比对、报告与最终交付请在任务的“比对与成果”中查看。</div
>
</section>
</ContentWrap>
@ -677,6 +678,7 @@ import { getResourceRoles, normalizeFlowResourceSchema } from '@/cmvr/common/uti
import RuntimeAssignmentsEditor from '@/cmvr/common/views/flow/components/RuntimeAssignmentsEditor.vue'
import ScanExecutionMonitor from './ScanExecutionMonitor.vue'
const AgvLiveMap = defineAsyncComponent(() => import('./AgvLiveMap.vue'))
import { scanTaskPollInterval } from './workbenchPolling.mjs'
import ResourceSchedule, { type ScheduleForm } from './ResourceSchedule.vue'
import { attemptLabel, sourceAttempt, batchProgress, preparationStage, unitExecution } from './executionPresentation.mjs'
import ParameterFields from './ParameterFields.vue'
@ -697,7 +699,8 @@ const route = useRoute()
const router = useRouter()
const message = useMessage()
const taskId = computed(() => String(route.params.id))
const detail = ref<ScanApi.ScanTaskDetail>()
const detail = shallowRef<ScanApi.ScanTaskDetail>()
const catalogLoading=ref(false)
const loading = ref(false)
const busy = ref(false)
const dirty = ref(false)
@ -888,7 +891,7 @@ const applySchema = (inputConfig: any, flowData: any, values: Record<string, any
}
let pageGeneration = 0
let activeRefresh: Promise<void> | undefined
const refresh = async (replaceForm = false) => {
const refresh = async (replaceForm = false, refreshVersions = true) => {
if (activeRefresh) {
await activeRefresh
if (!replaceForm) return
@ -938,7 +941,7 @@ const refresh = async (replaceForm = false) => {
dirty.value = false
if (replaceForm) {
resourceRevision.value++
if(executionMode.value === 'single') await loadVersions(false)
if(refreshVersions && executionMode.value === 'single') await loadVersions(false)
}
}
}
@ -1307,11 +1310,29 @@ const openLogs = (execution: Partial<LabExecutionVO>) => {
}
let timer: ReturnType<typeof setInterval> | undefined
let pollingSuspended = false
let catalogLoaded=false,catalogPending:Promise<void>|undefined
const loadCatalog=async()=>{
if(!detail.value||locked.value||catalogLoaded||catalogPending||!props.active||activeTab.value!=='prepare')return
const generation=pageGeneration
catalogLoading.value=true
const pending=(async()=>{
try{
const found:any[]=[];let pageNum=1
while(true){const result:any=await getTestCaseList({pageNum,pageSize:100});if(generation!==pageGeneration)return;const rows=result.rows||[];found.push(...rows);if(!rows.length||found.length>=(result.total??found.length))break;pageNum++}
if(generation!==pageGeneration)return
cases.value=found;catalogLoaded=true;await loadVersions()
}catch(error:any){if(generation===pageGeneration)message.warning(error.message||'用例目录加载失败,可刷新重试;已保存配置仍可查看')}
finally{if(generation===pageGeneration)catalogLoading.value=false}
})()
catalogPending=pending
try{await pending}finally{if(catalogPending===pending)catalogPending=undefined}
}
const initialize = async () => {
logVisible.value = false
logSelection.value = undefined
pageGeneration++
versionRequest++
catalogLoaded=false;catalogPending=undefined;catalogLoading.value=false
dirty.value = false
selectedUnitId.value = ''
selectedAttemptId.value = ''
@ -1319,19 +1340,11 @@ const initialize = async () => {
try {
// Frozen task history is readable even when the operator cannot browse the native catalog.
cases.value = []
await refresh(true)
await refresh(true,false)
activeTab.value = detail.value?.config.startedAt || terminal.value ? 'units' : 'prepare'
const found: any[] = []
let pageNum = 1
while (true) {
const result: any = await getTestCaseList({ pageNum, pageSize: 100 })
const rows = result.rows || []
found.push(...rows)
if (!rows.length || found.length >= (result.total ?? found.length)) break
pageNum++
}
cases.value = found
await loadVersions()
loading.value=false
if(!locked.value)void loadCatalog()
else await loadVersions()
} catch (error: any) {
message.warning(
error.message || '用例目录加载失败;已保存的任务记录仍可查看,请检查用例读取权限。'
@ -1343,13 +1356,14 @@ const initialize = async () => {
onMounted(() => {
initialize().catch(() => {})
timer = setInterval(() => {
if (props.active && !pollingSuspended && !document.hidden && !busy.value && !terminal.value) {
if (props.active && !pollingSuspended && !document.hidden && !busy.value && scanTaskPollInterval(detail.value)) {
refresh().catch(() => {})
}
}, 3000)
}, 5000)
})
onActivated(() => { pollingSuspended = false })
onDeactivated(() => { pollingSuspended = true })
watch([()=>props.active,activeTab],()=>{if(props.active&&!pollingSuspended){void loadCatalog()}})
watch(() => route.params.id, initialize)
onBeforeRouteLeave(async () => {
if (dirty.value && !locked.value) {

View File

@ -0,0 +1,13 @@
const active = new Set(['QUEUED', 'PREPARING', 'RUNNING', 'PAUSED', 'STOPPING'])
export const AGV_MAP_INTERVAL_MS = 60000
export function agvPollingPolicy(executionId, status) {
return { stateMs: executionId && active.has(status) ? status === 'PAUSED' ? 10000 : 3000 : 0, mapMs: AGV_MAP_INTERVAL_MS }
}
export function scanTaskPollInterval(detail) {
if (!detail) return 0
const working = detail.config?.stopPending || active.has(detail.task?.status) || detail.units?.some(unit => active.has(unit.status) || unit.attempts?.some(attempt => active.has(attempt.status)))
return working ? 5000 : 0
}
export function comparisonPollInterval(status) {
return ['SUBMITTING', 'PROCESSING', 'REVIEW', 'ARCHIVE_PENDING'].includes(status) ? 10000 : 0
}

View File

@ -221,6 +221,19 @@ pwsh -NoProfile -File deploy/windows11/manage.ps1 -Action Start
模板升级不会覆盖`.local/standalone`。数据库结构升级需要阅读对应迁移说明,不能把空库Bootstrap当作业务库升级工具。
尺寸比对集成新增`017_dimension_comparison.sql`中的三张独立表。迁移包恢复会自动执行增量结构升级,保留原任务、用例、用户及菜单。已有独立实例更新代码后,在停止后端并完成备份的维护窗口执行:
```powershell
python scripts/bootstrap_standalone.py --config .local/standalone/runtime.json --upgrade
python scripts/bootstrap_standalone.py --config .local/standalone/runtime.json --verify
```
配置文件路径以本机`manage.ps1`生成的实际路径为准。`--upgrade`只增加已批准迁移中的缺失结构,不执行空库初始化或重置用户菜单。
尺寸比对计算仍使用供应商的Windows EXE,单独安装并启动,沿用默认地址`http://127.0.0.1:8769`。平台后端在同一Windows主机运行,因此这里的127.0.0.1指该主机。无需把计算服务放进Docker或改写供应商检测计划管理方式。只有供应商服务地址实际变化时才设置`INSPECTION_PYTHON_BASE_URL`。连接建立默认3秒,计算和文件传输等待默认10分钟,与设备动作的120秒等待独立。
进入任务的“比对与成果”,选好数模、PDF和本次扫描PLY后保存资料版本,点击“开始尺寸比对”。平台自动读取已归档文件;在“打开比对工作区”中沿用供应商的计划维护、清理和比对操作。计算完成后每15秒同步状态,并把同一成果版本的STL与PDF成套归档。下载和确认交付均使用平台归档副本。若服务只提供报告而没有唯一的处理后STL,页面会提示“成果归档待处理”;不会将原扫描文件冒充比对成果。补齐供应商输出后点“重试成果归档”,无需重新扫描或计算。提交回执丢失时保留待核对作业,不自动重复提交。
管理员可注册登录启动:
```powershell
@ -262,7 +275,7 @@ docker load -i freescan-images.tar
## 13. 常见故障
本次在源电脑完成了后端回归、前端类型检查与standalone打包、配置隔离检查,以及模拟空库的迁移流程验证。源电脑没有Docker环境,未在这里启动新MySQL/Redis容器或实际导出/恢复业务数据库。目标AI必须执行本手册的Docker配置检查、真实导入和验收;不能跳过后宣称迁移完成。启动容器前先运行`docker compose --env-file .local/standalone/compose.env -f deploy/windows11/compose.yaml config --quiet`,不要打印包含密码的展开配置。
源电脑已完成后端回归、前端类型检查与standalone打包、配置隔离检查、模拟空库迁移验证,并已生成当前业务数据库和可用文件的数据迁移包。源电脑没有Docker环境,未在这里启动新MySQL/Redis容器或执行目标恢复。目标AI必须执行本手册的Docker配置检查、真实导入和验收;不能跳过后宣称迁移完成。启动容器前先运行`docker compose --env-file .local/standalone/compose.env -f deploy/windows11/compose.yaml config --quiet`,不要打印包含密码的展开配置。
- WSL/Docker没启动:检查虚拟化、WSL版本、当前用户Docker Desktop,不切成Windows容器。
- MySQL/Redis不健康:先看`compose ps`及容器日志;不输出`compose config`展开后的密码,不删卷重建。

View File

@ -125,6 +125,7 @@ switch ($Action) {
'Restore' {
if (-not $ConfirmStopped -or -not $MigrationPath) { throw 'Restore requires -MigrationPath and -ConfirmStopped; source must remain stopped' }
Invoke-Checked 'python' @((Join-Path $repo 'scripts/migrate_standalone.py'),'import','--config',$runtimeFile,'--package',$MigrationPath,'--confirm-source-stopped')
Invoke-Checked 'python' @($bootstrap,'--config',$runtimeFile,'--upgrade')
Invoke-Checked 'python' @($bootstrap,'--config',$runtimeFile,'--verify')
}
'Start' {

View File

@ -0,0 +1,10 @@
{
"feature": "任务尺寸比对集成",
"supplierFrontend": {"repository": "http://117.72.214.124:6060/am/am-web.git", "branch": "master", "commit": "d02da42ce634e57bf0b213151fa84e4ffa59a0b2"},
"supplierBackend": {"repository": "http://117.72.214.124:6060/am/am-backend.git", "branch": "master-jdk17", "commit": "8ee5293986fad9068f25dd0587e9a2d5f3427472"},
"selectedModules": ["inspection workbench, viewer, cleanup and plan templates", "inspection geometry, display and theme styles", "managed inspection template service and seed catalog"],
"platformAdaptations": ["task-owned frozen CAD/PDF/PLY inputs streamed to the existing EXE", "durable submission intent with no automatic resubmission on lost receipt", "tenant and task ownership checks", "paired local STL/PDF archive with input, scan execution, plan and output revision provenance", "archived PDF and STL remain downloadable when the EXE is unavailable"],
"excludedModules": ["supplier standalone task and report menus", "legacy report BLOB archive and Redis import", "supplier fixed upload limits", "replacement of platform task or scan state machines"],
"engine": {"defaultBaseUrl": "http://127.0.0.1:8769", "distribution": "supplier Windows EXE, separate installation", "sourceInRepository": false},
"schemaMigration": "am-backend/sql/freescan/017_dimension_comparison.sql"
}

View File

@ -0,0 +1,41 @@
"""Add only the three comparison tables to the explicitly owned development database.
Default is offline. No menus, users, tasks, flows or historical results are changed.
"""
from pathlib import Path
import argparse,hashlib,json,sys
ROOT=Path(__file__).resolve().parents[1]
sys.path.insert(0,str(ROOT/'scripts'))
import bootstrap_db as base
from apply_scan_only import load_migration,apply_schema
SQL=base.SQL_ROOT/'017_dimension_comparison.sql'
TABLES={'lab_inspection_scan','lab_inspection_template','lab_dimension_comparison'}
def main():
parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--apply',action='store_true');args=parser.parse_args()
operations=load_migration(SQL)
if {item['table'] for item in operations}!=TABLES or any(item['kind']!='table' for item in operations):raise ValueError('Unexpected schema operation')
if not args.apply:print(json.dumps(dict(offline=True,tables=sorted(TABLES),noDatabaseConnection=True)));return
import pymysql
config=json.loads((ROOT/'.local/runtime.json').read_text(encoding='utf-8-sig'))['mysql'];base.validate_target(config)
db=pymysql.connect(host=config['host'],port=int(config.get('port',3306)),user=config['user'],password=config['password'],database=config['database'],charset='utf8mb4',autocommit=True)
try:
with db.cursor() as cursor:
cursor.execute(f"SELECT value FROM `{base.META}` WHERE name='owner'")
if cursor.fetchone()!=(base.OWNER,):raise ValueError('Database ownership mismatch')
cursor.execute('SELECT GET_LOCK(%s,10)',(base.OWNER,))
if cursor.fetchone()!=(1,):raise ValueError('Another schema operation is running')
try:
before={}
for table in ['lab_test_task','lab_execution','lab_fixture','system_menu']:
cursor.execute(f'SELECT COUNT(*) FROM `{table}`');before[table]=cursor.fetchone()[0]
changes=apply_schema(cursor,operations)
for table,count in before.items():
cursor.execute(f'SELECT COUNT(*) FROM `{table}`')
if cursor.fetchone()[0]!=count:raise ValueError('Unexpected concurrent business change; review before continuing')
cursor.execute(f'INSERT INTO `{base.META}` (name,value) VALUES(%s,%s) ON DUPLICATE KEY UPDATE value=VALUES(value)',(SQL.name,hashlib.sha256(SQL.read_bytes()).hexdigest()))
print(json.dumps(dict(applied=True,additiveChanges=changes,existingRowsPreserved=True)))
finally:cursor.execute('SELECT RELEASE_LOCK(%s)',(base.OWNER,))
finally:db.close()
if __name__=='__main__':
try:main()
except Exception as error:
print('Comparison schema stopped: '+(str(error) if isinstance(error,ValueError) else type(error).__name__+'; inspect private configuration'),file=sys.stderr);raise SystemExit(1)

View File

@ -136,7 +136,7 @@ def load_assets():
seeds = {}
for path in sorted(SQL_ROOT.glob("*.sql")):
if path.name.endswith("_schema.sql") or path.name in {"005_scan_only.sql", "006_resource_scheduling.sql",
"007_scanner_integration.sql", "008_scanner_execution_view.sql", "009_rotary_base_integration.sql", "010_scanner_framework_reference.sql", "011_fixture_framework.sql", "012_robot_service_endpoint.sql", "013_execution_plan.sql", "014_dimension_delivery.sql", "015_fixture_trajectory.sql"}:
"007_scanner_integration.sql", "008_scanner_execution_view.sql", "009_rotary_base_integration.sql", "010_scanner_framework_reference.sql", "011_fixture_framework.sql", "012_robot_service_endpoint.sql", "013_execution_plan.sql", "014_dimension_delivery.sql", "015_fixture_trajectory.sql", "017_dimension_comparison.sql"}:
# Dedicated additive migration runs after bootstrap_cmvr. It is not
# a reference seed and must never pass through the seed executor.
continue

View File

@ -22,7 +22,7 @@ MIGRATIONS = (
"008_scanner_execution_view.sql", "009_rotary_base_integration.sql",
"010_scanner_framework_reference.sql", "011_fixture_framework.sql",
"012_robot_service_endpoint.sql", "013_execution_plan.sql", "014_dimension_delivery.sql",
"015_fixture_trajectory.sql",
"015_fixture_trajectory.sql", "017_dimension_comparison.sql",
)
def plan():
@ -83,10 +83,11 @@ def main(argv=None):
mode = parser.add_mutually_exclusive_group()
mode.add_argument("--apply", action="store_true")
mode.add_argument("--verify", action="store_true")
mode.add_argument("--upgrade", action="store_true", help="Add approved schema structures to this owned instance without rewriting users or menus")
mode.add_argument("--check-idle", action="store_true")
args = parser.parse_args(argv)
schema, seeds, cmvr, reference, migrations = plan()
if not any((args.apply, args.verify, args.check_idle)):
if not any((args.apply, args.verify, args.check_idle, args.upgrade)):
print(json.dumps(dict(mode="offline", target="127.0.0.1:3306/am-freescan",
baseTables=len(schema), nativeTables=len(cmvr), migrations=[n for n, _ in migrations],
referenceSeeds=list(seeds), noDatabaseConnection=True)))
@ -99,6 +100,19 @@ def main(argv=None):
with connect(cfg) as connection:
with connection.cursor() as cursor:
ownership(cursor, cfg, allow_empty=args.apply)
if args.upgrade:
cursor.execute("SELECT GET_LOCK(%s,10)", (OWNER,))
if cursor.fetchone() != (1,):
raise ValueError("Another standalone schema operation is running")
try:
changes = sum(apply_schema(cursor, operations) for _, operations in migrations)
for name, _ in migrations:
checksum = hashlib.sha256((base.SQL_ROOT / name).read_bytes()).hexdigest()
cursor.execute(f"INSERT INTO `{base.META}` (name,value) VALUES(%s,%s) ON DUPLICATE KEY UPDATE value=VALUES(value)", (name,checksum))
print(json.dumps(dict(upgraded=True, additiveChanges=changes, usersAndMenusPreserved=True)))
finally:
cursor.execute("SELECT RELEASE_LOCK(%s)", (OWNER,))
return 0
if args.check_idle:
for sql in (
"SELECT COUNT(*) FROM te_task_inst WHERE status IN ('1','3')",
@ -121,7 +135,7 @@ def main(argv=None):
cursor.execute(sql)
if cursor.fetchone()[0] < 1:
raise ValueError("Required identity or navigation data is missing")
for table in set(schema) | set(cmvr) | {"lab_dimension_delivery", "lab_fixture_trajectory", "lab_resource_occupation", "lab_scanner_command"}:
for table in set(schema) | set(cmvr) | {"lab_dimension_delivery", "lab_fixture_trajectory", "lab_resource_occupation", "lab_scanner_command", "lab_dimension_comparison", "lab_inspection_scan", "lab_inspection_template"}:
cursor.execute("SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA='am-freescan' AND TABLE_NAME=%s", (table,))
if cursor.fetchone()[0] != 1:
raise ValueError("Missing required table: " + table)

View File

@ -13,7 +13,7 @@ import sys
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / '.tools/python'))
MARKERS = ('SCANQA-', 'CMVR_VERIFY_', 'CMVR_HOST_', 'CMVR_HOST_CONTROL_', 'E2E-')
LAB_TABLES = '''lab_dimension_event lab_dimension_delivery lab_dimension_file lab_dimension_case
LAB_TABLES = '''lab_dimension_comparison lab_dimension_event lab_dimension_delivery lab_dimension_file lab_dimension_case
lab_test_task lab_execution lab_task_scan_config lab_task_sample_unit
lab_task_assignment lab_task_sample lab_task_fixture lab_task_scan_plan_selection lab_task_timeline
lab_task_import_batch lab_task_import_row lab_cmvr_execution lab_scan_attachment lab_scan_robot_occupation
@ -28,7 +28,7 @@ lab_sample lab_fixture lab_fixture_applicable lab_fixture_framework lab_fixture_
NATIVE_TABLES = '''aima_test_case aima_task aima_task_test_case aima_task_instance aima_test_log
te_detection_item te_detection_item_version te_task_config_info te_task_orchestration
te_task_inst te_task_inst_flow_version te_node_inst te_ai_evaluation'''.split()
TABLES = LAB_TABLES + NATIVE_TABLES + ['infra_file','lab_device','lab_scanner_command','lab_scanner_framework_transfer']
TABLES = LAB_TABLES + NATIVE_TABLES + ['infra_file','lab_device','lab_scanner_command','lab_scanner_framework_transfer','lab_inspection_scan']
def plan_rows(data, prefixes=None):
@ -67,6 +67,13 @@ def plan_rows(data, prefixes=None):
for table in LAB_TABLES:
if table != 'lab_task_import_row':
choose(table, lambda r: has(r, 'task_id', task_ids))
comparison_keys={(str(r.get('tenant_id')),str(r.get('engine_id'))) for r in rows('lab_dimension_comparison') if r.get('engine_id')}
choose('lab_inspection_scan',lambda r:(str(r.get('tenant_id')),str(r.get('id'))) in comparison_keys)
for index,row in enumerate(data.get('lab_dimension_comparison',[])):
if index not in selected.get('lab_dimension_comparison',set()) and (str(row.get('tenant_id')),str(row.get('engine_id'))) in comparison_keys:
raise ValueError('非测试比对作业仍引用待清理的计算记录')
if any(r.get('status') in ('SUBMITTING','UNKNOWN','PROCESSING','ARCHIVE_PENDING') for r in rows('lab_dimension_comparison')):
raise ValueError('比对作业尚未确认终态,拒绝清理')
execution_ids = ids('lab_execution')
choose('lab_cmvr_execution', lambda r: has(r, 'execution_id', execution_ids))
# Include generated plans only for SUPPLEMENT executions of the exact marked