feat: integrate barcode recognition with task workbench
This commit is contained in:
parent
a16f16e19a
commit
33c7d52d8c
90
am-backend/sql/freescan/019_barcode.sql
Normal file
90
am-backend/sql/freescan/019_barcode.sql
Normal file
@ -0,0 +1,90 @@
|
||||
-- RC7.2 实物条码登记与测量任务关联。
|
||||
-- 不改 Task / Selection / Execution / ResultBatch 状态机。
|
||||
-- 同一任务同一零部件只允许一件实物条码处于关联中:现有执行记录不能按实物拆分结果。
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `lab_piece_barcode` (
|
||||
`id` bigint NOT NULL COMMENT '主键',
|
||||
`barcode` varchar(128) NOT NULL COMMENT '实物条码原值',
|
||||
`barcode_namespace` varchar(64) NOT NULL DEFAULT 'LOCAL' COMMENT '编码来源或业务域',
|
||||
`sample_id` bigint NOT NULL COMMENT '零部件主数据 lab_sample.id',
|
||||
`part_no` varchar(64) NOT NULL COMMENT '零部件编号,稳定键',
|
||||
`physical_serial_no` varchar(128) DEFAULT NULL COMMENT '实物序列号',
|
||||
`status` varchar(32) NOT NULL COMMENT 'ACTIVE/DISABLED',
|
||||
`source` varchar(32) NOT NULL COMMENT 'MANUAL/IMPORT/EXTERNAL',
|
||||
`active_flag` tinyint DEFAULT NULL COMMENT '1=当前有效;停用后置空以释放唯一约束',
|
||||
`remark` varchar(500) DEFAULT NULL COMMENT '备注',
|
||||
`creator` varchar(64) DEFAULT '',
|
||||
`create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
`updater` varchar(64) DEFAULT '',
|
||||
`update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
`deleted` bit(1) NOT NULL DEFAULT b'0',
|
||||
`tenant_id` bigint NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_piece_barcode_active` (`tenant_id`, `barcode_namespace`, `barcode`, `active_flag`),
|
||||
KEY `idx_piece_barcode_part` (`tenant_id`, `part_no`, `status`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='实物条码登记';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `lab_piece_barcode_binding` (
|
||||
`id` bigint NOT NULL COMMENT '主键',
|
||||
`barcode_id` bigint NOT NULL COMMENT '条码登记',
|
||||
`barcode` varchar(128) NOT NULL COMMENT '条码快照',
|
||||
`task_id` bigint NOT NULL COMMENT '测量任务',
|
||||
`part_no` varchar(64) NOT NULL COMMENT '零部件编号',
|
||||
`sample_id` bigint NOT NULL COMMENT '零部件主数据',
|
||||
`binding_status` varchar(32) NOT NULL COMMENT 'BOUND/UNBOUND',
|
||||
`source` varchar(32) NOT NULL COMMENT 'SCAN/MANUAL',
|
||||
`idempotency_key` varchar(128) DEFAULT NULL COMMENT '幂等键',
|
||||
`bound_by` bigint DEFAULT NULL COMMENT '绑定人',
|
||||
`bound_at` datetime DEFAULT NULL COMMENT '绑定时间',
|
||||
`unbound_by` bigint DEFAULT NULL COMMENT '解除人',
|
||||
`unbound_at` datetime DEFAULT NULL COMMENT '解除时间',
|
||||
`unbind_reason` varchar(500) DEFAULT NULL COMMENT '解除或改绑原因',
|
||||
`active_flag` tinyint DEFAULT NULL COMMENT '1=当前关联;解除后置空',
|
||||
`creator` varchar(64) DEFAULT '',
|
||||
`create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
`updater` varchar(64) DEFAULT '',
|
||||
`update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
`deleted` bit(1) NOT NULL DEFAULT b'0',
|
||||
`tenant_id` bigint NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_piece_binding_one` (`tenant_id`, `task_id`, `part_no`, `active_flag`),
|
||||
UNIQUE KEY `uk_piece_binding_idem` (`tenant_id`, `idempotency_key`, `active_flag`),
|
||||
KEY `idx_piece_binding_barcode` (`tenant_id`, `barcode_id`, `binding_status`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='实物条码与测量任务关联';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `lab_piece_barcode_audit` (
|
||||
`id` bigint NOT NULL COMMENT '主键',
|
||||
`action` varchar(32) NOT NULL COMMENT '动作',
|
||||
`barcode` varchar(128) DEFAULT NULL COMMENT '条码',
|
||||
`barcode_namespace` varchar(64) DEFAULT NULL COMMENT '编码域',
|
||||
`barcode_id` bigint DEFAULT NULL COMMENT '条码登记',
|
||||
`task_id` bigint DEFAULT NULL COMMENT '任务',
|
||||
`part_no` varchar(64) DEFAULT NULL COMMENT '零部件编号',
|
||||
`resolution` varchar(32) DEFAULT NULL COMMENT '识别结论',
|
||||
`message` varchar(500) DEFAULT NULL COMMENT '说明',
|
||||
`detail_json` varchar(1000) DEFAULT NULL COMMENT '最小审计明细',
|
||||
`operator_id` bigint DEFAULT NULL COMMENT '操作人',
|
||||
`creator` varchar(64) DEFAULT '',
|
||||
`create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
`updater` varchar(64) DEFAULT '',
|
||||
`update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
`deleted` bit(1) NOT NULL DEFAULT b'0',
|
||||
`tenant_id` bigint NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_piece_barcode_audit` (`tenant_id`, `barcode`, `create_time`),
|
||||
KEY `idx_piece_barcode_audit_task` (`tenant_id`, `task_id`, `create_time`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='实物条码识别与关联审计';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `lab_barcode_scan_profile` (
|
||||
`id` bigint NOT NULL COMMENT '主键',
|
||||
`prefix` varchar(16) NOT NULL DEFAULT '' COMMENT '扫描枪前缀,识别时去掉一次',
|
||||
`suffix` varchar(16) NOT NULL DEFAULT '' COMMENT '扫描枪后缀,识别时去掉一次',
|
||||
`creator` varchar(64) DEFAULT '',
|
||||
`create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
`updater` varchar(64) DEFAULT '',
|
||||
`update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
`deleted` bit(1) NOT NULL DEFAULT b'0',
|
||||
`tenant_id` bigint NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_barcode_scan_profile_tenant` (`tenant_id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='扫码枪前后缀配置';
|
||||
@ -0,0 +1,107 @@
|
||||
package cn.iocoder.yudao.module.lab.controller.admin.barcode;
|
||||
|
||||
import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
|
||||
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
|
||||
import cn.iocoder.yudao.framework.common.pojo.PageResult;
|
||||
import cn.iocoder.yudao.module.lab.controller.admin.barcode.vo.*;
|
||||
import cn.iocoder.yudao.module.lab.service.barcode.LabBarcodeService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.annotation.Resource;
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.CREATE;
|
||||
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.UPDATE;
|
||||
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
|
||||
|
||||
@Tag(name = "管理后台 - 实物条码")
|
||||
@RestController
|
||||
@RequestMapping("/lab/barcode")
|
||||
@Validated
|
||||
public class LabBarcodeController {
|
||||
|
||||
@Resource
|
||||
private LabBarcodeService barcodeService;
|
||||
|
||||
@PostMapping("/resolve")
|
||||
@Operation(summary = "识别实物条码并匹配测量任务,不写任务状态")
|
||||
@PreAuthorize("@ss.hasPermission('lab:barcode:query')")
|
||||
public CommonResult<LabBarcodeResolveRespVO> resolve(@Valid @RequestBody LabBarcodeResolveReqVO reqVO) {
|
||||
return success(barcodeService.resolve(reqVO));
|
||||
}
|
||||
|
||||
@PostMapping("/register")
|
||||
@Operation(summary = "把未登记条码绑定到已有零部件")
|
||||
@PreAuthorize("@ss.hasPermission('lab:barcode:register')")
|
||||
@ApiAccessLog(operateType = CREATE)
|
||||
public CommonResult<LabBarcodeResolveRespVO> register(@Valid @RequestBody LabBarcodeRegisterReqVO reqVO) {
|
||||
return success(barcodeService.register(reqVO));
|
||||
}
|
||||
|
||||
@PostMapping("/bind-task")
|
||||
@Operation(summary = "把已登记条码关联到测量任务")
|
||||
@PreAuthorize("@ss.hasPermission('lab:barcode:bind')")
|
||||
@ApiAccessLog(operateType = CREATE)
|
||||
public CommonResult<LabBarcodeResolveRespVO> bindTask(@Valid @RequestBody LabBarcodeBindReqVO reqVO) {
|
||||
return success(barcodeService.bindTask(reqVO));
|
||||
}
|
||||
|
||||
@PostMapping("/unbind-task")
|
||||
@Operation(summary = "解除条码与测量任务的关联")
|
||||
@PreAuthorize("@ss.hasPermission('lab:barcode:rebind')")
|
||||
@ApiAccessLog(operateType = UPDATE)
|
||||
public CommonResult<LabBarcodeResolveRespVO> unbindTask(@Valid @RequestBody LabBarcodeUnbindReqVO reqVO) {
|
||||
return success(barcodeService.unbindTask(reqVO));
|
||||
}
|
||||
|
||||
@PostMapping("/rebind")
|
||||
@Operation(summary = "把条码改绑到另一个已有零部件")
|
||||
@PreAuthorize("@ss.hasPermission('lab:barcode:rebind')")
|
||||
@ApiAccessLog(operateType = UPDATE)
|
||||
public CommonResult<LabBarcodeResolveRespVO> rebind(@Valid @RequestBody LabBarcodeRebindReqVO reqVO) {
|
||||
return success(barcodeService.rebind(reqVO));
|
||||
}
|
||||
|
||||
@PostMapping("/disable")
|
||||
@Operation(summary = "停用实物条码")
|
||||
@PreAuthorize("@ss.hasPermission('lab:barcode:rebind')")
|
||||
@ApiAccessLog(operateType = UPDATE)
|
||||
public CommonResult<LabBarcodeResolveRespVO> disable(@Valid @RequestBody LabBarcodeDisableReqVO reqVO) {
|
||||
return success(barcodeService.disable(reqVO));
|
||||
}
|
||||
|
||||
@GetMapping("/binding-history")
|
||||
@Operation(summary = "查看条码登记和关联审计")
|
||||
@PreAuthorize("@ss.hasPermission('lab:barcode:query')")
|
||||
public CommonResult<PageResult<LabBarcodeAuditRespVO>> history(@Valid LabBarcodeHistoryPageReqVO reqVO) {
|
||||
return success(barcodeService.history(reqVO));
|
||||
}
|
||||
|
||||
@GetMapping("/parts")
|
||||
@Operation(summary = "搜索可登记的已有零部件")
|
||||
@PreAuthorize("@ss.hasPermission('lab:barcode:register')")
|
||||
public CommonResult<List<LabBarcodePartOptionRespVO>> parts(@RequestParam(value = "keyword", required = false) String keyword) {
|
||||
return success(barcodeService.searchParts(keyword));
|
||||
}
|
||||
|
||||
@GetMapping("/profile")
|
||||
@Operation(summary = "读取扫码前后缀")
|
||||
@PreAuthorize("@ss.hasPermission('lab:barcode:query')")
|
||||
public CommonResult<LabBarcodeProfileRespVO> getProfile() {
|
||||
return success(barcodeService.getProfile());
|
||||
}
|
||||
|
||||
@PutMapping("/profile")
|
||||
@Operation(summary = "保存扫码前后缀")
|
||||
@PreAuthorize("@ss.hasPermission('lab:barcode:register')")
|
||||
@ApiAccessLog(operateType = UPDATE)
|
||||
public CommonResult<Boolean> saveProfile(@Valid @RequestBody LabBarcodeProfileReqVO reqVO) {
|
||||
barcodeService.saveProfile(reqVO);
|
||||
return success(true);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,21 @@
|
||||
package cn.iocoder.yudao.module.lab.controller.admin.barcode.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
public class LabBarcodeAuditRespVO {
|
||||
|
||||
private Long id;
|
||||
private String action;
|
||||
private String barcode;
|
||||
private String barcodeNamespace;
|
||||
private Long barcodeId;
|
||||
private Long taskId;
|
||||
private String partNo;
|
||||
private String resolution;
|
||||
private String message;
|
||||
private Long operatorId;
|
||||
private LocalDateTime createTime;
|
||||
}
|
||||
@ -0,0 +1,27 @@
|
||||
package cn.iocoder.yudao.module.lab.controller.admin.barcode.vo;
|
||||
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class LabBarcodeBindReqVO {
|
||||
|
||||
@Size(max = 256)
|
||||
private String barcode;
|
||||
|
||||
/** True only when reusing a previously resolved canonical barcode. */
|
||||
private boolean barcodeNormalized;
|
||||
|
||||
@NotNull(message = "请选择测量任务")
|
||||
private Long taskId;
|
||||
|
||||
@Size(max = 64)
|
||||
private String barcodeNamespace;
|
||||
|
||||
@Size(max = 128)
|
||||
private String idempotencyKey;
|
||||
|
||||
@Size(max = 64)
|
||||
private String stationId;
|
||||
}
|
||||
@ -0,0 +1,20 @@
|
||||
package cn.iocoder.yudao.module.lab.controller.admin.barcode.vo;
|
||||
|
||||
import jakarta.validation.constraints.Size;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class LabBarcodeDisableReqVO {
|
||||
|
||||
@Size(max = 256)
|
||||
private String barcode;
|
||||
|
||||
/** True only when reusing a previously resolved canonical barcode. */
|
||||
private boolean barcodeNormalized;
|
||||
|
||||
@Size(max = 64)
|
||||
private String barcodeNamespace;
|
||||
|
||||
@Size(max = 500)
|
||||
private String reason;
|
||||
}
|
||||
@ -0,0 +1,18 @@
|
||||
package cn.iocoder.yudao.module.lab.controller.admin.barcode.vo;
|
||||
|
||||
import cn.iocoder.yudao.framework.common.pojo.PageParam;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public class LabBarcodeHistoryPageReqVO extends PageParam {
|
||||
|
||||
private String barcode;
|
||||
|
||||
/** True only when reusing a previously resolved canonical barcode. */
|
||||
private boolean barcodeNormalized;
|
||||
private String barcodeNamespace;
|
||||
private Long taskId;
|
||||
private String action;
|
||||
}
|
||||
@ -0,0 +1,15 @@
|
||||
package cn.iocoder.yudao.module.lab.controller.admin.barcode.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class LabBarcodePartOptionRespVO {
|
||||
|
||||
private Long sampleId;
|
||||
private String partNo;
|
||||
private String partName;
|
||||
private String sampleCode;
|
||||
private String vehicleModel;
|
||||
private String projectName;
|
||||
private String status;
|
||||
}
|
||||
@ -0,0 +1,14 @@
|
||||
package cn.iocoder.yudao.module.lab.controller.admin.barcode.vo;
|
||||
|
||||
import jakarta.validation.constraints.Size;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class LabBarcodeProfileReqVO {
|
||||
|
||||
@Size(max = 16)
|
||||
private String prefix;
|
||||
|
||||
@Size(max = 16)
|
||||
private String suffix;
|
||||
}
|
||||
@ -0,0 +1,10 @@
|
||||
package cn.iocoder.yudao.module.lab.controller.admin.barcode.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class LabBarcodeProfileRespVO {
|
||||
|
||||
private String prefix;
|
||||
private String suffix;
|
||||
}
|
||||
@ -0,0 +1,27 @@
|
||||
package cn.iocoder.yudao.module.lab.controller.admin.barcode.vo;
|
||||
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class LabBarcodeRebindReqVO {
|
||||
|
||||
@Size(max = 256)
|
||||
private String barcode;
|
||||
|
||||
/** True only when reusing a previously resolved canonical barcode. */
|
||||
private boolean barcodeNormalized;
|
||||
|
||||
@NotNull(message = "请选择已有零部件")
|
||||
private Long sampleId;
|
||||
|
||||
@Size(max = 64)
|
||||
private String barcodeNamespace;
|
||||
|
||||
@Size(max = 128)
|
||||
private String physicalSerialNo;
|
||||
|
||||
@Size(max = 500)
|
||||
private String reason;
|
||||
}
|
||||
@ -0,0 +1,29 @@
|
||||
package cn.iocoder.yudao.module.lab.controller.admin.barcode.vo;
|
||||
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class LabBarcodeRegisterReqVO {
|
||||
|
||||
@Size(max = 256)
|
||||
private String barcode;
|
||||
|
||||
/** True only when reusing a previously resolved canonical barcode. */
|
||||
private boolean barcodeNormalized;
|
||||
|
||||
@NotNull(message = "请选择已有零部件")
|
||||
private Long sampleId;
|
||||
|
||||
@Size(max = 64)
|
||||
private String barcodeNamespace;
|
||||
|
||||
@Size(max = 128)
|
||||
private String physicalSerialNo;
|
||||
|
||||
@Size(max = 32)
|
||||
private String source;
|
||||
|
||||
private Long currentTaskId;
|
||||
}
|
||||
@ -0,0 +1,27 @@
|
||||
package cn.iocoder.yudao.module.lab.controller.admin.barcode.vo;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class LabBarcodeResolveReqVO {
|
||||
|
||||
@Schema(description = "扫描枪或手工输入的条码原值")
|
||||
@Size(max = 256)
|
||||
private String barcode;
|
||||
|
||||
/** True only when reusing a previously resolved canonical barcode. */
|
||||
private boolean barcodeNormalized;
|
||||
|
||||
@Schema(description = "当前已打开的测量任务。为空时按全局任务匹配")
|
||||
private Long currentTaskId;
|
||||
|
||||
@Schema(description = "编码来源。为空时使用 LOCAL")
|
||||
@Size(max = 64)
|
||||
private String barcodeNamespace;
|
||||
|
||||
@Schema(description = "工位号,只记入审计,不参与匹配")
|
||||
@Size(max = 64)
|
||||
private String stationId;
|
||||
}
|
||||
@ -0,0 +1,89 @@
|
||||
package cn.iocoder.yudao.module.lab.controller.admin.barcode.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
public class LabBarcodeResolveRespVO {
|
||||
|
||||
private String resolution;
|
||||
private String barcode;
|
||||
private String barcodeNamespace;
|
||||
/** ABSENT / ACTIVE / DISABLED / PART_DISABLED */
|
||||
private String registryStatus;
|
||||
/** 已识别、已绑定、未登记等,和是否已写入任务关联是两件事 */
|
||||
private String recognitionLabel;
|
||||
private Boolean recognized;
|
||||
private Boolean bound;
|
||||
private Boolean readOnly;
|
||||
private Boolean bindAllowed;
|
||||
private Boolean registeredNow;
|
||||
private String pieceTraceMode;
|
||||
private String message;
|
||||
private String nextAction;
|
||||
private String planHint;
|
||||
private Long chosenTaskId;
|
||||
private Long bindingId;
|
||||
private Long auditId;
|
||||
private String blockingBarcode;
|
||||
private Part part;
|
||||
private List<Task> candidateTasks = new ArrayList<>();
|
||||
private List<Task> historyTasks = new ArrayList<>();
|
||||
private List<Plan> selectedPlans = new ArrayList<>();
|
||||
private Plan currentPlan;
|
||||
private Plan nextPlan;
|
||||
|
||||
@Data
|
||||
public static class Part {
|
||||
private Long partId;
|
||||
private Long sampleId;
|
||||
private String partNo;
|
||||
private String partName;
|
||||
private String sampleCode;
|
||||
private String vehicleModel;
|
||||
private String projectName;
|
||||
private String status;
|
||||
private String physicalSerialNo;
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class Task {
|
||||
private Long taskId;
|
||||
private String taskNo;
|
||||
private String taskName;
|
||||
private String taskStatus;
|
||||
private String taskStatusName;
|
||||
private LocalDateTime plannedFinishAt;
|
||||
private String partNo;
|
||||
private Boolean readOnly;
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class Plan {
|
||||
private Long selectionId;
|
||||
private Integer sequenceNo;
|
||||
private String scanPlanName;
|
||||
private String scanPlanCode;
|
||||
private Boolean sequenceReady;
|
||||
private String displayStatus;
|
||||
private String blockedReason;
|
||||
private Long executionId;
|
||||
private Long unitId;
|
||||
private String executionNo;
|
||||
private String executionStatus;
|
||||
private Boolean pointCloudReady;
|
||||
private String inspectionScanId;
|
||||
private List<Link> resultBatches = new ArrayList<>();
|
||||
private List<Link> reports = new ArrayList<>();
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class Link {
|
||||
private Long id;
|
||||
private String no;
|
||||
private Long executionId;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,24 @@
|
||||
package cn.iocoder.yudao.module.lab.controller.admin.barcode.vo;
|
||||
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class LabBarcodeUnbindReqVO {
|
||||
|
||||
@Size(max = 256)
|
||||
private String barcode;
|
||||
|
||||
/** True only when reusing a previously resolved canonical barcode. */
|
||||
private boolean barcodeNormalized;
|
||||
|
||||
@NotNull(message = "请选择测量任务")
|
||||
private Long taskId;
|
||||
|
||||
@Size(max = 64)
|
||||
private String barcodeNamespace;
|
||||
|
||||
@Size(max = 500)
|
||||
private String reason;
|
||||
}
|
||||
@ -0,0 +1,19 @@
|
||||
package cn.iocoder.yudao.module.lab.dal.dataobject.barcode;
|
||||
|
||||
import cn.iocoder.yudao.framework.tenant.core.db.TenantBaseDO;
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
@TableName("lab_barcode_scan_profile")
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public class LabBarcodeScanProfileDO extends TenantBaseDO {
|
||||
|
||||
@TableId(type = IdType.ASSIGN_ID)
|
||||
private Long id;
|
||||
private String prefix;
|
||||
private String suffix;
|
||||
}
|
||||
@ -0,0 +1,27 @@
|
||||
package cn.iocoder.yudao.module.lab.dal.dataobject.barcode;
|
||||
|
||||
import cn.iocoder.yudao.framework.tenant.core.db.TenantBaseDO;
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
@TableName("lab_piece_barcode_audit")
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public class LabPieceBarcodeAuditDO extends TenantBaseDO {
|
||||
|
||||
@TableId(type = IdType.ASSIGN_ID)
|
||||
private Long id;
|
||||
private String action;
|
||||
private String barcode;
|
||||
private String barcodeNamespace;
|
||||
private Long barcodeId;
|
||||
private Long taskId;
|
||||
private String partNo;
|
||||
private String resolution;
|
||||
private String message;
|
||||
private String detailJson;
|
||||
private Long operatorId;
|
||||
}
|
||||
@ -0,0 +1,33 @@
|
||||
package cn.iocoder.yudao.module.lab.dal.dataobject.barcode;
|
||||
|
||||
import cn.iocoder.yudao.framework.tenant.core.db.TenantBaseDO;
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@TableName("lab_piece_barcode_binding")
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public class LabPieceBarcodeBindingDO extends TenantBaseDO {
|
||||
|
||||
@TableId(type = IdType.ASSIGN_ID)
|
||||
private Long id;
|
||||
private Long barcodeId;
|
||||
private String barcode;
|
||||
private Long taskId;
|
||||
private String partNo;
|
||||
private Long sampleId;
|
||||
private String bindingStatus;
|
||||
private String source;
|
||||
private String idempotencyKey;
|
||||
private Long boundBy;
|
||||
private LocalDateTime boundAt;
|
||||
private Long unboundBy;
|
||||
private LocalDateTime unboundAt;
|
||||
private String unbindReason;
|
||||
private Integer activeFlag;
|
||||
}
|
||||
@ -0,0 +1,26 @@
|
||||
package cn.iocoder.yudao.module.lab.dal.dataobject.barcode;
|
||||
|
||||
import cn.iocoder.yudao.framework.tenant.core.db.TenantBaseDO;
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
@TableName("lab_piece_barcode")
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public class LabPieceBarcodeDO extends TenantBaseDO {
|
||||
|
||||
@TableId(type = IdType.ASSIGN_ID)
|
||||
private Long id;
|
||||
private String barcode;
|
||||
private String barcodeNamespace;
|
||||
private Long sampleId;
|
||||
private String partNo;
|
||||
private String physicalSerialNo;
|
||||
private String status;
|
||||
private String source;
|
||||
private Integer activeFlag;
|
||||
private String remark;
|
||||
}
|
||||
@ -0,0 +1,19 @@
|
||||
package cn.iocoder.yudao.module.lab.dal.mysql.barcode;
|
||||
|
||||
import cn.iocoder.yudao.framework.mybatis.core.mapper.BaseMapperX;
|
||||
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
|
||||
import cn.iocoder.yudao.module.lab.dal.dataobject.barcode.LabBarcodeScanProfileDO;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Mapper
|
||||
public interface LabBarcodeScanProfileMapper extends BaseMapperX<LabBarcodeScanProfileDO> {
|
||||
|
||||
default LabBarcodeScanProfileDO selectCurrent() {
|
||||
List<LabBarcodeScanProfileDO> list = selectList(new LambdaQueryWrapperX<LabBarcodeScanProfileDO>()
|
||||
.orderByDesc(LabBarcodeScanProfileDO::getId)
|
||||
.last("LIMIT 1"));
|
||||
return list.isEmpty() ? null : list.get(0);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,21 @@
|
||||
package cn.iocoder.yudao.module.lab.dal.mysql.barcode;
|
||||
|
||||
import cn.iocoder.yudao.framework.common.pojo.PageResult;
|
||||
import cn.iocoder.yudao.framework.mybatis.core.mapper.BaseMapperX;
|
||||
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
|
||||
import cn.iocoder.yudao.module.lab.controller.admin.barcode.vo.LabBarcodeHistoryPageReqVO;
|
||||
import cn.iocoder.yudao.module.lab.dal.dataobject.barcode.LabPieceBarcodeAuditDO;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
@Mapper
|
||||
public interface LabPieceBarcodeAuditMapper extends BaseMapperX<LabPieceBarcodeAuditDO> {
|
||||
|
||||
default PageResult<LabPieceBarcodeAuditDO> selectPage(LabBarcodeHistoryPageReqVO reqVO) {
|
||||
return selectPage(reqVO, new LambdaQueryWrapperX<LabPieceBarcodeAuditDO>()
|
||||
.eqIfPresent(LabPieceBarcodeAuditDO::getBarcode, reqVO.getBarcode())
|
||||
.eqIfPresent(LabPieceBarcodeAuditDO::getBarcodeNamespace, reqVO.getBarcodeNamespace())
|
||||
.eqIfPresent(LabPieceBarcodeAuditDO::getTaskId, reqVO.getTaskId())
|
||||
.eqIfPresent(LabPieceBarcodeAuditDO::getAction, reqVO.getAction())
|
||||
.orderByDesc(LabPieceBarcodeAuditDO::getId));
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,31 @@
|
||||
package cn.iocoder.yudao.module.lab.dal.mysql.barcode;
|
||||
|
||||
import cn.iocoder.yudao.framework.mybatis.core.mapper.BaseMapperX;
|
||||
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
|
||||
import cn.iocoder.yudao.module.lab.dal.dataobject.barcode.LabPieceBarcodeBindingDO;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
@Mapper
|
||||
public interface LabPieceBarcodeBindingMapper extends BaseMapperX<LabPieceBarcodeBindingDO> {
|
||||
|
||||
default LabPieceBarcodeBindingDO selectActive(Long taskId, String partNo) {
|
||||
return selectOne(new LambdaQueryWrapperX<LabPieceBarcodeBindingDO>()
|
||||
.eq(LabPieceBarcodeBindingDO::getTaskId, taskId)
|
||||
.eq(LabPieceBarcodeBindingDO::getPartNo, partNo)
|
||||
.eq(LabPieceBarcodeBindingDO::getBindingStatus, "BOUND")
|
||||
.eq(LabPieceBarcodeBindingDO::getActiveFlag, 1));
|
||||
}
|
||||
|
||||
default LabPieceBarcodeBindingDO selectActiveByKey(String idempotencyKey) {
|
||||
return selectOne(new LambdaQueryWrapperX<LabPieceBarcodeBindingDO>()
|
||||
.eq(LabPieceBarcodeBindingDO::getIdempotencyKey, idempotencyKey)
|
||||
.eq(LabPieceBarcodeBindingDO::getActiveFlag, 1));
|
||||
}
|
||||
|
||||
default Long countActiveByBarcode(Long barcodeId) {
|
||||
return selectCount(new LambdaQueryWrapperX<LabPieceBarcodeBindingDO>()
|
||||
.eq(LabPieceBarcodeBindingDO::getBarcodeId, barcodeId)
|
||||
.eq(LabPieceBarcodeBindingDO::getBindingStatus, "BOUND")
|
||||
.eq(LabPieceBarcodeBindingDO::getActiveFlag, 1));
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,19 @@
|
||||
package cn.iocoder.yudao.module.lab.dal.mysql.barcode;
|
||||
|
||||
import cn.iocoder.yudao.framework.mybatis.core.mapper.BaseMapperX;
|
||||
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
|
||||
import cn.iocoder.yudao.module.lab.dal.dataobject.barcode.LabPieceBarcodeDO;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Mapper
|
||||
public interface LabPieceBarcodeMapper extends BaseMapperX<LabPieceBarcodeDO> {
|
||||
|
||||
default List<LabPieceBarcodeDO> selectByCode(String namespace, String barcode) {
|
||||
return selectList(new LambdaQueryWrapperX<LabPieceBarcodeDO>()
|
||||
.eq(LabPieceBarcodeDO::getBarcodeNamespace, namespace)
|
||||
.eq(LabPieceBarcodeDO::getBarcode, barcode)
|
||||
.orderByDesc(LabPieceBarcodeDO::getId));
|
||||
}
|
||||
}
|
||||
@ -130,4 +130,22 @@ public interface ErrorCodeConstants {
|
||||
ErrorCode INTEGRATION_EXECUTION_FORBIDDEN = new ErrorCode(1_070_007_022, "执行不属于当前接入方");
|
||||
ErrorCode INTEGRATION_TENANT_MISMATCH = new ErrorCode(1_070_007_023, "租户与接入方不一致");
|
||||
ErrorCode INTEGRATION_IDEMPOTENCY_CONFLICT = new ErrorCode(1_070_007_024, "幂等键已被不同请求使用");
|
||||
|
||||
ErrorCode BARCODE_EMPTY = new ErrorCode(1_070_008_000, "请扫描或输入条码");
|
||||
ErrorCode BARCODE_INVALID = new ErrorCode(1_070_008_001, "条码格式不正确");
|
||||
ErrorCode BARCODE_ALREADY_REGISTERED = new ErrorCode(1_070_008_002, "该条码已登记到其他零部件。请使用改绑,不能直接覆盖。");
|
||||
ErrorCode BARCODE_NOT_REGISTERED = new ErrorCode(1_070_008_003, "条码尚未登记");
|
||||
ErrorCode BARCODE_DISABLED = new ErrorCode(1_070_008_004, "条码已停用,不能绑定");
|
||||
ErrorCode BARCODE_PART_DISABLED = new ErrorCode(1_070_008_005, "零部件已停用,不能绑定");
|
||||
ErrorCode BARCODE_PART_NOT_IN_TASK = new ErrorCode(1_070_008_006, "该零部件不属于当前任务");
|
||||
ErrorCode BARCODE_TASK_READONLY = new ErrorCode(1_070_008_007, "任务已结束,只能查看,不能通过扫码继续绑定");
|
||||
ErrorCode BARCODE_MULTI_PIECE_BLOCKED = new ErrorCode(1_070_008_008, "当前任务的该零部件已关联另一件实物。现有扫描执行不能按实物分开,已阻止继续绑定。");
|
||||
ErrorCode BARCODE_IDEMPOTENCY_CONFLICT = new ErrorCode(1_070_008_009, "幂等键已被不同的条码或任务使用");
|
||||
ErrorCode BARCODE_REASON_REQUIRED = new ErrorCode(1_070_008_010, "请填写原因");
|
||||
ErrorCode BARCODE_REBIND_BLOCKED = new ErrorCode(1_070_008_011, "条码仍关联测量任务,请先解除关联后再改绑零部件");
|
||||
ErrorCode BARCODE_BINDING_NOT_FOUND = new ErrorCode(1_070_008_012, "没有可解除的条码关联");
|
||||
ErrorCode BARCODE_PART_NOT_FOUND = new ErrorCode(1_070_008_013, "零部件不存在,请先维护零部件主数据");
|
||||
ErrorCode BARCODE_PART_KEY_MISSING = new ErrorCode(1_070_008_014, "该零部件主数据没有零部件编号,请先维护编号");
|
||||
ErrorCode BARCODE_PROFILE_INVALID = new ErrorCode(1_070_008_015, "扫码前后缀配置不正确");
|
||||
ErrorCode BARCODE_FORBIDDEN = new ErrorCode(1_070_008_016, "没有查看测量任务的权限");
|
||||
}
|
||||
|
||||
@ -0,0 +1,48 @@
|
||||
package cn.iocoder.yudao.module.lab.service.barcode;
|
||||
|
||||
import cn.iocoder.yudao.module.lab.dal.dataobject.barcode.LabPieceBarcodeBindingDO;
|
||||
import cn.iocoder.yudao.module.lab.dal.dataobject.barcode.LabPieceBarcodeDO;
|
||||
import cn.iocoder.yudao.module.lab.dal.mysql.barcode.LabPieceBarcodeBindingMapper;
|
||||
import cn.iocoder.yudao.module.lab.dal.mysql.barcode.LabPieceBarcodeMapper;
|
||||
import jakarta.annotation.Resource;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.transaction.annotation.Propagation;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 冲突后在新事务里读取已提交的登记和关联,避免当前事务快照或会话缓存看不到并发写入。
|
||||
*/
|
||||
@Component
|
||||
public class LabBarcodeCommittedRead {
|
||||
|
||||
@Resource
|
||||
private LabPieceBarcodeBindingMapper bindingMapper;
|
||||
@Resource
|
||||
private LabPieceBarcodeMapper barcodeMapper;
|
||||
|
||||
@Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = true)
|
||||
public LabPieceBarcodeBindingDO selectActiveBinding(Long taskId, String partNo) {
|
||||
return bindingMapper.selectActive(taskId, partNo);
|
||||
}
|
||||
|
||||
@Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = true)
|
||||
public LabPieceBarcodeBindingDO selectActiveBindingByKey(String idempotencyKey) {
|
||||
if (idempotencyKey == null) {
|
||||
return null;
|
||||
}
|
||||
return bindingMapper.selectActiveByKey(idempotencyKey);
|
||||
}
|
||||
|
||||
@Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = true)
|
||||
public LabPieceBarcodeDO selectActiveBarcode(String namespace, String barcode) {
|
||||
List<LabPieceBarcodeDO> rows = barcodeMapper.selectByCode(namespace, barcode);
|
||||
for (LabPieceBarcodeDO row : rows) {
|
||||
if ("ACTIVE".equals(row.getStatus()) && Integer.valueOf(1).equals(row.getActiveFlag())) {
|
||||
return row;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,130 @@
|
||||
package cn.iocoder.yudao.module.lab.service.barcode;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* 条码规范化与任务匹配。只根据已经查到的登记和任务做判断,不猜测条码前缀对应的零部件。
|
||||
*/
|
||||
public final class LabBarcodeMatchRules {
|
||||
|
||||
public static final Set<String> TERMINAL = Set.of("COMPLETED", "CANCELLED", "FAILED");
|
||||
public static final String MULTI_PIECE_MESSAGE = "当前任务的该零部件已关联另一件实物。现有扫描执行不能按实物分开保存结果,已阻止继续绑定。";
|
||||
|
||||
private LabBarcodeMatchRules() {
|
||||
}
|
||||
|
||||
public record TaskSnap(long id, String status, boolean containsPart) {
|
||||
}
|
||||
|
||||
public record Decision(String resolution, Long chosenTaskId, boolean readOnly, boolean bindAllowed,
|
||||
String bindBlockReason, String message) {
|
||||
}
|
||||
|
||||
public static String normalize(String raw, String prefix, String suffix) {
|
||||
if (raw == null) {
|
||||
return "";
|
||||
}
|
||||
String value = raw.replace("\uFEFF", "").trim();
|
||||
while (!value.isEmpty() && isEdgeWhitespace(value.charAt(value.length() - 1))) {
|
||||
value = value.substring(0, value.length() - 1).trim();
|
||||
}
|
||||
while (!value.isEmpty() && isEdgeWhitespace(value.charAt(0))) {
|
||||
value = value.substring(1).trim();
|
||||
}
|
||||
if (prefix != null && !prefix.isEmpty() && value.startsWith(prefix) && value.length() > prefix.length()) {
|
||||
value = value.substring(prefix.length()).trim();
|
||||
}
|
||||
if (suffix != null && !suffix.isEmpty() && value.endsWith(suffix) && value.length() > suffix.length()) {
|
||||
value = value.substring(0, value.length() - suffix.length()).trim();
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
public static String invalidReason(String normalized) {
|
||||
if (normalized == null || normalized.isEmpty()) {
|
||||
return "EMPTY";
|
||||
}
|
||||
if (normalized.length() > 128) {
|
||||
return "TOO_LONG";
|
||||
}
|
||||
for (int i = 0; i < normalized.length(); i++) {
|
||||
char c = normalized.charAt(i);
|
||||
if (c < 32 || c == 127) {
|
||||
return "CONTROL";
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static boolean terminal(String status) {
|
||||
return status != null && TERMINAL.contains(status);
|
||||
}
|
||||
|
||||
public static Decision decide(String registry, boolean canReadTasks, Long currentTaskId, TaskSnap current,
|
||||
List<TaskSnap> partTasks, boolean otherPieceBound) {
|
||||
if ("ABSENT".equals(registry)) {
|
||||
return new Decision("UNREGISTERED", null, false, false, null,
|
||||
"这条码还没有登记。请选择已有零部件后再绑定,系统不会自动新建零部件。");
|
||||
}
|
||||
if ("DISABLED".equals(registry)) {
|
||||
return new Decision("DISABLED", null, true, false, "DISABLED", "条码已停用,不能自动绑定。");
|
||||
}
|
||||
if ("PART_DISABLED".equals(registry)) {
|
||||
return new Decision("PART_DISABLED", null, true, false, "PART_DISABLED", "零部件已停用,不能自动绑定。");
|
||||
}
|
||||
if (!canReadTasks) {
|
||||
return new Decision("FORBIDDEN", null, true, false, "FORBIDDEN", "没有查看测量任务的权限,条码未关联任务。");
|
||||
}
|
||||
List<TaskSnap> tasks = partTasks == null ? List.of() : partTasks;
|
||||
if (currentTaskId != null) {
|
||||
if (current == null || !current.containsPart()) {
|
||||
return new Decision("PART_NOT_IN_TASK", null, true, false, "PART_NOT_IN_TASK",
|
||||
"该零部件不属于当前任务。可以打开其他任务查看,当前任务不会被修改。");
|
||||
}
|
||||
if (terminal(current.status())) {
|
||||
return new Decision("TASK_READONLY", current.id(), true, false, "TASK_READONLY",
|
||||
"任务已结束,只能查看历史,不能通过扫码继续绑定或恢复执行。");
|
||||
}
|
||||
if (otherPieceBound) {
|
||||
return new Decision("MULTI_PIECE_BLOCKED", current.id(), true, false, "MULTI_PIECE_BLOCKED", MULTI_PIECE_MESSAGE);
|
||||
}
|
||||
return new Decision("UNIQUE_MATCH", current.id(), false, true, null, "已识别到当前测量任务。");
|
||||
}
|
||||
List<TaskSnap> active = new ArrayList<>();
|
||||
for (TaskSnap task : tasks) {
|
||||
if (task != null && task.containsPart() && !terminal(task.status())) {
|
||||
active.add(task);
|
||||
}
|
||||
}
|
||||
if (active.isEmpty()) {
|
||||
boolean history = tasks.stream().anyMatch(task -> task != null && task.containsPart() && terminal(task.status()));
|
||||
return new Decision("NO_ACTIVE_TASK", null, true, false, null, history
|
||||
? "已识别零部件。相关测量任务均已结束,只能查看历史,不会自动恢复。"
|
||||
: "已识别零部件,但没有可关联的测量任务。");
|
||||
}
|
||||
if (active.size() > 1) {
|
||||
return new Decision("MULTIPLE_TASKS", null, false, false, null, "此零部件存在多个可关联测量任务,请选择后再关联。");
|
||||
}
|
||||
TaskSnap only = active.get(0);
|
||||
if (otherPieceBound) {
|
||||
return new Decision("MULTI_PIECE_BLOCKED", only.id(), true, false, "MULTI_PIECE_BLOCKED", MULTI_PIECE_MESSAGE);
|
||||
}
|
||||
return new Decision("UNIQUE_MATCH", only.id(), false, true, null, "已识别到唯一测量任务。");
|
||||
}
|
||||
|
||||
public static String bindRefusal(Decision decision, boolean alreadyBound) {
|
||||
if (alreadyBound) {
|
||||
return null;
|
||||
}
|
||||
if (decision == null || !decision.bindAllowed()) {
|
||||
return decision == null || decision.bindBlockReason() == null ? decision == null ? "FORBIDDEN" : decision.resolution() : decision.bindBlockReason();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static boolean isEdgeWhitespace(char c) {
|
||||
return c == '\r' || c == '\n' || c == '\t' || c == ' ';
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,29 @@
|
||||
package cn.iocoder.yudao.module.lab.service.barcode;
|
||||
|
||||
import cn.iocoder.yudao.framework.common.pojo.PageResult;
|
||||
import cn.iocoder.yudao.module.lab.controller.admin.barcode.vo.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface LabBarcodeService {
|
||||
|
||||
LabBarcodeResolveRespVO resolve(LabBarcodeResolveReqVO reqVO);
|
||||
|
||||
LabBarcodeResolveRespVO register(LabBarcodeRegisterReqVO reqVO);
|
||||
|
||||
LabBarcodeResolveRespVO bindTask(LabBarcodeBindReqVO reqVO);
|
||||
|
||||
LabBarcodeResolveRespVO unbindTask(LabBarcodeUnbindReqVO reqVO);
|
||||
|
||||
LabBarcodeResolveRespVO rebind(LabBarcodeRebindReqVO reqVO);
|
||||
|
||||
LabBarcodeResolveRespVO disable(LabBarcodeDisableReqVO reqVO);
|
||||
|
||||
PageResult<LabBarcodeAuditRespVO> history(LabBarcodeHistoryPageReqVO reqVO);
|
||||
|
||||
List<LabBarcodePartOptionRespVO> searchParts(String keyword);
|
||||
|
||||
LabBarcodeProfileRespVO getProfile();
|
||||
|
||||
void saveProfile(LabBarcodeProfileReqVO reqVO);
|
||||
}
|
||||
@ -0,0 +1,941 @@
|
||||
package cn.iocoder.yudao.module.lab.service.barcode;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import cn.hutool.json.JSONObject;
|
||||
import cn.iocoder.yudao.framework.common.pojo.PageResult;
|
||||
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
|
||||
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
|
||||
import cn.iocoder.yudao.framework.security.core.service.SecurityFrameworkService;
|
||||
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
|
||||
import cn.iocoder.yudao.module.lab.controller.admin.barcode.vo.*;
|
||||
import cn.iocoder.yudao.module.lab.dal.dataobject.barcode.LabBarcodeScanProfileDO;
|
||||
import cn.iocoder.yudao.module.lab.dal.dataobject.barcode.LabPieceBarcodeAuditDO;
|
||||
import cn.iocoder.yudao.module.lab.dal.dataobject.barcode.LabPieceBarcodeBindingDO;
|
||||
import cn.iocoder.yudao.module.lab.dal.dataobject.barcode.LabPieceBarcodeDO;
|
||||
import cn.iocoder.yudao.module.lab.dal.dataobject.data.LabArtifactFileDO;
|
||||
import cn.iocoder.yudao.module.lab.dal.dataobject.document.LabReportDO;
|
||||
import cn.iocoder.yudao.module.lab.dal.dataobject.execution.LabExecutionDO;
|
||||
import cn.iocoder.yudao.module.lab.dal.dataobject.master.LabSampleDO;
|
||||
import cn.iocoder.yudao.module.lab.dal.dataobject.result.LabMeasurementBatchDO;
|
||||
import cn.iocoder.yudao.module.lab.dal.dataobject.task.LabTaskSampleDO;
|
||||
import cn.iocoder.yudao.module.lab.dal.dataobject.task.LabTestTaskDO;
|
||||
import cn.iocoder.yudao.module.lab.dal.mysql.barcode.LabBarcodeScanProfileMapper;
|
||||
import cn.iocoder.yudao.module.lab.dal.mysql.barcode.LabPieceBarcodeAuditMapper;
|
||||
import cn.iocoder.yudao.module.lab.dal.mysql.barcode.LabPieceBarcodeBindingMapper;
|
||||
import cn.iocoder.yudao.module.lab.dal.mysql.barcode.LabPieceBarcodeMapper;
|
||||
import cn.iocoder.yudao.module.lab.dal.mysql.data.LabArtifactFileMapper;
|
||||
import cn.iocoder.yudao.module.lab.dal.mysql.document.LabReportMapper;
|
||||
import cn.iocoder.yudao.module.lab.dal.mysql.execution.LabExecutionMapper;
|
||||
import cn.iocoder.yudao.module.lab.dal.mysql.master.LabSampleMapper;
|
||||
import cn.iocoder.yudao.module.lab.dal.mysql.result.LabMeasurementBatchMapper;
|
||||
import cn.iocoder.yudao.module.lab.dal.mysql.task.LabTaskSampleMapper;
|
||||
import cn.iocoder.yudao.module.lab.dal.mysql.task.LabTestTaskMapper;
|
||||
import cn.iocoder.yudao.module.lab.enums.LabMasterStatusEnum;
|
||||
import cn.iocoder.yudao.module.lab.enums.LabTaskStatusEnum;
|
||||
import cn.iocoder.yudao.module.lab.service.task.LabTestTaskService;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import jakarta.annotation.Resource;
|
||||
import org.springframework.dao.DataIntegrityViolationException;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Isolation;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
|
||||
import static cn.iocoder.yudao.module.lab.enums.ErrorCodeConstants.*;
|
||||
|
||||
@Service
|
||||
@Validated
|
||||
public class LabBarcodeServiceImpl implements LabBarcodeService {
|
||||
|
||||
private static final Set<String> SOURCES = Set.of("MANUAL", "IMPORT", "EXTERNAL");
|
||||
|
||||
@Resource
|
||||
private LabPieceBarcodeMapper barcodeMapper;
|
||||
@Resource
|
||||
private LabPieceBarcodeBindingMapper bindingMapper;
|
||||
@Resource
|
||||
private LabPieceBarcodeAuditMapper auditMapper;
|
||||
@Resource
|
||||
private LabBarcodeScanProfileMapper profileMapper;
|
||||
@Resource
|
||||
private LabSampleMapper sampleMapper;
|
||||
@Resource
|
||||
private LabTestTaskMapper taskMapper;
|
||||
@Resource
|
||||
private LabTaskSampleMapper taskSampleMapper;
|
||||
@Resource
|
||||
private LabExecutionMapper executionMapper;
|
||||
@Resource
|
||||
private LabArtifactFileMapper artifactMapper;
|
||||
@Resource
|
||||
private LabMeasurementBatchMapper batchMapper;
|
||||
@Resource
|
||||
private LabReportMapper reportMapper;
|
||||
@Resource
|
||||
private org.springframework.jdbc.core.JdbcTemplate jdbc;
|
||||
@Resource
|
||||
private LabTestTaskService taskService;
|
||||
@Resource
|
||||
private SecurityFrameworkService securityFrameworkService;
|
||||
@Resource
|
||||
private LabBarcodeCommittedRead committedRead;
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public LabBarcodeResolveRespVO resolve(LabBarcodeResolveReqVO reqVO) {
|
||||
return identify(reqVO, true, false);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class, isolation = Isolation.READ_COMMITTED)
|
||||
public LabBarcodeResolveRespVO register(LabBarcodeRegisterReqVO reqVO) {
|
||||
String barcode = requireBarcode(reqVO.getBarcode(), reqVO.isBarcodeNormalized());
|
||||
String namespace = namespace(reqVO.getBarcodeNamespace());
|
||||
LabSampleDO sample = requireEnabledSample(reqVO.getSampleId());
|
||||
String source = source(reqVO.getSource());
|
||||
String serial = blankNull(reqVO.getPhysicalSerialNo(), 128);
|
||||
Registry registry = loadRegistry(namespace, barcode);
|
||||
if (registry.row() != null && "ACTIVE".equals(registry.row().getStatus())) {
|
||||
if (sample.getId().equals(registry.row().getSampleId())) {
|
||||
updateSerial(registry.row().getId(), serial);
|
||||
Long auditId = audit("REGISTER_REPEAT", barcode, namespace, registry.row().getId(), null, sample.getPartNo(),
|
||||
"UNIQUE_MATCH", "条码已登记到该零部件,未重复建档", null);
|
||||
return finish(barcode, namespace, reqVO.getCurrentTaskId(), false, false, auditId);
|
||||
}
|
||||
throw exception(BARCODE_ALREADY_REGISTERED);
|
||||
}
|
||||
if (registry.row() != null && "DISABLED".equals(registry.row().getStatus())) {
|
||||
if (!sample.getId().equals(registry.row().getSampleId())) {
|
||||
throw exception(BARCODE_ALREADY_REGISTERED);
|
||||
}
|
||||
barcodeMapper.update(null, new LambdaUpdateWrapper<LabPieceBarcodeDO>()
|
||||
.eq(LabPieceBarcodeDO::getId, registry.row().getId())
|
||||
.set(LabPieceBarcodeDO::getStatus, "ACTIVE")
|
||||
.set(LabPieceBarcodeDO::getActiveFlag, 1)
|
||||
.set(LabPieceBarcodeDO::getSource, source)
|
||||
.set(serial != null, LabPieceBarcodeDO::getPhysicalSerialNo, serial));
|
||||
Long auditId = audit("REGISTER", barcode, namespace, registry.row().getId(), null, sample.getPartNo(),
|
||||
"UNIQUE_MATCH", "已重新启用原条码登记", null);
|
||||
return finish(barcode, namespace, reqVO.getCurrentTaskId(), false, true, auditId);
|
||||
}
|
||||
LabPieceBarcodeDO row = new LabPieceBarcodeDO();
|
||||
row.setBarcode(barcode);
|
||||
row.setBarcodeNamespace(namespace);
|
||||
row.setSampleId(sample.getId());
|
||||
row.setPartNo(sample.getPartNo().trim());
|
||||
row.setPhysicalSerialNo(serial);
|
||||
row.setStatus("ACTIVE");
|
||||
row.setSource(source);
|
||||
row.setActiveFlag(1);
|
||||
try {
|
||||
barcodeMapper.insert(row);
|
||||
} catch (DataIntegrityViolationException ex) {
|
||||
LabPieceBarcodeDO again = committedRead.selectActiveBarcode(namespace, barcode);
|
||||
if (again != null && sample.getId().equals(again.getSampleId())) {
|
||||
Long auditId = audit("REGISTER_REPEAT", barcode, namespace, again.getId(), null, sample.getPartNo(),
|
||||
"UNIQUE_MATCH", "条码已登记到该零部件,未重复建档", null);
|
||||
return finish(barcode, namespace, reqVO.getCurrentTaskId(), false, false, auditId);
|
||||
}
|
||||
throw exception(BARCODE_ALREADY_REGISTERED);
|
||||
}
|
||||
Long auditId = audit("REGISTER", barcode, namespace, row.getId(), null, sample.getPartNo(),
|
||||
"UNIQUE_MATCH", "已把条码登记到零部件", null);
|
||||
return finish(barcode, namespace, reqVO.getCurrentTaskId(), false, true, auditId);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class, isolation = Isolation.READ_COMMITTED)
|
||||
public LabBarcodeResolveRespVO bindTask(LabBarcodeBindReqVO reqVO) {
|
||||
String barcode = requireBarcode(reqVO.getBarcode(), reqVO.isBarcodeNormalized());
|
||||
String namespace = namespace(reqVO.getBarcodeNamespace());
|
||||
String key = idempotency(reqVO.getIdempotencyKey());
|
||||
Registry registry = requireActive(namespace, barcode);
|
||||
LabTestTaskDO task = requireTask(reqVO.getTaskId());
|
||||
String partNo = registry.sample().getPartNo().trim();
|
||||
boolean contains = taskContains(task, partNo);
|
||||
LabBarcodeMatchRules.TaskSnap snap = new LabBarcodeMatchRules.TaskSnap(task.getId(), task.getStatus(), contains);
|
||||
boolean other = contains && !LabBarcodeMatchRules.terminal(task.getStatus()) && otherPiece(task.getId(), partNo, barcode);
|
||||
LabBarcodeMatchRules.Decision decision = LabBarcodeMatchRules.decide("ACTIVE", canReadTasks(), task.getId(), snap, List.of(snap), other);
|
||||
LabPieceBarcodeBindingDO existing = bindingMapper.selectActive(task.getId(), partNo);
|
||||
boolean already = existing != null && barcode.equals(existing.getBarcode());
|
||||
reject(LabBarcodeMatchRules.bindRefusal(decision, already));
|
||||
if (key != null) {
|
||||
LabPieceBarcodeBindingDO byKey = bindingMapper.selectActiveByKey(key);
|
||||
if (byKey != null && !sameBinding(byKey, barcode, task.getId(), partNo)) {
|
||||
throw exception(BARCODE_IDEMPOTENCY_CONFLICT);
|
||||
}
|
||||
if (byKey != null) {
|
||||
already = true;
|
||||
existing = byKey;
|
||||
}
|
||||
}
|
||||
if (already) {
|
||||
Long auditId = audit("BIND_REPEAT", barcode, namespace, registry.row().getId(), task.getId(), partNo,
|
||||
"UNIQUE_MATCH", "重复扫码,未新增任务关联", detail(reqVO.getStationId(), null));
|
||||
LabBarcodeResolveRespVO view = finish(barcode, namespace, task.getId(), false, false, auditId);
|
||||
view.setMessage("该条码已关联此测量任务。");
|
||||
view.setRecognitionLabel("已绑定");
|
||||
view.setBound(true);
|
||||
return view;
|
||||
}
|
||||
LabPieceBarcodeBindingDO row = new LabPieceBarcodeBindingDO();
|
||||
row.setBarcodeId(registry.row().getId());
|
||||
row.setBarcode(barcode);
|
||||
row.setTaskId(task.getId());
|
||||
row.setPartNo(partNo);
|
||||
row.setSampleId(registry.sample().getId());
|
||||
row.setBindingStatus("BOUND");
|
||||
row.setSource("SCAN");
|
||||
row.setIdempotencyKey(key);
|
||||
row.setBoundBy(SecurityFrameworkUtils.getLoginUserId());
|
||||
row.setBoundAt(LocalDateTime.now());
|
||||
row.setActiveFlag(1);
|
||||
try {
|
||||
bindingMapper.insert(row);
|
||||
} catch (DataIntegrityViolationException ex) {
|
||||
LabPieceBarcodeBindingDO raced = committedRead.selectActiveBinding(task.getId(), partNo);
|
||||
if (raced != null && barcode.equals(raced.getBarcode())) {
|
||||
Long auditId = audit("BIND_REPEAT", barcode, namespace, registry.row().getId(), task.getId(), partNo,
|
||||
"UNIQUE_MATCH", "重复扫码,未新增任务关联", null);
|
||||
return repeatBinding(barcode, namespace, task.getId(), auditId);
|
||||
}
|
||||
if (raced != null) {
|
||||
throw exception(BARCODE_MULTI_PIECE_BLOCKED);
|
||||
}
|
||||
if (key != null) {
|
||||
LabPieceBarcodeBindingDO byKey = committedRead.selectActiveBindingByKey(key);
|
||||
if (byKey != null && sameBinding(byKey, barcode, task.getId(), partNo)) {
|
||||
return repeatBinding(barcode, namespace, task.getId(), null);
|
||||
}
|
||||
if (byKey != null) {
|
||||
throw exception(BARCODE_IDEMPOTENCY_CONFLICT);
|
||||
}
|
||||
}
|
||||
throw exception(BARCODE_MULTI_PIECE_BLOCKED);
|
||||
}
|
||||
Map<String, Object> content = new LinkedHashMap<>();
|
||||
content.put("barcode", barcode);
|
||||
content.put("partNo", partNo);
|
||||
taskService.recordEvent(task.getId(), "BARCODE_BOUND", content);
|
||||
Long auditId = audit("BIND", barcode, namespace, registry.row().getId(), task.getId(), partNo,
|
||||
"UNIQUE_MATCH", "已关联测量任务", detail(reqVO.getStationId(), null));
|
||||
LabBarcodeResolveRespVO view = finish(barcode, namespace, task.getId(), false, false, auditId);
|
||||
view.setMessage("已关联测量任务。扫码没有改变任务状态,也没有发布扫描执行。");
|
||||
view.setRecognitionLabel("已绑定");
|
||||
view.setBound(true);
|
||||
view.setNextAction("OPEN_TASK");
|
||||
return view;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public LabBarcodeResolveRespVO unbindTask(LabBarcodeUnbindReqVO reqVO) {
|
||||
String barcode = requireBarcode(reqVO.getBarcode(), reqVO.isBarcodeNormalized());
|
||||
String namespace = namespace(reqVO.getBarcodeNamespace());
|
||||
String reason = reason(reqVO.getReason());
|
||||
Registry registry = loadRegistry(namespace, barcode);
|
||||
if (registry.row() == null) {
|
||||
throw exception(BARCODE_NOT_REGISTERED);
|
||||
}
|
||||
LabTestTaskDO task = requireTask(reqVO.getTaskId());
|
||||
LabPieceBarcodeBindingDO binding = bindingMapper.selectActive(task.getId(), registry.row().getPartNo());
|
||||
if (binding == null || !barcode.equals(binding.getBarcode())) {
|
||||
throw exception(BARCODE_BINDING_NOT_FOUND);
|
||||
}
|
||||
bindingMapper.update(null, new LambdaUpdateWrapper<LabPieceBarcodeBindingDO>()
|
||||
.eq(LabPieceBarcodeBindingDO::getId, binding.getId())
|
||||
.set(LabPieceBarcodeBindingDO::getBindingStatus, "UNBOUND")
|
||||
.set(LabPieceBarcodeBindingDO::getActiveFlag, null)
|
||||
.set(LabPieceBarcodeBindingDO::getUnbindReason, reason)
|
||||
.set(LabPieceBarcodeBindingDO::getUnboundBy, SecurityFrameworkUtils.getLoginUserId())
|
||||
.set(LabPieceBarcodeBindingDO::getUnboundAt, LocalDateTime.now()));
|
||||
Map<String, Object> content = new LinkedHashMap<>();
|
||||
content.put("barcode", barcode);
|
||||
content.put("partNo", binding.getPartNo());
|
||||
content.put("reason", reason);
|
||||
taskService.recordEvent(task.getId(), "BARCODE_UNBOUND", content);
|
||||
Long auditId = audit("UNBIND", barcode, namespace, registry.row().getId(), task.getId(), binding.getPartNo(),
|
||||
"UNBOUND", "已解除任务关联,原测量结果未改动", detail(null, reason));
|
||||
return finish(barcode, namespace, task.getId(), false, false, auditId);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public LabBarcodeResolveRespVO rebind(LabBarcodeRebindReqVO reqVO) {
|
||||
String barcode = requireBarcode(reqVO.getBarcode(), reqVO.isBarcodeNormalized());
|
||||
String namespace = namespace(reqVO.getBarcodeNamespace());
|
||||
String reason = reason(reqVO.getReason());
|
||||
LabSampleDO sample = requireEnabledSample(reqVO.getSampleId());
|
||||
Registry registry = loadRegistry(namespace, barcode);
|
||||
if (registry.row() == null) {
|
||||
throw exception(BARCODE_NOT_REGISTERED);
|
||||
}
|
||||
String oldPart = StrUtil.blankToDefault(registry.row().getPartNo(), "");
|
||||
String newPart = sample.getPartNo().trim();
|
||||
if (!oldPart.equals(newPart) && bindingMapper.countActiveByBarcode(registry.row().getId()) > 0) {
|
||||
throw exception(BARCODE_REBIND_BLOCKED);
|
||||
}
|
||||
String serial = blankNull(reqVO.getPhysicalSerialNo(), 128);
|
||||
LambdaUpdateWrapper<LabPieceBarcodeDO> update = new LambdaUpdateWrapper<LabPieceBarcodeDO>()
|
||||
.eq(LabPieceBarcodeDO::getId, registry.row().getId())
|
||||
.set(LabPieceBarcodeDO::getSampleId, sample.getId())
|
||||
.set(LabPieceBarcodeDO::getPartNo, newPart)
|
||||
.set(LabPieceBarcodeDO::getStatus, "ACTIVE")
|
||||
.set(LabPieceBarcodeDO::getActiveFlag, 1);
|
||||
if (serial != null) {
|
||||
update.set(LabPieceBarcodeDO::getPhysicalSerialNo, serial);
|
||||
}
|
||||
barcodeMapper.update(null, update);
|
||||
if (oldPart.equals(newPart)) {
|
||||
bindingMapper.update(null, new LambdaUpdateWrapper<LabPieceBarcodeBindingDO>()
|
||||
.eq(LabPieceBarcodeBindingDO::getBarcodeId, registry.row().getId())
|
||||
.eq(LabPieceBarcodeBindingDO::getActiveFlag, 1)
|
||||
.set(LabPieceBarcodeBindingDO::getSampleId, sample.getId()));
|
||||
}
|
||||
JSONObject extra = new JSONObject();
|
||||
extra.set("fromPartNo", oldPart);
|
||||
extra.set("toPartNo", newPart);
|
||||
extra.set("reason", reason);
|
||||
Long auditId = audit("REBIND", barcode, namespace, registry.row().getId(), null, newPart,
|
||||
"REBIND", "已改绑零部件,旧登记保留在审计中", StrUtil.sub(extra.toString(), 0, 1000));
|
||||
return finish(barcode, namespace, null, false, false, auditId);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public LabBarcodeResolveRespVO disable(LabBarcodeDisableReqVO reqVO) {
|
||||
String barcode = requireBarcode(reqVO.getBarcode(), reqVO.isBarcodeNormalized());
|
||||
String namespace = namespace(reqVO.getBarcodeNamespace());
|
||||
String reason = reason(reqVO.getReason());
|
||||
Registry registry = loadRegistry(namespace, barcode);
|
||||
if (registry.row() == null) {
|
||||
throw exception(BARCODE_NOT_REGISTERED);
|
||||
}
|
||||
if (!"DISABLED".equals(registry.row().getStatus())) {
|
||||
barcodeMapper.update(null, new LambdaUpdateWrapper<LabPieceBarcodeDO>()
|
||||
.eq(LabPieceBarcodeDO::getId, registry.row().getId())
|
||||
.set(LabPieceBarcodeDO::getStatus, "DISABLED")
|
||||
.set(LabPieceBarcodeDO::getActiveFlag, null)
|
||||
.set(LabPieceBarcodeDO::getRemark, reason));
|
||||
}
|
||||
Long auditId = audit("DISABLE", barcode, namespace, registry.row().getId(), null, registry.row().getPartNo(),
|
||||
"DISABLED", "条码已停用。若要换到另一件实物,请先解除原任务关联。", detail(null, reason));
|
||||
return finish(barcode, namespace, null, false, false, auditId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public PageResult<LabBarcodeAuditRespVO> history(LabBarcodeHistoryPageReqVO reqVO) {
|
||||
if (StrUtil.isNotBlank(reqVO.getBarcode())) {
|
||||
reqVO.setBarcode(requireBarcode(reqVO.getBarcode(), reqVO.isBarcodeNormalized()));
|
||||
}
|
||||
if (StrUtil.isNotBlank(reqVO.getBarcodeNamespace())) {
|
||||
reqVO.setBarcodeNamespace(namespace(reqVO.getBarcodeNamespace()));
|
||||
}
|
||||
return BeanUtils.toBean(auditMapper.selectPage(reqVO), LabBarcodeAuditRespVO.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<LabBarcodePartOptionRespVO> searchParts(String keyword) {
|
||||
String key = StrUtil.blankToDefault(keyword, "").trim();
|
||||
LambdaQueryWrapperX<LabSampleDO> query = new LambdaQueryWrapperX<LabSampleDO>()
|
||||
.eq(LabSampleDO::getStatus, LabMasterStatusEnum.ENABLED.getStatus())
|
||||
.orderByDesc(LabSampleDO::getId)
|
||||
.last("LIMIT 20");
|
||||
if (StrUtil.isNotBlank(key)) {
|
||||
query.and(wrapper -> wrapper.like(LabSampleDO::getPartNo, key)
|
||||
.or().like(LabSampleDO::getSampleName, key)
|
||||
.or().like(LabSampleDO::getSampleCode, key));
|
||||
}
|
||||
List<LabBarcodePartOptionRespVO> result = new ArrayList<>();
|
||||
for (LabSampleDO sample : sampleMapper.selectList(query)) {
|
||||
if (StrUtil.isBlank(sample.getPartNo())) {
|
||||
continue;
|
||||
}
|
||||
LabBarcodePartOptionRespVO item = new LabBarcodePartOptionRespVO();
|
||||
item.setSampleId(sample.getId());
|
||||
item.setPartNo(sample.getPartNo().trim());
|
||||
item.setPartName(sample.getSampleName());
|
||||
item.setSampleCode(sample.getSampleCode());
|
||||
item.setVehicleModel(sample.getVehicleModel());
|
||||
item.setProjectName(sample.getProjectName());
|
||||
item.setStatus(sample.getStatus());
|
||||
result.add(item);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public LabBarcodeProfileRespVO getProfile() {
|
||||
LabBarcodeScanProfileDO row = profileMapper.selectCurrent();
|
||||
LabBarcodeProfileRespVO resp = new LabBarcodeProfileRespVO();
|
||||
resp.setPrefix(row == null ? "" : StrUtil.blankToDefault(row.getPrefix(), ""));
|
||||
resp.setSuffix(row == null ? "" : StrUtil.blankToDefault(row.getSuffix(), ""));
|
||||
return resp;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void saveProfile(LabBarcodeProfileReqVO reqVO) {
|
||||
String prefix = affix(reqVO.getPrefix());
|
||||
String suffix = affix(reqVO.getSuffix());
|
||||
LabBarcodeScanProfileDO row = profileMapper.selectCurrent();
|
||||
if (row == null) {
|
||||
row = new LabBarcodeScanProfileDO();
|
||||
row.setPrefix(prefix);
|
||||
row.setSuffix(suffix);
|
||||
profileMapper.insert(row);
|
||||
return;
|
||||
}
|
||||
profileMapper.update(null, new LambdaUpdateWrapper<LabBarcodeScanProfileDO>()
|
||||
.eq(LabBarcodeScanProfileDO::getId, row.getId())
|
||||
.set(LabBarcodeScanProfileDO::getPrefix, prefix)
|
||||
.set(LabBarcodeScanProfileDO::getSuffix, suffix));
|
||||
}
|
||||
|
||||
private LabBarcodeResolveRespVO repeatBinding(String barcode, String namespace, Long taskId, Long auditId) {
|
||||
LabBarcodeResolveRespVO view = finish(barcode, namespace, taskId, false, false, auditId);
|
||||
view.setMessage("该条码已关联此测量任务。");
|
||||
view.setRecognitionLabel("已绑定");
|
||||
view.setBound(true);
|
||||
view.setNextAction("OPEN_TASK");
|
||||
return view;
|
||||
}
|
||||
|
||||
private LabBarcodeResolveRespVO finish(String barcode, String namespace, Long currentTaskId, boolean auditResolve,
|
||||
boolean registeredNow, Long auditId) {
|
||||
LabBarcodeResolveReqVO req = new LabBarcodeResolveReqVO();
|
||||
req.setBarcode(barcode);
|
||||
req.setBarcodeNormalized(true);
|
||||
req.setBarcodeNamespace(namespace);
|
||||
req.setCurrentTaskId(currentTaskId);
|
||||
LabBarcodeResolveRespVO view = identify(req, auditResolve, registeredNow);
|
||||
if (auditId != null) {
|
||||
view.setAuditId(auditId);
|
||||
}
|
||||
return view;
|
||||
}
|
||||
|
||||
private LabBarcodeResolveRespVO identify(LabBarcodeResolveReqVO reqVO, boolean auditResolve, boolean registeredNow) {
|
||||
String[] affix = affixes();
|
||||
String barcode = LabBarcodeMatchRules.normalize(reqVO.getBarcode(), reqVO.isBarcodeNormalized() ? "" : affix[0], reqVO.isBarcodeNormalized() ? "" : affix[1]);
|
||||
String invalid = LabBarcodeMatchRules.invalidReason(barcode);
|
||||
LabBarcodeResolveRespVO resp = new LabBarcodeResolveRespVO();
|
||||
resp.setBarcode(barcode);
|
||||
resp.setRegisteredNow(registeredNow);
|
||||
if (invalid != null) {
|
||||
resp.setResolution("INVALID");
|
||||
resp.setRegistryStatus("ABSENT");
|
||||
resp.setRecognized(false);
|
||||
resp.setBound(false);
|
||||
resp.setReadOnly(false);
|
||||
resp.setBindAllowed(false);
|
||||
resp.setRecognitionLabel("未识别");
|
||||
resp.setNextAction("NONE");
|
||||
resp.setMessage("EMPTY".equals(invalid) ? "请扫描或输入条码" : "条码格式不正确");
|
||||
if (auditResolve) {
|
||||
resp.setAuditId(audit("RESOLVE_FAIL", StrUtil.sub(StrUtil.blankToDefault(reqVO.getBarcode(), ""), 0, 128),
|
||||
null, null, reqVO.getCurrentTaskId(), null, "INVALID", resp.getMessage(), detail(reqVO.getStationId(), null)));
|
||||
}
|
||||
return resp;
|
||||
}
|
||||
String namespace = namespace(reqVO.getBarcodeNamespace());
|
||||
resp.setBarcodeNamespace(namespace);
|
||||
LabTestTaskDO current = reqVO.getCurrentTaskId() == null ? null : requireTask(reqVO.getCurrentTaskId());
|
||||
Registry registry = loadRegistry(namespace, barcode);
|
||||
boolean canRead = canReadTasks();
|
||||
String partNo = registry.sample() == null ? "" : StrUtil.blankToDefault(registry.sample().getPartNo(), "").trim();
|
||||
List<LabTestTaskDO> tasks = canRead && "ACTIVE".equals(registry.state()) && StrUtil.isNotBlank(partNo)
|
||||
? tasksForPart(partNo) : List.of();
|
||||
boolean contains = current != null && canRead && "ACTIVE".equals(registry.state()) && taskContains(current, partNo);
|
||||
LabBarcodeMatchRules.TaskSnap currentSnap = current == null ? null
|
||||
: new LabBarcodeMatchRules.TaskSnap(current.getId(), current.getStatus(), contains);
|
||||
List<LabBarcodeMatchRules.TaskSnap> snaps = tasks.stream()
|
||||
.map(task -> new LabBarcodeMatchRules.TaskSnap(task.getId(), task.getStatus(), true))
|
||||
.toList();
|
||||
LabBarcodeMatchRules.Decision draft = LabBarcodeMatchRules.decide(registry.state(), canRead,
|
||||
current == null ? null : current.getId(), currentSnap, snaps, false);
|
||||
boolean other = false;
|
||||
if (draft.chosenTaskId() != null && "ACTIVE".equals(registry.state()) && canRead && StrUtil.isNotBlank(partNo)) {
|
||||
other = otherPiece(draft.chosenTaskId(), partNo, barcode);
|
||||
}
|
||||
LabBarcodeMatchRules.Decision decision = other
|
||||
? LabBarcodeMatchRules.decide(registry.state(), canRead, current == null ? null : current.getId(), currentSnap, snaps, true)
|
||||
: draft;
|
||||
resp.setResolution(decision.resolution());
|
||||
resp.setRegistryStatus(registry.state());
|
||||
resp.setReadOnly(decision.readOnly());
|
||||
resp.setBindAllowed(decision.bindAllowed());
|
||||
resp.setMessage(decision.message());
|
||||
resp.setChosenTaskId(decision.chosenTaskId());
|
||||
resp.setRecognized("ACTIVE".equals(registry.state()));
|
||||
fillPart(resp, registry);
|
||||
if (registry.sample() == null && registry.row() != null && "PART_DISABLED".equals(registry.state())) {
|
||||
resp.setMessage("关联的零部件主数据不存在或已停用,不能自动绑定。");
|
||||
}
|
||||
fillTasks(resp, decision, tasks, partNo);
|
||||
boolean bound = false;
|
||||
if (decision.chosenTaskId() != null && StrUtil.isNotBlank(partNo)) {
|
||||
LabPieceBarcodeBindingDO binding = bindingMapper.selectActive(decision.chosenTaskId(), partNo);
|
||||
bound = binding != null && barcode.equals(binding.getBarcode());
|
||||
if (bound) {
|
||||
resp.setBindingId(binding.getId());
|
||||
resp.setBound(true);
|
||||
resp.setRecognitionLabel("已绑定");
|
||||
if ("UNIQUE_MATCH".equals(decision.resolution())) {
|
||||
resp.setMessage("该条码已关联此测量任务。");
|
||||
resp.setNextAction("OPEN_TASK");
|
||||
}
|
||||
} else if (binding != null && "MULTI_PIECE_BLOCKED".equals(decision.resolution())) {
|
||||
resp.setBlockingBarcode(binding.getBarcode());
|
||||
}
|
||||
}
|
||||
resp.setBound(bound);
|
||||
if (!bound) {
|
||||
resp.setRecognitionLabel(label(registry.state(), decision.resolution()));
|
||||
}
|
||||
resp.setPieceTraceMode(!resp.getRecognized() ? null : "MULTI_PIECE_BLOCKED".equals(decision.resolution()) ? "BLOCKED" : "IDENTITY_ONLY");
|
||||
if (resp.getNextAction() == null) {
|
||||
resp.setNextAction(nextAction(decision.resolution()));
|
||||
}
|
||||
if (decision.chosenTaskId() != null && resp.getRecognized() && canRead) {
|
||||
fillPlans(resp, decision.chosenTaskId(), partNo);
|
||||
}
|
||||
if (auditResolve) {
|
||||
String action = "INVALID".equals(decision.resolution()) || "UNREGISTERED".equals(decision.resolution())
|
||||
|| "FORBIDDEN".equals(decision.resolution()) || "DISABLED".equals(decision.resolution())
|
||||
|| "PART_DISABLED".equals(decision.resolution()) ? "RESOLVE_FAIL" : "RESOLVE";
|
||||
resp.setAuditId(audit(action, barcode, namespace, registry.row() == null ? null : registry.row().getId(),
|
||||
decision.chosenTaskId(), StrUtil.blankToDefault(partNo, null), decision.resolution(), decision.message(),
|
||||
detail(reqVO.getStationId(), null)));
|
||||
}
|
||||
return resp;
|
||||
}
|
||||
|
||||
private void fillPart(LabBarcodeResolveRespVO resp, Registry registry) {
|
||||
LabSampleDO sample = registry.sample();
|
||||
if (sample == null && registry.row() == null) {
|
||||
return;
|
||||
}
|
||||
LabBarcodeResolveRespVO.Part part = new LabBarcodeResolveRespVO.Part();
|
||||
if (sample != null) {
|
||||
part.setPartId(sample.getId());
|
||||
part.setSampleId(sample.getId());
|
||||
part.setPartNo(StrUtil.blankToDefault(sample.getPartNo(), "").trim());
|
||||
part.setPartName(sample.getSampleName());
|
||||
part.setSampleCode(sample.getSampleCode());
|
||||
part.setVehicleModel(sample.getVehicleModel());
|
||||
part.setProjectName(sample.getProjectName());
|
||||
part.setStatus(sample.getStatus());
|
||||
} else {
|
||||
part.setPartNo(registry.row().getPartNo());
|
||||
part.setSampleId(registry.row().getSampleId());
|
||||
part.setPartId(registry.row().getSampleId());
|
||||
}
|
||||
if (registry.row() != null) {
|
||||
part.setPhysicalSerialNo(registry.row().getPhysicalSerialNo());
|
||||
}
|
||||
resp.setPart(part);
|
||||
}
|
||||
|
||||
private void fillTasks(LabBarcodeResolveRespVO resp, LabBarcodeMatchRules.Decision decision,
|
||||
List<LabTestTaskDO> tasks, String partNo) {
|
||||
if ("FORBIDDEN".equals(decision.resolution()) || "UNREGISTERED".equals(decision.resolution())
|
||||
|| "DISABLED".equals(decision.resolution()) || "PART_DISABLED".equals(decision.resolution())
|
||||
|| "INVALID".equals(decision.resolution())) {
|
||||
resp.setCandidateTasks(List.of());
|
||||
resp.setHistoryTasks(List.of());
|
||||
resp.setChosenTaskId("FORBIDDEN".equals(decision.resolution()) ? null : resp.getChosenTaskId());
|
||||
return;
|
||||
}
|
||||
List<LabBarcodeResolveRespVO.Task> active = new ArrayList<>();
|
||||
List<LabBarcodeResolveRespVO.Task> history = new ArrayList<>();
|
||||
for (LabTestTaskDO task : tasks) {
|
||||
LabBarcodeResolveRespVO.Task item = toTask(task, partNo);
|
||||
if (LabBarcodeMatchRules.terminal(task.getStatus())) {
|
||||
history.add(item);
|
||||
} else {
|
||||
active.add(item);
|
||||
}
|
||||
}
|
||||
if ("MULTIPLE_TASKS".equals(decision.resolution()) || "PART_NOT_IN_TASK".equals(decision.resolution())) {
|
||||
resp.setCandidateTasks(active);
|
||||
} else if (decision.chosenTaskId() != null) {
|
||||
List<LabBarcodeResolveRespVO.Task> chosen = new ArrayList<>();
|
||||
for (LabBarcodeResolveRespVO.Task item : active) {
|
||||
if (decision.chosenTaskId().equals(item.getTaskId())) {
|
||||
chosen.add(item);
|
||||
}
|
||||
}
|
||||
for (LabBarcodeResolveRespVO.Task item : history) {
|
||||
if (decision.chosenTaskId().equals(item.getTaskId())) {
|
||||
chosen.add(item);
|
||||
}
|
||||
}
|
||||
if (chosen.isEmpty()) {
|
||||
LabTestTaskDO task = taskMapper.selectById(decision.chosenTaskId());
|
||||
if (task != null) {
|
||||
chosen.add(toTask(task, partNo));
|
||||
}
|
||||
}
|
||||
resp.setCandidateTasks(chosen);
|
||||
} else {
|
||||
resp.setCandidateTasks(List.of());
|
||||
}
|
||||
resp.setHistoryTasks(history);
|
||||
}
|
||||
|
||||
/** Barcode navigation reads existing executions; it never dispatches scans or computations. */
|
||||
private void fillPlans(LabBarcodeResolveRespVO resp, Long taskId, String partNo) {
|
||||
long tenant = cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder.getRequiredTenantId();
|
||||
var task = taskMapper.selectById(taskId);
|
||||
List<LabBarcodeResolveRespVO.Plan> plans = new ArrayList<>();
|
||||
var batches = batchMapper.selectListByTaskId(taskId);
|
||||
var reports = reportMapper.selectListByTaskId(taskId);
|
||||
for (var execution : executionMapper.selectListByTaskId(taskId)) {
|
||||
if (!"SCAN_ONLY".equals(task.getProcessType()) && StrUtil.isNotBlank(execution.getPartTypeCode()) && !partNo.equals(execution.getPartTypeCode().trim())) continue;
|
||||
var plan = new LabBarcodeResolveRespVO.Plan();
|
||||
plan.setExecutionId(execution.getId());
|
||||
plan.setExecutionNo(execution.getExecutionNo());
|
||||
plan.setExecutionStatus(execution.getStatus());
|
||||
plan.setUnitId(execution.getSampleUnitId());
|
||||
plan.setScanPlanName(StrUtil.blankToDefault(execution.getScanPlanName(), "扫描执行"));
|
||||
plan.setScanPlanCode(execution.getScanPlanCode());
|
||||
plan.setSequenceReady(false);
|
||||
plan.setDisplayStatus(taskStatusName(execution.getStatus()));
|
||||
var clouds = artifactMapper.selectAvailableByExecutionId(execution.getId());
|
||||
plan.setPointCloudReady(clouds.stream().anyMatch(f -> "MATCHED".equals(f.getChecksumStatus()) && ("POINT_CLOUD".equals(f.getArtifactType()) || StrUtil.blankToDefault(f.getFileName(), "").toLowerCase(java.util.Locale.ROOT).endsWith(".ply"))));
|
||||
var comparisons = jdbc.queryForList("SELECT engine_id FROM lab_dimension_comparison WHERE task_id=? AND source_execution_id=? AND tenant_id=? AND engine_id IS NOT NULL ORDER BY create_time DESC,id DESC LIMIT 1", taskId, execution.getId(), tenant);
|
||||
if (!comparisons.isEmpty()) plan.setInspectionScanId(java.util.Objects.toString(comparisons.get(0).get("engine_id"), null));
|
||||
for (var batch : batches) if (execution.getId().equals(batch.getExecutionId())) {
|
||||
var link = new LabBarcodeResolveRespVO.Link();link.setId(batch.getId());link.setNo(batch.getBatchNo());link.setExecutionId(execution.getId());plan.getResultBatches().add(link);
|
||||
}
|
||||
for (var report : reports) if (execution.getId().equals(report.getExecutionId())) {
|
||||
var link = new LabBarcodeResolveRespVO.Link();link.setId(report.getId());link.setNo(report.getReportNo());link.setExecutionId(execution.getId());plan.getReports().add(link);
|
||||
}
|
||||
plans.add(plan);
|
||||
}
|
||||
resp.setSelectedPlans(plans);
|
||||
resp.setCurrentPlan(plans.isEmpty() ? null : plans.get(0));
|
||||
resp.setPlanHint(plans.isEmpty() ? "尚无扫描执行,请进入任务工作台选择方案并准备扫描。" : "按原有任务工作台查看初次扫描、补扫与重试;扫码不改变方案顺序和执行状态。");
|
||||
}
|
||||
|
||||
private LabBarcodeResolveRespVO.Task toTask(LabTestTaskDO task, String partNo) {
|
||||
LabBarcodeResolveRespVO.Task item = new LabBarcodeResolveRespVO.Task();
|
||||
item.setTaskId(task.getId());
|
||||
item.setTaskNo(task.getTaskNo());
|
||||
item.setTaskName(task.getTaskName());
|
||||
item.setTaskStatus(task.getStatus());
|
||||
item.setTaskStatusName(taskStatusName(task.getStatus()));
|
||||
item.setPlannedFinishAt(task.getPlannedFinishAt());
|
||||
item.setPartNo(partNo);
|
||||
item.setReadOnly(LabBarcodeMatchRules.terminal(task.getStatus()));
|
||||
return item;
|
||||
}
|
||||
|
||||
private List<LabTestTaskDO> tasksForPart(String partNo) {
|
||||
List<LabSampleDO> samples = sampleMapper.selectList(LabSampleDO::getPartNo, partNo);
|
||||
if (samples.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
Set<Long> sampleIds = new LinkedHashSet<>();
|
||||
for (LabSampleDO sample : samples) {
|
||||
sampleIds.add(sample.getId());
|
||||
}
|
||||
List<LabTaskSampleDO> links = taskSampleMapper.selectList(new LambdaQueryWrapperX<LabTaskSampleDO>()
|
||||
.in(LabTaskSampleDO::getSampleId, sampleIds));
|
||||
Set<Long> taskIds = new LinkedHashSet<>();
|
||||
for (LabTaskSampleDO link : links) {
|
||||
if (link.getTaskId() != null) {
|
||||
taskIds.add(link.getTaskId());
|
||||
}
|
||||
}
|
||||
if (taskIds.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
List<LabTestTaskDO> tasks = taskMapper.selectByIds(taskIds);
|
||||
return tasks == null ? List.of() : tasks;
|
||||
}
|
||||
|
||||
private boolean taskContains(LabTestTaskDO task, String partNo) {
|
||||
if (task == null || StrUtil.isBlank(partNo)) {
|
||||
return false;
|
||||
}
|
||||
List<LabTaskSampleDO> links = taskSampleMapper.selectListByTaskId(task.getId());
|
||||
if (links.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
Set<Long> sampleIds = new LinkedHashSet<>();
|
||||
for (LabTaskSampleDO link : links) {
|
||||
if (link.getSampleId() != null) {
|
||||
sampleIds.add(link.getSampleId());
|
||||
}
|
||||
}
|
||||
if (sampleIds.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
List<LabSampleDO> samples = sampleMapper.selectByIds(sampleIds);
|
||||
if (samples == null) {
|
||||
return false;
|
||||
}
|
||||
for (LabSampleDO sample : samples) {
|
||||
if (partNo.equals(StrUtil.blankToDefault(sample.getPartNo(), "").trim())) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private boolean otherPiece(Long taskId, String partNo, String barcode) {
|
||||
LabPieceBarcodeBindingDO existing = bindingMapper.selectActive(taskId, partNo);
|
||||
return existing != null && !barcode.equals(existing.getBarcode());
|
||||
}
|
||||
|
||||
private Registry requireActive(String namespace, String barcode) {
|
||||
Registry registry = loadRegistry(namespace, barcode);
|
||||
String refusal = switch (registry.state()) {
|
||||
case "ABSENT" -> "UNREGISTERED";
|
||||
case "DISABLED" -> "DISABLED";
|
||||
case "PART_DISABLED" -> "PART_DISABLED";
|
||||
default -> null;
|
||||
};
|
||||
reject(refusal);
|
||||
return registry;
|
||||
}
|
||||
|
||||
private Registry loadRegistry(String namespace, String barcode) {
|
||||
List<LabPieceBarcodeDO> rows = barcodeMapper.selectByCode(namespace, barcode);
|
||||
for (LabPieceBarcodeDO row : rows) {
|
||||
if ("ACTIVE".equals(row.getStatus()) && Integer.valueOf(1).equals(row.getActiveFlag())) {
|
||||
LabSampleDO sample = sampleMapper.selectById(row.getSampleId());
|
||||
if (sample == null || StrUtil.isBlank(sample.getPartNo())
|
||||
|| !LabMasterStatusEnum.ENABLED.getStatus().equals(sample.getStatus())) {
|
||||
return new Registry("PART_DISABLED", row, sample);
|
||||
}
|
||||
return new Registry("ACTIVE", row, sample);
|
||||
}
|
||||
}
|
||||
for (LabPieceBarcodeDO row : rows) {
|
||||
if ("DISABLED".equals(row.getStatus())) {
|
||||
return new Registry("DISABLED", row, sampleMapper.selectById(row.getSampleId()));
|
||||
}
|
||||
}
|
||||
return new Registry("ABSENT", null, null);
|
||||
}
|
||||
|
||||
private LabSampleDO requireEnabledSample(Long sampleId) {
|
||||
LabSampleDO sample = sampleMapper.selectById(sampleId);
|
||||
if (sample == null) {
|
||||
throw exception(BARCODE_PART_NOT_FOUND);
|
||||
}
|
||||
if (StrUtil.isBlank(sample.getPartNo())) {
|
||||
throw exception(BARCODE_PART_KEY_MISSING);
|
||||
}
|
||||
if (!LabMasterStatusEnum.ENABLED.getStatus().equals(sample.getStatus())) {
|
||||
throw exception(BARCODE_PART_DISABLED);
|
||||
}
|
||||
return sample;
|
||||
}
|
||||
|
||||
private LabTestTaskDO requireTask(Long taskId) {
|
||||
LabTestTaskDO task = taskMapper.selectById(taskId);
|
||||
if (task == null) {
|
||||
throw exception(TASK_NOT_EXISTS);
|
||||
}
|
||||
return task;
|
||||
}
|
||||
|
||||
private void reject(String refusal) {
|
||||
if (refusal == null) {
|
||||
return;
|
||||
}
|
||||
throw exception(switch (refusal) {
|
||||
case "PART_NOT_IN_TASK" -> BARCODE_PART_NOT_IN_TASK;
|
||||
case "TASK_READONLY" -> BARCODE_TASK_READONLY;
|
||||
case "MULTI_PIECE_BLOCKED" -> BARCODE_MULTI_PIECE_BLOCKED;
|
||||
case "DISABLED" -> BARCODE_DISABLED;
|
||||
case "PART_DISABLED" -> BARCODE_PART_DISABLED;
|
||||
case "UNREGISTERED" -> BARCODE_NOT_REGISTERED;
|
||||
case "FORBIDDEN" -> BARCODE_FORBIDDEN;
|
||||
default -> BARCODE_INVALID;
|
||||
});
|
||||
}
|
||||
|
||||
private String requireBarcode(String raw, boolean normalized) {
|
||||
String[] affix = affixes();
|
||||
String barcode = LabBarcodeMatchRules.normalize(raw, normalized ? "" : affix[0], normalized ? "" : affix[1]);
|
||||
String reason = LabBarcodeMatchRules.invalidReason(barcode);
|
||||
if ("EMPTY".equals(reason)) {
|
||||
throw exception(BARCODE_EMPTY);
|
||||
}
|
||||
if (reason != null) {
|
||||
throw exception(BARCODE_INVALID);
|
||||
}
|
||||
return barcode;
|
||||
}
|
||||
|
||||
private String namespace(String raw) {
|
||||
String value = StrUtil.blankToDefault(raw, "LOCAL").trim();
|
||||
if (value.isEmpty()) {
|
||||
return "LOCAL";
|
||||
}
|
||||
if (LabBarcodeMatchRules.invalidReason(value) != null) {
|
||||
throw exception(BARCODE_INVALID);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private String source(String raw) {
|
||||
String value = StrUtil.blankToDefault(raw, "MANUAL").trim().toUpperCase();
|
||||
if (!SOURCES.contains(value)) {
|
||||
throw exception(BARCODE_INVALID);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private String idempotency(String raw) {
|
||||
if (StrUtil.isBlank(raw)) {
|
||||
return null;
|
||||
}
|
||||
String value = raw.trim();
|
||||
if (value.length() > 128 || LabBarcodeMatchRules.invalidReason(value) != null) {
|
||||
throw exception(BARCODE_INVALID);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private String reason(String raw) {
|
||||
String value = StrUtil.blankToDefault(raw, "").trim();
|
||||
if (value.isEmpty() || value.length() > 500) {
|
||||
throw exception(BARCODE_REASON_REQUIRED);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private String blankNull(String raw, int max) {
|
||||
if (StrUtil.isBlank(raw)) {
|
||||
return null;
|
||||
}
|
||||
String value = raw.trim();
|
||||
if (value.length() > max) {
|
||||
throw exception(BARCODE_INVALID);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private String affix(String raw) {
|
||||
String value = raw == null ? "" : raw.trim();
|
||||
String invalid = LabBarcodeMatchRules.invalidReason(value);
|
||||
if (invalid != null && !"EMPTY".equals(invalid)) {
|
||||
throw exception(BARCODE_PROFILE_INVALID);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private String[] affixes() {
|
||||
LabBarcodeScanProfileDO profile = profileMapper.selectCurrent();
|
||||
if (profile == null) {
|
||||
return new String[]{"", ""};
|
||||
}
|
||||
return new String[]{StrUtil.blankToDefault(profile.getPrefix(), ""), StrUtil.blankToDefault(profile.getSuffix(), "")};
|
||||
}
|
||||
|
||||
private void updateSerial(Long id, String serial) {
|
||||
if (serial == null) {
|
||||
return;
|
||||
}
|
||||
LabPieceBarcodeDO update = new LabPieceBarcodeDO();
|
||||
update.setId(id);
|
||||
update.setPhysicalSerialNo(serial);
|
||||
barcodeMapper.updateById(update);
|
||||
}
|
||||
|
||||
private boolean canReadTasks() {
|
||||
return securityFrameworkService.hasPermission("lab:task:query");
|
||||
}
|
||||
|
||||
private boolean sameBinding(LabPieceBarcodeBindingDO row, String barcode, Long taskId, String partNo) {
|
||||
return row != null && barcode.equals(row.getBarcode()) && taskId.equals(row.getTaskId()) && partNo.equals(row.getPartNo());
|
||||
}
|
||||
|
||||
private String label(String registry, String resolution) {
|
||||
if ("ABSENT".equals(registry)) {
|
||||
return "未登记";
|
||||
}
|
||||
if ("DISABLED".equals(registry)) {
|
||||
return "已停用";
|
||||
}
|
||||
if ("PART_DISABLED".equals(registry)) {
|
||||
return "零部件已停用";
|
||||
}
|
||||
if ("FORBIDDEN".equals(resolution)) {
|
||||
return "无权限";
|
||||
}
|
||||
if ("ACTIVE".equals(registry)) {
|
||||
return "已识别";
|
||||
}
|
||||
return "未识别";
|
||||
}
|
||||
|
||||
private String nextAction(String resolution) {
|
||||
return switch (resolution) {
|
||||
case "UNIQUE_MATCH" -> "BIND_TASK";
|
||||
case "MULTIPLE_TASKS" -> "CHOOSE_TASK";
|
||||
case "UNREGISTERED" -> "REGISTER";
|
||||
case "TASK_READONLY", "MULTI_PIECE_BLOCKED" -> "VIEW_TASK";
|
||||
case "PART_NOT_IN_TASK" -> "VIEW_OTHER_TASK";
|
||||
default -> "NONE";
|
||||
};
|
||||
}
|
||||
|
||||
private String taskStatusName(String status) {
|
||||
for (LabTaskStatusEnum item : LabTaskStatusEnum.values()) {
|
||||
if (item.getStatus().equals(status)) {
|
||||
return item.getName();
|
||||
}
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
private Long audit(String action, String barcode, String namespace, Long barcodeId, Long taskId, String partNo,
|
||||
String resolution, String message, String detail) {
|
||||
LabPieceBarcodeAuditDO row = new LabPieceBarcodeAuditDO();
|
||||
row.setAction(action);
|
||||
row.setBarcode(StrUtil.sub(StrUtil.blankToDefault(barcode, ""), 0, 128));
|
||||
row.setBarcodeNamespace(namespace);
|
||||
row.setBarcodeId(barcodeId);
|
||||
row.setTaskId(taskId);
|
||||
row.setPartNo(StrUtil.sub(StrUtil.blankToDefault(partNo, ""), 0, 64));
|
||||
row.setResolution(resolution);
|
||||
row.setMessage(StrUtil.sub(StrUtil.blankToDefault(message, ""), 0, 500));
|
||||
row.setDetailJson(StrUtil.sub(StrUtil.blankToDefault(detail, ""), 0, 1000));
|
||||
row.setOperatorId(SecurityFrameworkUtils.getLoginUserId());
|
||||
auditMapper.insert(row);
|
||||
return row.getId();
|
||||
}
|
||||
|
||||
private String detail(String stationId, String reason) {
|
||||
if (StrUtil.isBlank(stationId) && StrUtil.isBlank(reason)) {
|
||||
return null;
|
||||
}
|
||||
JSONObject json = new JSONObject();
|
||||
if (StrUtil.isNotBlank(stationId)) {
|
||||
json.set("stationId", stationId);
|
||||
}
|
||||
if (StrUtil.isNotBlank(reason)) {
|
||||
json.set("reason", reason);
|
||||
}
|
||||
return StrUtil.sub(json.toString(), 0, 1000);
|
||||
}
|
||||
|
||||
private record Registry(String state, LabPieceBarcodeDO row, LabSampleDO sample) {
|
||||
}
|
||||
}
|
||||
155
am-web/src/api/lab/barcode/index.ts
Normal file
155
am-web/src/api/lab/barcode/index.ts
Normal file
@ -0,0 +1,155 @@
|
||||
import request from '@/config/axios'
|
||||
|
||||
export interface LabBarcodePart {
|
||||
partId?: number | string
|
||||
sampleId?: number | string
|
||||
partNo?: string
|
||||
partName?: string
|
||||
sampleCode?: string
|
||||
vehicleModel?: string
|
||||
projectName?: string
|
||||
status?: string
|
||||
physicalSerialNo?: string
|
||||
}
|
||||
|
||||
export interface LabBarcodeTask {
|
||||
taskId: number | string
|
||||
taskNo?: string
|
||||
taskName?: string
|
||||
taskStatus?: string
|
||||
taskStatusName?: string
|
||||
plannedFinishAt?: string
|
||||
partNo?: string
|
||||
readOnly?: boolean
|
||||
}
|
||||
|
||||
export interface LabBarcodeLink {
|
||||
id: number | string
|
||||
no?: string
|
||||
executionId?: number | string
|
||||
}
|
||||
|
||||
export interface LabBarcodePlan {
|
||||
selectionId?: number | string
|
||||
sequenceNo?: number
|
||||
scanPlanName?: string
|
||||
scanPlanCode?: string
|
||||
sequenceReady?: boolean
|
||||
displayStatus?: string
|
||||
blockedReason?: string
|
||||
executionId?: number | string
|
||||
executionNo?: string
|
||||
unitId?: number | string
|
||||
executionStatus?: string
|
||||
pointCloudReady?: boolean
|
||||
inspectionScanId?: string
|
||||
resultBatches?: LabBarcodeLink[]
|
||||
reports?: LabBarcodeLink[]
|
||||
}
|
||||
|
||||
export interface LabBarcodeResolution {
|
||||
resolution?: string
|
||||
barcode?: string
|
||||
barcodeNamespace?: string
|
||||
registryStatus?: string
|
||||
recognitionLabel?: string
|
||||
recognized?: boolean
|
||||
bound?: boolean
|
||||
readOnly?: boolean
|
||||
bindAllowed?: boolean
|
||||
registeredNow?: boolean
|
||||
pieceTraceMode?: string
|
||||
message?: string
|
||||
nextAction?: string
|
||||
planHint?: string
|
||||
chosenTaskId?: number | string
|
||||
bindingId?: number | string
|
||||
auditId?: number | string
|
||||
blockingBarcode?: string
|
||||
part?: LabBarcodePart
|
||||
candidateTasks?: LabBarcodeTask[]
|
||||
historyTasks?: LabBarcodeTask[]
|
||||
selectedPlans?: LabBarcodePlan[]
|
||||
currentPlan?: LabBarcodePlan
|
||||
nextPlan?: LabBarcodePlan
|
||||
}
|
||||
|
||||
export interface LabBarcodePartOption {
|
||||
sampleId: number | string
|
||||
partNo?: string
|
||||
partName?: string
|
||||
sampleCode?: string
|
||||
vehicleModel?: string
|
||||
projectName?: string
|
||||
status?: string
|
||||
}
|
||||
|
||||
export const resolveBarcode = (data: {
|
||||
barcode: string
|
||||
currentTaskId?: number | string
|
||||
barcodeNormalized?: boolean
|
||||
barcodeNamespace?: string
|
||||
stationId?: string
|
||||
}) => {
|
||||
return request.post<LabBarcodeResolution>({ url: '/lab/barcode/resolve', data })
|
||||
}
|
||||
|
||||
export const registerBarcode = (data: {
|
||||
barcode: string
|
||||
sampleId: number | string
|
||||
barcodeNamespace?: string
|
||||
physicalSerialNo?: string
|
||||
source?: string
|
||||
currentTaskId?: number | string
|
||||
}) => {
|
||||
return request.post<LabBarcodeResolution>({ url: '/lab/barcode/register', data: { ...data, barcodeNormalized: true } })
|
||||
}
|
||||
|
||||
export const bindBarcodeTask = (data: {
|
||||
barcode: string
|
||||
taskId: number | string
|
||||
barcodeNamespace?: string
|
||||
idempotencyKey?: string
|
||||
stationId?: string
|
||||
}) => {
|
||||
return request.post<LabBarcodeResolution>({ url: '/lab/barcode/bind-task', data: { ...data, barcodeNormalized: true } })
|
||||
}
|
||||
|
||||
export const unbindBarcodeTask = (data: {
|
||||
barcode: string
|
||||
taskId: number | string
|
||||
barcodeNamespace?: string
|
||||
reason: string
|
||||
}) => {
|
||||
return request.post<LabBarcodeResolution>({ url: '/lab/barcode/unbind-task', data: { ...data, barcodeNormalized: true } })
|
||||
}
|
||||
|
||||
export const rebindBarcode = (data: {
|
||||
barcode: string
|
||||
sampleId: number | string
|
||||
barcodeNamespace?: string
|
||||
physicalSerialNo?: string
|
||||
reason: string
|
||||
}) => {
|
||||
return request.post<LabBarcodeResolution>({ url: '/lab/barcode/rebind', data: { ...data, barcodeNormalized: true } })
|
||||
}
|
||||
|
||||
export const disableBarcode = (data: { barcode: string; barcodeNamespace?: string; reason: string }) => {
|
||||
return request.post<LabBarcodeResolution>({ url: '/lab/barcode/disable', data: { ...data, barcodeNormalized: true } })
|
||||
}
|
||||
|
||||
export const getBarcodeHistory = (params) => {
|
||||
return request.get({ url: '/lab/barcode/binding-history', params: { ...params, barcodeNormalized: !!params?.barcode } })
|
||||
}
|
||||
|
||||
export const searchBarcodeParts = (keyword?: string) => {
|
||||
return request.get<LabBarcodePartOption[]>({ url: '/lab/barcode/parts', params: { keyword } })
|
||||
}
|
||||
|
||||
export const getBarcodeProfile = () => {
|
||||
return request.get<{ prefix?: string; suffix?: string }>({ url: '/lab/barcode/profile' })
|
||||
}
|
||||
|
||||
export const saveBarcodeProfile = (data: { prefix?: string; suffix?: string }) => {
|
||||
return request.put({ url: '/lab/barcode/profile', data })
|
||||
}
|
||||
539
am-web/src/views/lab/barcode/BarcodeScanPanel.vue
Normal file
539
am-web/src/views/lab/barcode/BarcodeScanPanel.vue
Normal file
@ -0,0 +1,539 @@
|
||||
<template>
|
||||
<ContentWrap>
|
||||
<div class="head">
|
||||
<div>
|
||||
<div class="title">{{ embedded ? '扫码关联' : '扫码识别与任务关联' }}</div>
|
||||
<div class="sub">扫描枪请使用键盘模式,扫完后发送 Enter。也可以手工输入后查询。</div>
|
||||
</div>
|
||||
<div class="actions">
|
||||
<el-button @click="helpVisible = true">扫码帮助</el-button>
|
||||
<el-button v-if="checkPermi(['lab:barcode:query'])" @click="openHistory">关联记录</el-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="scan-row">
|
||||
<el-input
|
||||
id="barcode-scan-input"
|
||||
ref="inputRef"
|
||||
v-model="barcode"
|
||||
:disabled="loading"
|
||||
@input="barcodeNormalized=false"
|
||||
size="large"
|
||||
clearable
|
||||
placeholder="点击此处扫描 / 可手动输入条码"
|
||||
@keyup.enter="submit"
|
||||
/>
|
||||
<el-button type="primary" size="large" :loading="loading" @click="submit">查询</el-button>
|
||||
</div>
|
||||
|
||||
<el-alert v-if="errorText" class="mt-12px" :title="errorText" type="error" show-icon :closable="false" />
|
||||
|
||||
<div v-if="result && result.resolution !== 'INVALID'" class="result">
|
||||
<div class="result-line">
|
||||
<span>条码:{{ result.barcode || '-' }}</span>
|
||||
<el-tag :type="tagType">{{ result.recognitionLabel || '未识别' }}</el-tag>
|
||||
<el-tag v-if="result.bound" type="success">已正式关联</el-tag>
|
||||
<el-tag v-else-if="result.recognized" type="warning">尚未关联任务</el-tag>
|
||||
</div>
|
||||
<el-alert class="mt-12px" :title="result.message || '识别完成'" :type="alertType" show-icon :closable="false" />
|
||||
<el-descriptions v-if="result.part" :column="2" border class="mt-12px">
|
||||
<el-descriptions-item label="零部件编号">{{ result.part.partNo || '-' }}</el-descriptions-item>
|
||||
<el-descriptions-item label="零部件名称">{{ result.part.partName || '-' }}</el-descriptions-item>
|
||||
<el-descriptions-item label="规格/车型">{{ result.part.vehicleModel || '-' }}</el-descriptions-item>
|
||||
<el-descriptions-item label="项目">{{ result.part.projectName || '-' }}</el-descriptions-item>
|
||||
<el-descriptions-item label="主数据状态">{{ result.part.status || '-' }}</el-descriptions-item>
|
||||
<el-descriptions-item label="实物序列号">{{ result.part.physicalSerialNo || '-' }}</el-descriptions-item>
|
||||
</el-descriptions>
|
||||
|
||||
<div v-if="result.resolution === 'PART_NOT_IN_TASK'" class="task-box">
|
||||
<div>该零部件不属于当前任务。打开其他任务不会修改当前任务。</div>
|
||||
<div class="footer-actions">
|
||||
<el-button v-for="task in result.candidateTasks || []" :key="String(task.taskId)" @click="openTask(task.taskId, result.part?.partNo)">
|
||||
{{ task.taskNo }} {{ task.taskName }} {{ task.taskStatusName }}
|
||||
</el-button>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="result.resolution === 'NO_ACTIVE_TASK' && result.historyTasks?.length" class="task-box">
|
||||
<div>相关测量任务已结束,只能查看,不会恢复执行。</div>
|
||||
<div class="footer-actions">
|
||||
<el-button v-for="task in result.historyTasks" :key="String(task.taskId)" @click="openTask(task.taskId, result.part?.partNo)">
|
||||
{{ task.taskNo }} {{ task.taskStatusName }}
|
||||
</el-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="chosen" class="task-box">
|
||||
<div>测量任务:{{ chosen.taskNo || '-' }} {{ chosen.taskName || '' }}</div>
|
||||
<div>状态:{{ chosen.taskStatusName || chosen.taskStatus || '-' }}</div>
|
||||
<div v-if="result.planHint">{{ result.planHint }}</div>
|
||||
<div v-if="result.nextPlan">
|
||||
下一方案:{{ seq(result.nextPlan.sequenceNo) }} {{ result.nextPlan.scanPlanName || '未命名' }}({{ result.nextPlan.displayStatus || '等待前序方案' }})
|
||||
</div>
|
||||
<div v-if="result.blockingBarcode">已占用的实物条码:{{ result.blockingBarcode }}</div>
|
||||
<div v-if="result.pieceTraceMode === 'IDENTITY_ONLY'" class="hint">
|
||||
此条码只标识这一件实物。测量结果仍归该零部件的扫描执行,不会另建一套结果。
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="result.selectedPlans?.length" class="plans">
|
||||
<div v-for="plan in result.selectedPlans" :key="String(plan.selectionId || plan.executionId)" class="plan">
|
||||
<div>
|
||||
{{ seq(plan.sequenceNo) }} {{ plan.scanPlanName || plan.scanPlanCode || '扫描方案' }}
|
||||
· {{ plan.displayStatus || '待执行' }}
|
||||
<span v-if="plan.executionNo"> · 执行 {{ plan.executionNo }}</span>
|
||||
</div>
|
||||
<div class="plan-actions">
|
||||
<el-button v-if="plan.executionId" link type="primary" @click="openExec(plan.executionId)">扫描执行</el-button>
|
||||
<el-button v-for="item in plan.resultBatches || []" :key="String(item.id)" link type="primary" @click="openResult(item.id)">
|
||||
测量结果 {{ item.no || '' }}
|
||||
</el-button>
|
||||
<el-button v-if="plan.inspectionScanId" link type="primary" @click="openInspection(plan.inspectionScanId)">三维检测</el-button>
|
||||
<span v-else-if="plan.pointCloudReady" class="hint">已有点云,尚未进入三维检测。扫码不会自动开始检测。</span>
|
||||
<span v-else-if="plan.executionId" class="hint">当前执行没有可用点云。</span>
|
||||
<el-button v-for="item in plan.reports || []" :key="'r' + String(item.id)" link type="primary" @click="openReport(item.id)">
|
||||
报告 {{ item.no || '' }}
|
||||
</el-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="footer-actions">
|
||||
<el-button v-if="chosen" type="primary" @click="openTask(chosen.taskId, result.part?.partNo)">进入任务工作台</el-button>
|
||||
<el-button v-if="chosen" @click="openResource(chosen.taskId, result.part?.partNo)">查看扫描方案与资源</el-button>
|
||||
<el-button v-if="chosen" @click="go(chosen.taskId, 'delivery', result?.currentPlan)">比对资料与成果</el-button>
|
||||
<el-button @click="continueScan">继续扫码</el-button>
|
||||
</div>
|
||||
|
||||
<div v-if="checkPermi(['lab:barcode:rebind']) && result.barcode" class="manage">
|
||||
<div class="manage-title">条码管理</div>
|
||||
<el-input v-model="manageReason" placeholder="停用、改绑或解除关联时填写原因" />
|
||||
<div class="footer-actions">
|
||||
<el-button v-if="result.bound && chosen" :disabled="!manageReason.trim()" @click="doUnbind">解除当前任务关联</el-button>
|
||||
<el-button :disabled="!manageReason.trim()" @click="openRebind">改绑零部件</el-button>
|
||||
<el-button :disabled="!manageReason.trim()" type="danger" plain @click="doDisable">停用条码</el-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</ContentWrap>
|
||||
|
||||
<Dialog v-model="taskDialog" title="选择测量任务" width="640">
|
||||
<div v-if="result?.part" class="mb-12px">已识别零部件:{{ result.part.partNo }} {{ result.part.partName }}</div>
|
||||
<div class="mb-12px">此零部件存在 {{ result?.candidateTasks?.length || 0 }} 个可关联测量任务,请选择:</div>
|
||||
<el-radio-group v-model="pickedTaskId" class="task-choices">
|
||||
<el-radio v-for="task in result?.candidateTasks || []" :key="String(task.taskId)" :value="String(task.taskId)" class="task-choice">
|
||||
{{ task.taskNo }} {{ task.taskName }} {{ formatDate(task.plannedFinishAt) || '' }} {{ task.taskStatusName || task.taskStatus }}
|
||||
</el-radio>
|
||||
</el-radio-group>
|
||||
<template #footer>
|
||||
<el-button @click="taskDialog = false">取消</el-button>
|
||||
<el-button :disabled="!pickedTaskId" @click="viewPicked">仅查看</el-button>
|
||||
<el-button type="primary" :disabled="!pickedTaskId || !checkPermi(['lab:barcode:bind'])" :loading="loading" @click="bindPicked">
|
||||
关联并进入
|
||||
</el-button>
|
||||
</template>
|
||||
</Dialog>
|
||||
|
||||
<Dialog v-model="registerVisible" title="登记未识别条码" width="560">
|
||||
<div class="mb-12px">条码:{{ pendingBarcode }}(未登记)</div>
|
||||
<el-form label-width="110px">
|
||||
<el-form-item label="已有零部件" required>
|
||||
<el-select
|
||||
v-model="registerSampleId"
|
||||
filterable
|
||||
remote
|
||||
reserve-keyword
|
||||
placeholder="搜索零部件编号或名称"
|
||||
class="!w-full"
|
||||
:remote-method="searchParts"
|
||||
:loading="partLoading"
|
||||
>
|
||||
<el-option
|
||||
v-for="item in partOptions"
|
||||
:key="String(item.sampleId)"
|
||||
:label="`${item.partNo || '-'} ${item.partName || ''}(${item.sampleCode || ''})`"
|
||||
:value="item.sampleId"
|
||||
/>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="实物序列号">
|
||||
<el-input v-model="registerSerial" placeholder="可选" />
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<div class="hint">这里只建立条码和已有零部件的对应关系。找不到零部件时,请先维护零部件主数据。</div>
|
||||
<template #footer>
|
||||
<el-button @click="registerVisible = false">取消</el-button>
|
||||
<el-button type="primary" :disabled="!registerSampleId" :loading="loading" @click="confirmRegister">确认绑定</el-button>
|
||||
</template>
|
||||
</Dialog>
|
||||
|
||||
<Dialog v-model="rebindVisible" title="改绑零部件" width="560">
|
||||
<el-select
|
||||
v-model="rebindSampleId"
|
||||
filterable
|
||||
remote
|
||||
reserve-keyword
|
||||
placeholder="搜索零部件编号或名称"
|
||||
class="!w-full"
|
||||
:remote-method="searchParts"
|
||||
:loading="partLoading"
|
||||
>
|
||||
<el-option
|
||||
v-for="item in partOptions"
|
||||
:key="'re' + String(item.sampleId)"
|
||||
:label="`${item.partNo || '-'} ${item.partName || ''}`"
|
||||
:value="item.sampleId"
|
||||
/>
|
||||
</el-select>
|
||||
<template #footer>
|
||||
<el-button @click="rebindVisible = false">取消</el-button>
|
||||
<el-button type="primary" :disabled="!rebindSampleId || !manageReason.trim()" :loading="loading" @click="confirmRebind">确认改绑</el-button>
|
||||
</template>
|
||||
</Dialog>
|
||||
|
||||
<Dialog v-model="helpVisible" title="扫码帮助" width="640">
|
||||
<ol class="help">
|
||||
<li>把扫描枪设为 USB 键盘,并在条码结尾附加 Enter。</li>
|
||||
<li>光标放在“扫描条码”输入框后扫描。没有扫描枪时,输入条码并按 Enter 或点击查询。</li>
|
||||
<li>系统只按已登记的条码带出零部件,不会按条码前缀猜测并保存。</li>
|
||||
<li>只有一个可做的测量任务时会关联该任务。有多个任务时必须手工选择。</li>
|
||||
<li>扫码不会发布扫描、启动设备、确认结果或发布报告。</li>
|
||||
<li>网络中断时不会显示识别成功。恢复后重新扫描即可。</li>
|
||||
</ol>
|
||||
<template v-if="checkPermi(['lab:barcode:register'])">
|
||||
<div class="manage-title">扫描枪前后缀</div>
|
||||
<el-form inline>
|
||||
<el-form-item label="前缀"><el-input v-model="profile.prefix" class="!w-140px" /></el-form-item>
|
||||
<el-form-item label="后缀"><el-input v-model="profile.suffix" class="!w-140px" /></el-form-item>
|
||||
<el-form-item><el-button type="primary" @click="saveProfile">保存</el-button></el-form-item>
|
||||
</el-form>
|
||||
</template>
|
||||
</Dialog>
|
||||
|
||||
<Dialog v-model="historyVisible" title="条码关联记录" width="860">
|
||||
<el-table :data="history" v-loading="historyLoading">
|
||||
<el-table-column label="时间" min-width="160">
|
||||
<template #default="scope">{{ formatDate(scope.row.createTime) || '-' }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="动作" prop="action" width="140" />
|
||||
<el-table-column label="条码" prop="barcode" min-width="160" />
|
||||
<el-table-column label="零部件" prop="partNo" width="120" />
|
||||
<el-table-column label="结论" prop="resolution" width="140" />
|
||||
<el-table-column label="说明" prop="message" min-width="220" />
|
||||
</el-table>
|
||||
</Dialog>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { formatDate } from '@/utils/formatTime'
|
||||
import { checkPermi } from '@/utils/permission'
|
||||
import * as BarcodeApi from '@/api/lab/barcode'
|
||||
|
||||
defineOptions({ name: 'BarcodeScanPanel' })
|
||||
|
||||
const props = defineProps<{ embedded?: boolean; taskId?: number | string; autofocus?: boolean }>()
|
||||
const emit = defineEmits<{ matched: [{ partNo?: string; taskId?: number | string }]; navigated: [] }>()
|
||||
|
||||
const { push } = useRouter()
|
||||
const message = useMessage()
|
||||
const inputRef = ref()
|
||||
const barcode = ref('')
|
||||
const barcodeNormalized = ref(false)
|
||||
let active = true
|
||||
onBeforeUnmount(() => { active = false })
|
||||
const loading = ref(false)
|
||||
const errorText = ref('')
|
||||
const result = ref<BarcodeApi.LabBarcodeResolution>()
|
||||
const taskDialog = ref(false)
|
||||
const pickedTaskId = ref<string>()
|
||||
const registerVisible = ref(false)
|
||||
const pendingBarcode = ref('')
|
||||
const registerSampleId = ref<number | string>()
|
||||
const registerSerial = ref('')
|
||||
const partOptions = ref<BarcodeApi.LabBarcodePartOption[]>([])
|
||||
const partLoading = ref(false)
|
||||
const helpVisible = ref(false)
|
||||
const profile = reactive({ prefix: '', suffix: '' })
|
||||
const historyVisible = ref(false)
|
||||
const historyLoading = ref(false)
|
||||
const history = ref<any[]>([])
|
||||
const manageReason = ref('')
|
||||
const rebindVisible = ref(false)
|
||||
const rebindSampleId = ref<number | string>()
|
||||
|
||||
const chosen = computed(() => {
|
||||
const id = result.value?.chosenTaskId
|
||||
if (id == null) return undefined
|
||||
return (result.value?.candidateTasks || []).find((item) => String(item.taskId) === String(id))
|
||||
|| (result.value?.historyTasks || []).find((item) => String(item.taskId) === String(id))
|
||||
})
|
||||
const tagType = computed(() => {
|
||||
if (result.value?.bound) return 'success'
|
||||
if (result.value?.recognized) return 'warning'
|
||||
if (result.value?.resolution === 'UNREGISTERED') return 'info'
|
||||
return 'danger'
|
||||
})
|
||||
const alertType = computed(() => {
|
||||
if (result.value?.resolution === 'MULTI_PIECE_BLOCKED' || result.value?.resolution === 'PART_NOT_IN_TASK') return 'error'
|
||||
if (result.value?.readOnly || result.value?.resolution === 'NO_ACTIVE_TASK') return 'warning'
|
||||
if (result.value?.bound || result.value?.resolution === 'UNIQUE_MATCH') return 'success'
|
||||
return 'info'
|
||||
})
|
||||
|
||||
const seq = (value?: number) => (value == null ? '' : String(value).padStart(2, '0'))
|
||||
const focusInput = () => nextTick(() => inputRef.value?.focus?.())
|
||||
const isOffline = (error: any) => {
|
||||
if (typeof navigator !== 'undefined' && navigator.onLine === false) return true
|
||||
return String(error?.message || error || '').includes('Network Error')
|
||||
}
|
||||
const idempotencyKey = (code: string, taskId: number | string) => {
|
||||
const key = `LOCAL|${code}|${taskId}`
|
||||
return key.length <= 128 ? key : undefined
|
||||
}
|
||||
|
||||
const applyResolution = async (data: BarcodeApi.LabBarcodeResolution, autoBind: boolean) => {
|
||||
if (!active) return
|
||||
result.value = data
|
||||
errorText.value = ''
|
||||
manageReason.value = ''
|
||||
if (!data || data.resolution === 'INVALID') {
|
||||
result.value = undefined
|
||||
errorText.value = data?.message || '请扫描或输入条码'
|
||||
return
|
||||
}
|
||||
if (data.resolution === 'UNREGISTERED') {
|
||||
pendingBarcode.value = data.barcode || barcode.value.trim()
|
||||
registerSampleId.value = undefined
|
||||
registerSerial.value = ''
|
||||
if (checkPermi(['lab:barcode:register'])) {
|
||||
registerVisible.value = true
|
||||
searchParts('')
|
||||
}
|
||||
return
|
||||
}
|
||||
if (data.resolution === 'MULTIPLE_TASKS') {
|
||||
pickedTaskId.value = undefined
|
||||
taskDialog.value = true
|
||||
return
|
||||
}
|
||||
if (autoBind && data.nextAction === 'BIND_TASK' && data.bindAllowed && !data.bound && data.chosenTaskId != null && checkPermi(['lab:barcode:bind'])) {
|
||||
await confirmBind(data.chosenTaskId, data.barcode || '')
|
||||
return
|
||||
}
|
||||
if (data.part?.partNo && data.chosenTaskId != null && ['UNIQUE_MATCH', 'TASK_READONLY', 'MULTI_PIECE_BLOCKED'].includes(data.resolution || '')) {
|
||||
emit('matched', { partNo: data.part.partNo, taskId: data.chosenTaskId })
|
||||
}
|
||||
}
|
||||
|
||||
const submit = async () => {
|
||||
if (loading.value || !active) return
|
||||
const raw = barcode.value.trim()
|
||||
result.value = undefined
|
||||
errorText.value = ''
|
||||
if (!raw) {
|
||||
errorText.value = '请扫描或输入条码'
|
||||
return
|
||||
}
|
||||
loading.value = true
|
||||
try {
|
||||
const data = await BarcodeApi.resolveBarcode({ barcode: raw, barcodeNormalized: barcodeNormalized.value, currentTaskId: props.taskId || undefined })
|
||||
await applyResolution(data, true)
|
||||
} catch (error) {
|
||||
result.value = undefined
|
||||
errorText.value = isOffline(error) ? '网络不可用,扫码结果未关联' : '扫码没有完成,请根据提示处理后重试'
|
||||
} finally {
|
||||
loading.value = false
|
||||
focusInput()
|
||||
}
|
||||
}
|
||||
|
||||
const confirmBind = async (taskId: number | string, code?: string) => {
|
||||
const raw = code || result.value?.barcode || barcode.value.trim()
|
||||
loading.value = true
|
||||
try {
|
||||
const data = await BarcodeApi.bindBarcodeTask({
|
||||
barcode: raw,
|
||||
taskId,
|
||||
idempotencyKey: idempotencyKey(raw, taskId)
|
||||
})
|
||||
result.value = data
|
||||
errorText.value = ''
|
||||
taskDialog.value = false
|
||||
if (data.part?.partNo) emit('matched', { partNo: data.part.partNo, taskId: data.chosenTaskId || taskId })
|
||||
} catch (error) {
|
||||
if (isOffline(error)) errorText.value = '网络不可用,扫码结果未关联'
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const bindPicked = async () => {
|
||||
const task = (result.value?.candidateTasks || []).find((item) => String(item.taskId) === pickedTaskId.value)
|
||||
if (!task) return
|
||||
await confirmBind(task.taskId)
|
||||
if (result.value?.bound) openTask(task.taskId, result.value.part?.partNo)
|
||||
}
|
||||
|
||||
const viewPicked = () => {
|
||||
const task = (result.value?.candidateTasks || []).find((item) => String(item.taskId) === pickedTaskId.value)
|
||||
if (!task) return
|
||||
taskDialog.value = false
|
||||
openTask(task.taskId, result.value?.part?.partNo)
|
||||
}
|
||||
|
||||
const searchParts = async (keyword: string) => {
|
||||
partLoading.value = true
|
||||
try {
|
||||
partOptions.value = (await BarcodeApi.searchBarcodeParts(keyword)) || []
|
||||
if (!partOptions.value.length && keyword) message.warning('没有找到零部件,请先维护零部件主数据')
|
||||
} finally {
|
||||
partLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const confirmRegister = async () => {
|
||||
if (!registerSampleId.value) return
|
||||
loading.value = true
|
||||
try {
|
||||
const data = await BarcodeApi.registerBarcode({
|
||||
barcode: pendingBarcode.value,
|
||||
sampleId: registerSampleId.value,
|
||||
physicalSerialNo: registerSerial.value || undefined,
|
||||
source: 'MANUAL',
|
||||
currentTaskId: props.taskId || undefined
|
||||
})
|
||||
registerVisible.value = false
|
||||
barcode.value = data.barcode || pendingBarcode.value
|
||||
barcodeNormalized.value = true
|
||||
await applyResolution(data, true)
|
||||
} catch (error) {
|
||||
if (isOffline(error)) errorText.value = '网络不可用,扫码结果未关联'
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const doUnbind = async () => {
|
||||
if (!chosen.value || !result.value?.barcode) return
|
||||
loading.value = true
|
||||
try {
|
||||
const data = await BarcodeApi.unbindBarcodeTask({
|
||||
barcode: result.value.barcode,
|
||||
taskId: chosen.value.taskId,
|
||||
reason: manageReason.value.trim()
|
||||
})
|
||||
await applyResolution(data, false)
|
||||
message.success('已解除关联')
|
||||
} catch (error) {
|
||||
if (isOffline(error)) errorText.value = '网络不可用,扫码结果未关联'
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const openRebind = () => {
|
||||
rebindSampleId.value = undefined
|
||||
rebindVisible.value = true
|
||||
searchParts('')
|
||||
}
|
||||
|
||||
const confirmRebind = async () => {
|
||||
if (!result.value?.barcode || !rebindSampleId.value) return
|
||||
loading.value = true
|
||||
try {
|
||||
const data = await BarcodeApi.rebindBarcode({
|
||||
barcode: result.value.barcode,
|
||||
sampleId: rebindSampleId.value,
|
||||
reason: manageReason.value.trim()
|
||||
})
|
||||
rebindVisible.value = false
|
||||
await applyResolution(data, false)
|
||||
message.success('已改绑零部件')
|
||||
} catch (error) {
|
||||
if (isOffline(error)) errorText.value = '网络不可用,扫码结果未关联'
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const doDisable = async () => {
|
||||
if (!result.value?.barcode) return
|
||||
loading.value = true
|
||||
try {
|
||||
const data = await BarcodeApi.disableBarcode({ barcode: result.value.barcode, reason: manageReason.value.trim() })
|
||||
await applyResolution(data, false)
|
||||
message.success('条码已停用')
|
||||
} catch (error) {
|
||||
if (isOffline(error)) errorText.value = '网络不可用,扫码结果未关联'
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const continueScan = () => {
|
||||
barcode.value = ''
|
||||
barcodeNormalized.value = false
|
||||
result.value = undefined
|
||||
errorText.value = ''
|
||||
focusInput()
|
||||
}
|
||||
|
||||
const go = (taskId: number | string | undefined, section: string, plan?: BarcodeApi.LabBarcodePlan) => {
|
||||
if (taskId == null) return
|
||||
emit('navigated')
|
||||
push({ name: 'DimensionWorkbench', params: { id: String(taskId) }, query: { section, ...(plan?.unitId ? { unitId: String(plan.unitId) } : {}), ...(plan?.executionId ? { executionId: String(plan.executionId) } : {}) } })
|
||||
}
|
||||
const openTask = (taskId?: number | string, _partNo?: string) => go(taskId, 'scan')
|
||||
const openResource = (taskId?: number | string, _partNo?: string) => go(taskId, 'prepare')
|
||||
const openExec = (id: number | string) => go(chosen.value?.taskId, 'scan', result.value?.selectedPlans?.find(p => String(p.executionId) === String(id)))
|
||||
const openResult = (id: number | string) => push({ name: 'LabResultDetail', params: { id: String(id) } })
|
||||
const openReport = (id: number | string) => push({ name: 'LabReportDetail', params: { id: String(id) } })
|
||||
const openInspection = (id: string) => go(chosen.value?.taskId, 'delivery', result.value?.selectedPlans?.find(p => p.inspectionScanId === id))
|
||||
|
||||
const openHistory = async () => {
|
||||
historyVisible.value = true
|
||||
historyLoading.value = true
|
||||
try {
|
||||
const page = await BarcodeApi.getBarcodeHistory({ pageNo: 1, pageSize: 20, barcode: result.value?.barcode || undefined })
|
||||
history.value = page?.list || []
|
||||
} finally {
|
||||
historyLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const saveProfile = async () => {
|
||||
await BarcodeApi.saveBarcodeProfile({ prefix: profile.prefix, suffix: profile.suffix })
|
||||
message.success('扫码前后缀已保存')
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
if (props.autofocus !== false) focusInput()
|
||||
if (checkPermi(['lab:barcode:query'])) {
|
||||
try {
|
||||
const data = await BarcodeApi.getBarcodeProfile()
|
||||
profile.prefix = data?.prefix || ''
|
||||
profile.suffix = data?.suffix || ''
|
||||
} catch {
|
||||
profile.prefix = ''
|
||||
profile.suffix = ''
|
||||
}
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.head { display: flex; justify-content: space-between; gap: 16px; align-items: flex-start; }
|
||||
.title { font-size: 18px; font-weight: 600; }
|
||||
.sub { margin-top: 4px; color: var(--el-text-color-secondary); }
|
||||
.actions { display: flex; gap: 8px; }
|
||||
.scan-row { display: flex; gap: 12px; margin-top: 16px; }
|
||||
.result { margin-top: 16px; }
|
||||
.result-line { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; font-size: 16px; }
|
||||
.task-box, .plan, .manage { margin-top: 12px; padding: 12px; background: var(--el-fill-color-light); border-radius: 6px; }
|
||||
.plan-actions, .footer-actions, .actions { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; }
|
||||
.footer-actions { margin-top: 12px; }
|
||||
.hint { color: var(--el-text-color-secondary); font-size: 13px; }
|
||||
.task-choices { display: flex; flex-direction: column; align-items: flex-start; gap: 10px; }
|
||||
.task-choice { margin-right: 0; }
|
||||
.help { padding-left: 18px; line-height: 1.8; }
|
||||
.manage-title { margin: 12px 0 8px; font-weight: 600; }
|
||||
</style>
|
||||
9
am-web/src/views/lab/barcode/index.vue
Normal file
9
am-web/src/views/lab/barcode/index.vue
Normal file
@ -0,0 +1,9 @@
|
||||
<template>
|
||||
<BarcodeScanPanel />
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import BarcodeScanPanel from './BarcodeScanPanel.vue'
|
||||
|
||||
defineOptions({ name: 'LabBarcodeWorkbench' })
|
||||
</script>
|
||||
@ -26,6 +26,7 @@
|
||||
@keyup.enter="load" /></el-form-item
|
||||
><el-button @click="load" :loading="loading">查询</el-button
|
||||
><el-button v-if="!resultMode" @click="router.push('/lab/task/import')">批量导入</el-button
|
||||
><el-button v-if="!resultMode" v-hasPermi="['lab:barcode:query']" @click="router.push('/lab/task/barcode')">扫码识别</el-button
|
||||
><MaintenanceActions v-if="mine && !resultMode"
|
||||
/></el-form>
|
||||
<el-table :data="rows" v-loading="loading">
|
||||
|
||||
@ -26,6 +26,7 @@
|
||||
<el-button v-else :type="data.stage === 'DELIVERED' ? 'success' : 'warning'" plain @click="switchSection('delivery')">{{
|
||||
deliveryStages[data.stage] || data.stage
|
||||
}} · {{ ['DELIVERED', 'PENDING_CONFIRM'].includes(data.stage) ? '查看成果' : '查看待办' }}</el-button>
|
||||
<el-button v-hasPermi="['lab:barcode:query']" @click="barcodeVisible = true">扫码关联</el-button>
|
||||
<el-button :loading="loading" @click="refresh">刷新</el-button>
|
||||
<el-button
|
||||
v-if="!data.task.ownerId && data.task.processType === 'SCAN_ONLY'"
|
||||
@ -422,6 +423,7 @@
|
||||
<Dialog v-model="snapshotOpen" title="该成果采用的输入版本" width="650px">
|
||||
<pre class="snapshot">{{ snapshotText }}</pre>
|
||||
</Dialog>
|
||||
<el-dialog v-model="barcodeVisible" title="扫码关联当前任务" width="min(1000px,95vw)" destroy-on-close><BarcodeScanPanel v-if="barcodeVisible" :task-id="taskId" embedded @navigated="barcodeVisible=false" /></el-dialog>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import * as Api from '@/api/lab/dimension'
|
||||
@ -442,6 +444,8 @@ const ModelViewer = defineAsyncComponent(
|
||||
() => import('@/views/lab/scan-task/ScannerModelViewer.vue')
|
||||
)
|
||||
const ComparisonPanel = defineAsyncComponent(() => import('./ComparisonPanel.vue'))
|
||||
const BarcodeScanPanel = defineAsyncComponent(() => import('@/views/lab/barcode/BarcodeScanPanel.vue'))
|
||||
const barcodeVisible = ref(false)
|
||||
const comparisonPanel = ref<any>()
|
||||
const route = useRoute(),
|
||||
router = useRouter(),
|
||||
@ -449,8 +453,8 @@ const route = useRoute(),
|
||||
taskId = computed(() => String(route.params.id))
|
||||
const data = shallowRef<any>(),
|
||||
cloudNotice = ref(''),
|
||||
unitId = ref(''),
|
||||
tab = ref('prepare'),
|
||||
unitId = ref(String(route.query.unitId || '')),
|
||||
tab = ref(['scan', 'materials', 'delivery', 'trace'].includes(String(route.query.section)) ? String(route.query.section) : 'prepare'),
|
||||
loading = ref(false),
|
||||
busy = ref(false),
|
||||
shared = ref(true),
|
||||
@ -458,7 +462,7 @@ const data = shallowRef<any>(),
|
||||
const scanWorkbench = ref<any>(),
|
||||
scanActions = ref<HTMLElement>(),
|
||||
scanMounted = ref(true),
|
||||
scanView = ref('prepare'),
|
||||
scanView = ref(route.query.section === 'scan' ? 'units' : 'prepare'),
|
||||
scanSummary = ref<any>()
|
||||
const isScanSection = computed(() => ['prepare', 'scan'].includes(tab.value))
|
||||
const sectionNavigation = ref<HTMLElement>()
|
||||
@ -802,13 +806,27 @@ function showSnapshot(row: any) {
|
||||
snapshotOpen.value = true
|
||||
}
|
||||
watch(taskId, () => {
|
||||
unitId.value = ''
|
||||
tab.value = 'prepare'
|
||||
scanView.value = 'prepare'
|
||||
barcodeVisible.value = false
|
||||
unitId.value = String(route.query.unitId || '')
|
||||
tab.value = ['scan','materials','delivery','trace'].includes(String(route.query.section)) ? String(route.query.section) : 'prepare'
|
||||
scanView.value = route.query.section === 'scan' ? 'units' : 'prepare'
|
||||
scanSummary.value = undefined
|
||||
data.value = undefined
|
||||
load()
|
||||
})
|
||||
watch(() => [route.query.section, route.query.unitId], async () => {
|
||||
if (!data.value || String(data.value.task.id) !== taskId.value || !(await mayDiscard())) return
|
||||
const requested = String(route.query.unitId || '')
|
||||
if (requested && !data.value.units.some(u => String(u.id) === requested)) {
|
||||
message.warning('指定样件不属于当前任务,请重新选择')
|
||||
return
|
||||
}
|
||||
if (requested) unitId.value = requested
|
||||
if (['prepare', 'scan', 'materials', 'delivery', 'trace'].includes(String(route.query.section))) {
|
||||
await switchSection(String(route.query.section))
|
||||
}
|
||||
await load()
|
||||
})
|
||||
// Scan progress remains owned by the original workbench. Refresh its exported
|
||||
// files when returning to materials, without losing unconfirmed input choices.
|
||||
watch(tab, (_current, previous) => {
|
||||
|
||||
@ -877,6 +877,16 @@ const viewAttempt = async (unit: ScanApi.ScanUnit, execution: Partial<LabExecuti
|
||||
await nextTick()
|
||||
executionPanel.value?.scrollIntoView({ block: 'start', behavior: 'smooth' })
|
||||
}
|
||||
watch(() => [route.query.executionId, route.query.unitId], async () => {
|
||||
if (!detail.value || String(detail.value.task.id) !== String(route.params.id)) return
|
||||
const execution = String(route.query.executionId || '')
|
||||
const unit = detail.value.units.find(u => execution ? u.attempts.some(a => String(a.id) === execution) : String(u.id) === String(route.query.unitId))
|
||||
if (unit) {
|
||||
const attempt = unit.attempts.find(a => String(a.id) === execution)
|
||||
if (attempt) await viewAttempt(unit, attempt)
|
||||
else selectUnit(unit)
|
||||
}
|
||||
})
|
||||
watch(
|
||||
() => selectedUnit.value?.id,
|
||||
() => {
|
||||
@ -1380,6 +1390,9 @@ const initialize = async () => {
|
||||
// Frozen task history is readable even when the operator cannot browse the native catalog.
|
||||
cases.value = []
|
||||
await refresh(true,false)
|
||||
const requestedExecution = String(route.query.executionId || '')
|
||||
const requestedUnit = detail.value?.units.find(u => String(u.id) === String(route.query.unitId) || u.attempts.some(a => String(a.id) === requestedExecution))
|
||||
if (requestedUnit) { selectUnit(requestedUnit); await nextTick(); if (requestedUnit.attempts.some(a => String(a.id) === requestedExecution)) selectedAttemptId.value = requestedExecution }
|
||||
activeTab.value = detail.value?.config.startedAt || terminal.value ? 'units' : 'prepare'
|
||||
loading.value=false
|
||||
if(!locked.value)void loadCatalog()
|
||||
|
||||
28
deploy/windows11/RELEASE-20261121-barcode.md
Normal file
28
deploy/windows11/RELEASE-20261121-barcode.md
Normal file
@ -0,0 +1,28 @@
|
||||
# 扫码识别与任务关联发布
|
||||
|
||||
本批在拉取远端 main 的 `a16f16e` 后集成扫码功能,保留远端尺寸比对 CAD 特征、设备告警、坐标系按名称调用、AGV 到位回执及标定窗口等修改。两个升级清单冲突已合并:保留 `018_inspection_cad_features.sql`,扫码迁移使用 `019_barcode.sql`,不覆盖已有迁移。
|
||||
|
||||
## 正式端更新
|
||||
|
||||
由正式端 AI 在用户通知更新、确认现场采集及运动停止后,在现有仓库根目录执行:
|
||||
|
||||
```powershell
|
||||
pwsh -NoProfile -File deploy/windows11/update.ps1 -CheckOnly
|
||||
pwsh -NoProfile -File deploy/windows11/update.ps1 -ConfirmStopped
|
||||
pwsh -NoProfile -File deploy/windows11/manage.ps1 -Action Status
|
||||
Get-Content .local/standalone/deployment.json
|
||||
```
|
||||
|
||||
核对部署提交号与本次交付提交一致。如果正式端有未提交的修改,先保留并核对,不能直接覆盖;脚本只允许快进更新。不要执行初始化、全量数据恢复或手工替换 JAR。
|
||||
|
||||
更新脚本自动安装锁文件依赖、构建平台前后端,执行批准的增量迁移。扫码新增四张独立表及任务中心扫码菜单,只对已有管理员角色初始授予权限;其他人员按需通过原角色管理分配。未新增必须填写的配置,不修改私有 YAML、设备地址、Bearer 或证书。
|
||||
|
||||
本次平台更新不自动安装或重启扫描仪服务及尺寸比对 EXE。远端已有标定窗口、CAD 特征等功能的现场配套要求,分别见同目录 calibration-window 和 cad-inspection 发布说明。
|
||||
|
||||
## 功能验收
|
||||
|
||||
重新登录刷新菜单,查看“任务中心 → 扫码识别”、任务列表“扫码识别”及工作台“扫码关联”。无扫描枪可以手动输入,原建任务、扫描和比对流程不要求条码。条码只关联已有启用样品和已有任务,不自动启动设备或计算。
|
||||
|
||||
只读抽查原任务、既有扫描执行、比对资料与成果可正常打开。扫描枪实体测试由现场安排,不把平台更新当作设备操作授权。
|
||||
|
||||
完整接入规则及开发验证范围见 `docs/barcode-integration-20261121.md`。本机不操作正式环境。
|
||||
46
docs/barcode-integration-20261121.md
Normal file
46
docs/barcode-integration-20261121.md
Normal file
@ -0,0 +1,46 @@
|
||||
# 扫码识别与任务关联接入说明
|
||||
|
||||
扫码沿用供应商的“实物条码 → 已有零部件主数据 → 检测任务”规则,接入本系统现有工作台。扫码不创建零部件、不修改任务或执行状态、不启动扫描、运动和尺寸比对。
|
||||
|
||||
## 使用入口
|
||||
|
||||
- 任务中心 → 扫码识别,地址 `/lab/task/barcode`。
|
||||
- 我的任务、全部任务列表中的“扫码识别”。
|
||||
- 检测任务工作台顶部“扫码关联”,会带当前任务核对归属。
|
||||
|
||||
扫描枪使用 USB HID 键盘模式,结尾发送 Enter;也可手动输入。未登记条码须由有权限人员选择已有、启用且有零部件编号的样品登记。多个可关联任务必须手选;一个任务的同一种零部件已有另一件实物时阻止覆盖,需先说明原因并解除原关联。
|
||||
|
||||
扫码界面支持登记、选择任务、绑定、解除、改绑、停用、审计历史和扫描枪前后缀设置。仅管理员角色初始获得新增权限,其他角色通过原角色管理分配 `lab:barcode:query/register/bind/rebind`,任务明细仍要求 `lab:task:query`。
|
||||
|
||||
## 与本系统的适配
|
||||
|
||||
- 进入任务使用 `DimensionWorkbench`,资源准备、扫描执行、比对资料与成果继续使用现有流程。
|
||||
- 原始扫描、补扫、重试按实际执行编号及样件 ID 定位,不将旧模块的 Selection 状态当作本系统工作流状态。
|
||||
- 比对入口根据本系统 `lab_dimension_comparison` 的任务、租户和来源执行读取;不导入供应商另一套任务或结果状态机。
|
||||
- 原有测量批次和历史报告若确有执行关联,仍可追溯。新的比对归档继续在现有“比对与成果”查看。
|
||||
- 前后缀只在原始输入规范化时去掉一次,登记、绑定和审计查询复用已识别条码时携带 `barcodeNormalized`;仍校验长度和控制字符。修正了连续调用时重复剥离前后缀的问题。
|
||||
- 查询中禁止重复回车;面板卸载后不再根据迟到的识别回执自动发起绑定。
|
||||
- 保留来源代码的“同任务、同零部件只关联一件实物”限制。条码用于身份追踪,不把现有扫描成果重新拆成按条码生成的一套结果;多件样品仍由原工作台选择样件。
|
||||
|
||||
## 升级方式
|
||||
|
||||
新增四张独立表:`lab_piece_barcode`、`lab_piece_barcode_binding`、`lab_piece_barcode_audit`、`lab_barcode_scan_profile`。迁移文件 `am-backend/sql/freescan/019_barcode.sql` 已纳入 `bootstrap_standalone.py` 的新增结构白名单、升级清单与部署验证。
|
||||
|
||||
`scripts/upgrade_barcode.py` 在升级中只新增扫码菜单及管理员授权。菜单 ID 与现有功能冲突时明确停止,不覆盖已有菜单,不自动给其他角色增加写权限。原业务数据、菜单重组、私有设备地址和证书保持。
|
||||
|
||||
用户明确要求发布后,按原 `deploy/windows11/update.ps1` 流程更新。不要重跑初始化或导入全量数据。更新完成后重新登录刷新菜单;其他使用者按需分配扫码权限。本次开发验证与代码发布在开发端完成;正式环境由正式端 AI 在用户确认现场空闲后通过更新脚本部署,本机不操作正式环境。
|
||||
|
||||
## 远端合并
|
||||
|
||||
发布前已快进到远端 `a16f16e`,保留其设备告警、坐标系按名称调用、AGV 完成回执、CAD 特征与标定窗口修改。升级清单同时保留 `018_inspection_cad_features.sql` 和本批 `019_barcode.sql`。合并后的平台前后端完整打包通过,扫描预览和坐标系原有前端回归 17 项通过。
|
||||
|
||||
## 验证范围
|
||||
|
||||
- 原供应商扫码匹配规则 5 项、本项目原有尺寸比对 14 项回归通过,后端完整打包通过。
|
||||
- 23 项接口场景检查通过:非法字符、未登记、准确识别、唯一/多个任务、绑定幂等、第二件拦截、解除、停用、原因必填、改绑约束、重复登记拦截、未登录拦截、已结束任务只读、前后缀只处理一次及操作审计等。
|
||||
- 只读核对一条既有扫描任务的执行追溯,无真实任务绑定和状态推进。
|
||||
- 新结构和菜单执行两次,第二次不重复创建。独立部署离线资产验证通过;最终 standalone 前端完整构建通过。
|
||||
- 浏览器自动化进程因本机 `CreateProcessWithLogonW failed: 32` 未能启动,页面交互尚未完成自动验收;实体扫描枪未实测。没有执行真实设备动作或计算。
|
||||
- 本轮测试条码、两个临时任务和两个临时样品已按明确 ID 与唯一前缀清理,扫描枪配置已恢复。
|
||||
|
||||
供应商提交号、手册文件指纹与排除范围见 [barcode-source.json](barcode-source.json)。
|
||||
28
docs/barcode-source.json
Normal file
28
docs/barcode-source.json
Normal file
@ -0,0 +1,28 @@
|
||||
{
|
||||
"feature": "扫码识别与任务关联",
|
||||
"supplierFrontend": {
|
||||
"branch": "master",
|
||||
"commit": "4880c1832c4f04cd37bc02bd4dddc35d3e9545b7"
|
||||
},
|
||||
"supplierBackend": {
|
||||
"branch": "master-jdk17",
|
||||
"commit": "850f96456bc7d2167c64656705b9d1765c9dfd0e"
|
||||
},
|
||||
"manual": {
|
||||
"name": "扫码识别与任务关联_用户操作手册_V1.0_含代码清单(1).docx",
|
||||
"sha256": "9e9fe41bfc5949e1c8c1e8448a083826e3d0af71ca0d646ee8d6675c9dd99b49"
|
||||
},
|
||||
"adaptations": [
|
||||
"existing task, unit, scan execution and dimension-workbench navigation",
|
||||
"barcode identity only; no automatic device operation or computation",
|
||||
"canonical barcode reuse; scanner affixes stripped once",
|
||||
"administrator-only initial permission grants"
|
||||
],
|
||||
"migration": "am-backend/sql/freescan/019_barcode.sql",
|
||||
"excluded": [
|
||||
"MES barcode modules",
|
||||
"supplier integration-center modules",
|
||||
"replacement task/scan state machines",
|
||||
"unrelated 3D/feature-plan updates"
|
||||
]
|
||||
}
|
||||
@ -136,7 +136,7 @@ def load_assets():
|
||||
seeds = {}
|
||||
for path in sorted(SQL_ROOT.glob("*.sql")):
|
||||
if path.name.endswith("_schema.sql") or path.name in {"005_scan_only.sql", "006_resource_scheduling.sql",
|
||||
"007_scanner_integration.sql", "008_scanner_execution_view.sql", "009_rotary_base_integration.sql", "010_scanner_framework_reference.sql", "011_fixture_framework.sql", "012_robot_service_endpoint.sql", "013_execution_plan.sql", "014_dimension_delivery.sql", "015_fixture_trajectory.sql", "017_dimension_comparison.sql", "018_inspection_cad_features.sql"}:
|
||||
"007_scanner_integration.sql", "008_scanner_execution_view.sql", "009_rotary_base_integration.sql", "010_scanner_framework_reference.sql", "011_fixture_framework.sql", "012_robot_service_endpoint.sql", "013_execution_plan.sql", "014_dimension_delivery.sql", "015_fixture_trajectory.sql", "017_dimension_comparison.sql", "018_inspection_cad_features.sql", "019_barcode.sql"}:
|
||||
# Dedicated additive migration runs after bootstrap_cmvr. It is not
|
||||
# a reference seed and must never pass through the seed executor.
|
||||
continue
|
||||
|
||||
@ -15,6 +15,7 @@ from urllib.parse import urlparse
|
||||
import bootstrap_db as base
|
||||
import bootstrap_cmvr as native
|
||||
from apply_scan_only import apply_schema, load_migration
|
||||
from upgrade_barcode import ensure_barcode_navigation
|
||||
|
||||
OWNER = "am-freescan/standalone-v1"
|
||||
IDLE_QUERIES = (
|
||||
@ -35,7 +36,7 @@ MIGRATIONS = (
|
||||
"008_scanner_execution_view.sql", "009_rotary_base_integration.sql",
|
||||
"010_scanner_framework_reference.sql", "011_fixture_framework.sql",
|
||||
"012_robot_service_endpoint.sql", "013_execution_plan.sql", "014_dimension_delivery.sql",
|
||||
"015_fixture_trajectory.sql", "017_dimension_comparison.sql", "018_inspection_cad_features.sql",
|
||||
"015_fixture_trajectory.sql", "017_dimension_comparison.sql", "018_inspection_cad_features.sql", "019_barcode.sql",
|
||||
)
|
||||
|
||||
def plan():
|
||||
@ -126,7 +127,8 @@ def main(argv=None):
|
||||
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)))
|
||||
ensure_barcode_navigation(cursor)
|
||||
print(json.dumps(dict(upgraded=True, additiveChanges=changes, usersAndMenusPreserved=True, barcodeNavigationInstalled=True)))
|
||||
finally:
|
||||
cursor.execute("SELECT RELEASE_LOCK(%s)", (OWNER,))
|
||||
return 0
|
||||
@ -145,7 +147,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", "lab_dimension_comparison", "lab_inspection_scan", "lab_inspection_template"}:
|
||||
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", "lab_piece_barcode", "lab_piece_barcode_binding", "lab_piece_barcode_audit", "lab_barcode_scan_profile"}:
|
||||
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)
|
||||
@ -175,6 +177,7 @@ def main(argv=None):
|
||||
cursor.execute(f"INSERT INTO `{base.META}` (name,value) VALUES(%s,%s) ON DUPLICATE KEY UPDATE value=VALUES(value)", (filename, checksum))
|
||||
native.references(cursor, reference)
|
||||
base.finalize_permissions(cursor)
|
||||
ensure_barcode_navigation(cursor)
|
||||
native.verify_references(cursor, reference)
|
||||
print(json.dumps(dict(initialized=True, target="127.0.0.1/am-freescan", additiveChanges=changed,
|
||||
user="admin", passwordPrinted=False, originalBusinessDataImported=False)))
|
||||
|
||||
31
scripts/upgrade_barcode.py
Normal file
31
scripts/upgrade_barcode.py
Normal file
@ -0,0 +1,31 @@
|
||||
"""Add only barcode navigation and administrator permissions; preserve existing menus and roles."""
|
||||
def ensure_barcode_navigation(cursor):
|
||||
menus = [
|
||||
(20140, '扫码识别', 'lab:barcode:query', 2, 4, 20100, 'barcode', 'ep:aim', 'lab/barcode/index', 'LabBarcodeWorkbench'),
|
||||
(20141, '条码登记', 'lab:barcode:register', 3, 1, 20140, '', '', '', ''),
|
||||
(20142, '条码关联任务', 'lab:barcode:bind', 3, 2, 20140, '', '', '', ''),
|
||||
(20143, '条码管理', 'lab:barcode:rebind', 3, 3, 20140, '', '', '', ''),
|
||||
]
|
||||
cursor.execute('SELECT id FROM system_menu WHERE id=20100 AND deleted=0')
|
||||
if not cursor.fetchone():
|
||||
raise ValueError('Task center menu is missing; barcode navigation cannot be installed')
|
||||
for menu in menus:
|
||||
cursor.execute('SELECT permission,component,parent_id FROM system_menu WHERE id=%s', (menu[0],))
|
||||
existing = cursor.fetchone()
|
||||
if existing:
|
||||
if tuple(existing) != (menu[2], menu[8], menu[5]):
|
||||
raise ValueError('Barcode menu ID conflicts with an existing menu: '+str(menu[0]))
|
||||
continue
|
||||
cursor.execute('INSERT INTO system_menu (id,name,permission,type,sort,parent_id,path,icon,component,component_name,status,visible,keep_alive,always_show,creator,updater,deleted) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,0,1,1,1,\'1\',\'1\',0)', menu)
|
||||
# New write permissions are not silently granted to task readers or other existing roles.
|
||||
cursor.execute("SELECT id,tenant_id FROM system_role WHERE code IN ('super_admin','admin') AND deleted=0 AND status=0")
|
||||
roles = list(cursor.fetchall())
|
||||
cursor.execute('SELECT COALESCE(MAX(id),100000) FROM system_role_menu')
|
||||
next_id = cursor.fetchone()[0]
|
||||
for role, tenant in roles:
|
||||
for menu in menus:
|
||||
cursor.execute('SELECT id FROM system_role_menu WHERE role_id=%s AND menu_id=%s AND tenant_id=%s AND deleted=0', (role,menu[0],tenant))
|
||||
if cursor.fetchone():
|
||||
continue
|
||||
next_id += 1
|
||||
cursor.execute('INSERT INTO system_role_menu (id,role_id,menu_id,creator,updater,deleted,tenant_id) VALUES (%s,%s,%s,\'1\',\'1\',0,%s)', (next_id,role,menu[0],tenant))
|
||||
Loading…
Reference in New Issue
Block a user