组件新增状态字段,禁用状态不参与拼装

This commit is contained in:
lxp
2026-10-20 18:07:55 +08:00
parent 5d94bc7871
commit 7eef6e3994
21 changed files with 265 additions and 16 deletions
+23 -4
View File
@@ -144,6 +144,7 @@ POST 和 PUT 使用扁平 JSON。新增业务字段仅 `stepObjectKey` 必填,
| --- | --- | --- |
| componentName | string | POST 可选,默认 `""`;PUT 必填、非空;最多 128 字符,允许同名 |
| category | string | POST 可选,默认 `""`;PUT 必填、非空;最多 64 字符,自由分类 |
| status | string / null | 仅接受 `ENABLED`(启用)、`DISABLED`(禁用);POST 省略或为 null 时默认启用,PUT 省略或为 null 时保留原状态 |
| description | string | 默认 `""`,UTF-8 不超过 65535 字节 |
| material | string | 默认 `""`,最多 128 字符 |
| massKg | number | 默认 0,千克,非负 |
@@ -158,7 +159,7 @@ POST 和 PUT 使用扁平 JSON。新增业务字段仅 `stepObjectKey` 必填,
| basicFields | 自定义字段数组 | 默认 `[]`,基本信息扩展字段 |
| parameterFields | 自定义字段数组 | 默认 `[]`,零件参数扩展字段 |
质量和扭矩最多 12 位整数、6 位小数,与 `DECIMAL(18,6)` 一致;不要在数值中提交单位文本。可选字段省略或传 null 会恢复默认值。名称、分类、材质、功能、形状和大小会裁剪首尾空白。
质量和扭矩最多 12 位整数、6 位小数,与 `DECIMAL(18,6)` 一致;不要在数值中提交单位文本。除 PUT 的 `status` 保留原值外,可选字段省略或传 null 会恢复默认值。名称、分类、材质、功能、形状和大小会裁剪首尾空白。
`bomList` 和 `urdfInfo` 直接提交 JSON 对象或数组,不接受字符串化的 JSON、数字或布尔值。`bomList` 省略或为 null 时保存为空数组;新增时 `urdfInfo` 省略或为 null 也保存为空数组,修改时仍须提供 JSON 对象或数组。两者内部字段不做固定结构校验,`urdfInfo` 由前端提供,不由后端解析 URDF 文件生成。
@@ -173,7 +174,9 @@ POST 和 PUT 使用扁平 JSON。新增业务字段仅 `stepObjectKey` 必填,
每组最多 100 项,名称非空且最多 64 字符,值为非 null 字符串、最多 2000 字符,可以为空字符串。同组名称裁剪后不可重复,两组之间可以重名;顺序与请求一致。
PUT 是全量表单更新,前端应提交完整表单,每次都必须提交 `urdfInfo`。省略可选字段会恢复默认值,提交空数组可清空 BOM 或自定义字段。
PUT 是全量表单更新,前端应提交完整表单,每次都必须提交 `urdfInfo`。除 `status` 外,省略可选字段会恢复默认值,提交空数组可清空 BOM 或自定义字段。
`status` 对应数据库 `status`,新增和存量组件默认 `ENABLED`。通过现有 PUT 编辑接口切换状态,仍须提交完整必填表单和最新 `version`,保存成功后版本递增。非法状态(包括小写、空字符串和数字)返回 422。禁用组件仍可在管理端列表、详情中查看和编辑,也可重新启用;禁用后不参与新生成的结构化匹配、AI 拼装或替代候选。用户端按编码查询详情、历史生成结果和已保存项目继续可查看。
`rotationAxis` 对应数据库 `rotation_axis`,下拉选项值使用 `X`、`Y`、`Z`;未设置时返回 null。PUT 省略该字段或传 null 会清空已有旋转轴。该字段是组件元数据,不替代 `urdfInfo` 中每个关节的 axis。
@@ -202,6 +205,19 @@ ALTER TABLE `component`
AFTER `degrees_of_freedom`;
```
### 4.4 组件状态字段部署
部署管理端和用户端新代码前,在两端使用的组件数据库中手动执行以下 SQL。已有记录自动获得启用状态,应用不会自动执行迁移;仓库 `.sql` 文件不修改。
```sql
ALTER TABLE `component`
ADD COLUMN `status` ENUM('ENABLED', 'DISABLED')
CHARACTER SET ascii COLLATE ascii_bin
NOT NULL DEFAULT 'ENABLED'
COMMENT '组件状态:ENABLED-启用,DISABLED-禁用'
AFTER `category`;
```
## 5. 组件接口
### 5.1 新增
@@ -215,12 +231,13 @@ ALTER TABLE `component`
}
```
其余业务字段按默认值保存;`bomList`、`urdfInfo` 虽为 NOT NULL,后端会显式写入空数组。部署前须完成上面的旋转轴字段迁移。需要填写元数据或上传 URDF 时,可提交完整请求:
其余业务字段按默认值保存;`bomList`、`urdfInfo` 虽为 NOT NULL,后端会显式写入空数组。部署前须完成上面的旋转轴和组件状态字段迁移。需要填写元数据或上传 URDF 时,可提交完整请求:
```json
{
"componentName":"四孔安装板",
"category":"安装板",
"status":"ENABLED",
"description":"用于固定机械组件",
"material":"铝合金",
"massKg":0.35,
@@ -255,6 +272,7 @@ ALTER TABLE `component`
"componentCode":"CW-7K3M9Q2R6V8X4T5N",
"componentName":"四孔安装板",
"category":"安装板",
"status":"ENABLED",
"description":"用于固定机械组件",
"material":"铝合金",
"massKg":0.35,
@@ -292,6 +310,7 @@ ALTER TABLE `component`
"version":1,
"componentName":"四孔安装板 V2",
"category":"安装板",
"status":"ENABLED",
"description":"更新说明",
"material":"铝合金",
"massKg":0.35,
@@ -331,7 +350,7 @@ ALTER TABLE `component`
| keyword | 名称或编码模糊查询 |
| category | 分类精确筛选 |
`items` 每项包含 `id`、`componentCode`、`componentName`、`category`、`description`、`degreesOfFreedom`、`rotationAxis`、`functionDescription`、`shape`、`size`、`torqueNm`、`stepUrl`、`urdfUrl`、`version`、`createdAt`、`updatedAt`。列表不查询或返回 `bomList`、`urdfInfo`、自定义表单和 URDF 文件清单。编辑先获取详情;创建和修改成功返回完整组件详情,包含旋转轴。
`items` 每项包含 `id`、`componentCode`、`componentName`、`category`、`status`、`description`、`degreesOfFreedom`、`rotationAxis`、`functionDescription`、`shape`、`size`、`torqueNm`、`stepUrl`、`urdfUrl`、`version`、`createdAt`、`updatedAt`。列表不查询或返回 `bomList`、`urdfInfo`、自定义表单和 URDF 文件清单。编辑先获取详情;创建和修改成功返回完整组件详情,包含状态和旋转轴。
列表查询参数 `size` 是每页条数,响应 `items` 内的 `size` 是组件大小描述。
@@ -234,6 +234,71 @@ class AdminApiTest {
.isEqualTo(changed);
}
@Test
void componentStatusDefaultsToEnabledWhenOmittedOrNull() throws Exception {
JsonNode omitted = create(uploaded());
Map<String, Object> body = uploaded();
body.put("status", null);
JsonNode explicitNull = create(body);
for (JsonNode created : List.of(omitted, explicitNull)) {
assertThat(created.path("status").asText()).isEqualTo("ENABLED");
assertThat(componentMapper.selectById(created.path("id").asLong()).getStatus().name()).isEqualTo("ENABLED");
}
}
@Test
void componentStatusRoundTripsAndOmittedUpdatesPreserveDisabledStatus() throws Exception {
Map<String, Object> body = uploaded();
body.put("status", "DISABLED");
JsonNode created = create(body);
long id = created.path("id").asLong();
assertThat(created.path("status").asText()).isEqualTo("DISABLED");
mvc.perform(get("/admin-api/components/{id}", id)).andExpect(status().isOk())
.andExpect(jsonPath("$.data.status").value("DISABLED"));
mvc.perform(get("/admin-api/components").param("keyword", created.path("componentCode").asText()))
.andExpect(status().isOk()).andExpect(jsonPath("$.data.items[0].status").value("DISABLED"));
for (long version = 1; version <= 2; version++) {
Map<String, Object> form = update(version);
if (version == 2) form.put("status", null);
JsonNode changed = data(mvc.perform(put("/admin-api/components/{id}", id).contentType(MediaType.APPLICATION_JSON)
.content(json.writeValueAsString(form))).andExpect(status().isOk()).andReturn());
assertThat(changed.path("status").asText()).isEqualTo("DISABLED");
assertThat(changed.path("version").asLong()).isEqualTo(version + 1);
}
Map<String, Object> enable = update(3);
enable.put("status", "ENABLED");
JsonNode enabled = data(mvc.perform(put("/admin-api/components/{id}", id).contentType(MediaType.APPLICATION_JSON)
.content(json.writeValueAsString(enable))).andExpect(status().isOk()).andReturn());
assertThat(enabled.path("status").asText()).isEqualTo("ENABLED");
assertThat(enabled.path("version").asLong()).isEqualTo(4);
Map<String, Object> disable = update(4);
disable.put("status", "DISABLED");
mvc.perform(put("/admin-api/components/{id}", id).contentType(MediaType.APPLICATION_JSON)
.content(json.writeValueAsString(disable))).andExpect(status().isOk())
.andExpect(jsonPath("$.data.status").value("DISABLED"));
expectUpdateError(id, enable, 409, "COMPONENT_REVISION_CONFLICT");
assertThat(componentMapper.selectById(id).getStatus().name()).isEqualTo("DISABLED");
assertThat(componentMapper.selectById(id).getVersion()).isEqualTo(5L);
}
@Test
void invalidComponentStatusValuesNeverCreateOrUpdateComponents() throws Exception {
long id = create(uploaded()).path("id").asLong();
Map<String, Object> body = uploaded();
Map<String, Object> form = update(1);
for (Object invalid : List.of("", "enabled", "disabled", " ENABLED ", "ACTIVE", 0, 1, true,
List.of("ENABLED"), Map.of("status", "ENABLED"))) {
body.put("status", invalid);
form.put("status", invalid);
expectCreateError(body, 422, "INVALID_REQUEST");
expectUpdateError(id, form, 422, "INVALID_REQUEST");
}
assertThat(count("component")).isEqualTo(1);
assertThat(componentMapper.selectById(id).getStatus().name()).isEqualTo("ENABLED");
assertThat(componentMapper.selectById(id).getVersion()).isEqualTo(1L);
}
@ParameterizedTest
@ValueSource(strings = {"X", "Y", "Z"})
void rotationAxisRoundTripsThroughCreateUpdateDetailAndList(String axis) throws Exception {
@@ -15,6 +15,7 @@ final class TestSchemaSupport {
component_code VARCHAR(64) NOT NULL DEFAULT '' UNIQUE,
component_name VARCHAR(128) NOT NULL DEFAULT '',
category VARCHAR(64) NOT NULL DEFAULT '',
status VARCHAR(16) NOT NULL DEFAULT 'ENABLED' CHECK (status IN ('ENABLED','DISABLED')) COMMENT '组件状态:ENABLED-启用,DISABLED-禁用',
description CLOB NOT NULL DEFAULT '',
material VARCHAR(128) NOT NULL DEFAULT '',
mass_kg DECIMAL(18,6) NOT NULL DEFAULT 0,
+3 -1
View File
@@ -181,6 +181,8 @@ ARM、HAND、LEG、FOOT 的父接口采用单向兼容:L 可接 L/0,R 可接
拼装候选必须同时有非空 STEP 和 URDF 主文件引用,仅上传 STEP 的组件仍只支持详情查询。接口以合法 interfaceType 决定目标 category,缺失/无效时从 child 的 LINK_ 后解析现有类别;双方 frames[].child 须非空并符合上述单向兼容规则,name 不参与判断。每个数组元素为独立接口,同child的多个接口不合并,连接双方各自只能占用一次。固定躯干后优先处理最近层级的接口,先满足所需类型和明确数量,再填充其余可匹配接口,不引入未要求的类型。自动增补不应破坏本可满足的硬要求;例如质量上限或指定总自由度会约束自动填充数量。坐标、安装基准、关节类型和rootLink不作为连接资格的阻塞条件,缺失接口则返回已有连通部分。
候选还必须处于启用状态(`status=ENABLED`);禁用组件不会进入新拼装方案或替代候选。禁用不影响用户端按编码查看组件详情、历史生成结果或已保存项目。生成结果加载阶段发现组件已禁用时,沿用 `409 / COMPONENT_REVISION_CONFLICT`,需要重新匹配。
`bomList` 和 `urdfInfo` 始终作为原始 JSON 返回,保留嵌套内容;详情里的 `urdfInfo` 也可能是其他对象或数组。接口匹配只评价元数据和连接类型,不验证机械承载或运动性能。
## 4. 匹配结果
@@ -789,7 +791,7 @@ HTTP 200,完整响应示例:
}
```
返回字段见 4.2。详情可能返回不满足拼装要求的原始 `urdfInfo`,查看详情不表示该组件一定可以参与匹配。
返回字段见 4.2。禁用组件仍可查询详情;详情可能返回不满足拼装要求的原始 `urdfInfo`,查看详情不表示该组件一定可以参与匹配。
## 6. 错误响应
+2
View File
@@ -14,6 +14,8 @@
`GET /api/projects` 即“我的工作空间”。项目装配内容保存后固定,只能修改名称、简介、封面和发布状态;重新拼装后另存一个项目。不提供任意模型文件上传、替换或文件编辑接口。
组件禁用只影响新拼装方案和替代候选,不影响已保存项目的独立装配快照及展示。
| 方法 | 路径 | 请求 | 用途 |
| --- | --- | --- | --- |
| POST | `/api/projects` | 创建 JSON | 保存生成结果 |
+2
View File
@@ -593,6 +593,8 @@ async function sendMessage(token, conversationId, message, onEvent, signal) {
### 躯干优先规则
新生成方案及替代候选仅使用启用状态(`status=ENABLED`)的组件;禁用组件仍可按编码查询详情,历史生成结果和已保存项目继续保留。生成结果和资源回查发现组件已禁用时,沿用 `COMPONENT_REVISION_CONFLICT` 业务错误;SSE 返回 `analysis.failed` 事件,需要发送新消息重新生成方案。
拼装仅检索同时具备非空 `step_object_key` 和已上传 URDF 主文件(非空 `urdf_main_object_key`)的组件;消息自动生成和替代候选使用同一筛选规则。仅上传 STEP 的组件不会参与拼装。接口以合法 `interfaceType` 确定目标 category,缺失或无效时从 `child` 的 LINK_ 后解析现有类别;只连接用户需求涉及的装配角色,双方原始 `frames[].child` 必须非空:完全相等时可连接;ARM/HAND/LEG/FOOT 的父 L/R 接口还可连接同部位的 0 接口,父 0 只接 0,L/R 不能互接。新增兼容仅替换标准编码末尾方向位(支持大写 L/R、小写 l/r),其余字符区分大小写保持一致。`name` 不参与兼容性判断。无法识别类型或无有效 child 的接口跳过并提示,不阻塞已有组合。
整机结果始终以 `TORSO_0` 为根,默认方案中的躯干只有一个。用户未单独提出躯干时,后端在规范化的 `requiredParts` 中补入 `TORSO_0` 并返回说明;原始对话和提取的用户条目保持其来源。明确要求“不要躯干”时保留排除项,返回 `no_match`、`missingParts.reason=EXCLUDED_TORSO`,不会偷偷补入躯干;同款组件支持多个独立实例,躯干始终固定一个。
@@ -79,6 +79,7 @@ class DemandFlowApiTest {
@Autowired private com.linkerbot.cadworld.service.demand.DemandAttachmentStore attachments;
@MockitoBean private DemandModelClient model;
@MockitoSpyBean private DemandMatchService matches;
@MockitoSpyBean private com.linkerbot.cadworld.service.matching.RobotMatchingService matching;
@Autowired @org.springframework.beans.factory.annotation.Qualifier("requestMappingHandlerMapping")
private RequestMappingHandlerMapping mappings;
@@ -95,6 +96,7 @@ class DemandFlowApiTest {
CREATE TABLE IF NOT EXISTS component (
id BIGINT AUTO_INCREMENT PRIMARY KEY,component_code VARCHAR(64) NOT NULL UNIQUE,
component_name VARCHAR(128) NOT NULL DEFAULT '',category VARCHAR(64) NOT NULL DEFAULT '',
status VARCHAR(16) NOT NULL DEFAULT 'ENABLED' CHECK (status IN ('ENABLED','DISABLED')),
description CLOB NOT NULL DEFAULT '',material VARCHAR(128) NOT NULL DEFAULT '',
mass_kg DECIMAL(18,6) NOT NULL DEFAULT 0,degrees_of_freedom INT NOT NULL DEFAULT 0,
rotation_axis CHAR(1) DEFAULT NULL CHECK (rotation_axis IN ('X','Y','Z')),
@@ -668,6 +670,58 @@ class DemandFlowApiTest {
assertThat(refreshed.path("alternatives").findValuesAsText("componentCode")).doesNotContain("CW-ARM");
}
@Test void disablingComponentsOnlyAffectsNewMessagesAndPreservesHistoricalResults() throws Exception {
components(true, 20);
Session session = create();
JsonNode completed = submit(session, "m1", TEXT, List.of());
String analysisId = completed.path("analysisId").asText();
JsonNode original = completed.path("match");
assertThat(original.path("components").findValuesAsText("componentCode")).containsExactly("CW-TORSO", "CW-ARM");
assertThat(original.path("alternatives").findValuesAsText("componentCode")).contains("CW-ARM-ALT");
jdbc.update("UPDATE component SET status='DISABLED',version=version+1 WHERE category='ARM_R'");
JsonNode historical = data(mvc.perform(get("/api/robot-analyses/" + analysisId)
.header("Authorization", "Bearer " + session.token())).andExpect(status().isOk()).andReturn());
assertThat(historical.path("match")).isEqualTo(original);
mvc.perform(get("/api/components/CW-ARM")).andExpect(status().isOk())
.andExpect(jsonPath("$.data.componentCode").value("CW-ARM"))
.andExpect(jsonPath("$.data.id").doesNotExist());
JsonNode partial = submit(session, "m2", TEXT, List.of()).path("match");
assertThat(partial.path("status").asText()).isEqualTo("partial");
assertThat(partial.path("components").findValuesAsText("componentCode")).containsExactly("CW-TORSO");
assertThat(partial.path("alternatives").findValuesAsText("componentCode")).doesNotContain("CW-ARM", "CW-ARM-ALT");
jdbc.update("UPDATE component SET status='ENABLED',version=version+1 WHERE component_code='CW-ARM-ALT'");
JsonNode restored = submit(session, "m3", TEXT, List.of()).path("match");
assertThat(restored.path("status").asText()).isEqualTo("complete");
assertThat(restored.path("components").findValuesAsText("componentCode")).containsExactly("CW-TORSO", "CW-ARM-ALT");
assertThat(restored.path("alternatives").findValuesAsText("componentCode")).doesNotContain("CW-ARM");
jdbc.update("UPDATE component SET status='DISABLED',version=version+1");
JsonNode empty = submit(session, "m4", TEXT, List.of()).path("match");
assertThat(empty.path("status").asText()).isEqualTo("no_match");
assertThat(empty.path("components")).isEmpty();
assertThat(empty.path("alternatives")).isEmpty();
}
@Test void disablingComponentBeforeResourceLookupFailsWithoutSavingMatch() throws Exception {
components(true, 20);
doAnswer(invocation -> {
Object response = invocation.callRealMethod();
// 保持版本不变,独立验证资源回查阶段的状态校验。
jdbc.update("UPDATE component SET status='DISABLED' WHERE component_code='CW-ARM'");
return response;
}).when(matching).matchConfirmed(org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.anySet(),
org.mockito.ArgumentMatchers.anyList(), org.mockito.ArgumentMatchers.anySet());
Session session = create();
MvcResult pending = message(session, "m-disabled-during-match", TEXT, List.of());
pending.getAsyncResult(5000);
mvc.perform(asyncDispatch(pending)).andExpect(status().isOk());
assertThat(pending.getResponse().getContentAsString()).contains("event:analysis.failed", "COMPONENT_REVISION_CONFLICT")
.doesNotContain("event:analysis.completed");
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM robot_demand_match", Integer.class)).isZero();
}
@Test void prefersRequirementsOnlyAfterHardRequirementsAndDoesNotRequireDegradationForPreferences() throws Exception {
components(true, 20);
jdbc.update("UPDATE component SET mass_kg=8,torque_nm=40 WHERE component_code='CW-ARM-ALT'");
@@ -6,6 +6,7 @@ import ch.qos.logback.core.read.ListAppender;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.linkerbot.cadworld.common.web.RequestIdFilter;
import com.linkerbot.cadworld.common.exception.BizException;
import com.linkerbot.cadworld.config.MatchingProperties;
import com.linkerbot.cadworld.dto.matching.RobotMatchRequest;
import com.linkerbot.cadworld.dto.matching.RobotMatchResponse;
@@ -36,11 +37,13 @@ import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.http.MediaType;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
@@ -77,6 +80,7 @@ class MatchingApiTest {
id BIGINT AUTO_INCREMENT PRIMARY KEY,
component_code VARCHAR(64) NOT NULL DEFAULT '' UNIQUE,
component_name VARCHAR(128) NOT NULL DEFAULT '', category VARCHAR(64) NOT NULL DEFAULT '',
status VARCHAR(16) NOT NULL DEFAULT 'ENABLED' CHECK (status IN ('ENABLED','DISABLED')),
description CLOB NOT NULL DEFAULT '', material VARCHAR(128) NOT NULL DEFAULT '',
mass_kg DECIMAL(18,6) NOT NULL DEFAULT 0, degrees_of_freedom INT NOT NULL DEFAULT 0,
rotation_axis CHAR(1) DEFAULT NULL CHECK (rotation_axis IN ('X','Y','Z')),
@@ -963,6 +967,42 @@ class MatchingApiTest {
assertThat(component.get("urdfInfo").isContainerNode()).isTrue();
}
@Test
void disabledComponentsAreExcludedFromNewMatchesAndAlternativesButRemainReadable() throws Exception {
save("CW-A", "TORSO_0", 0, "1", "0", "");
save("CW-B", "TORSO_0", 0, "1", "0", "");
save("CW-C", "TORSO_0", 0, "1", "0", "");
JsonNode original = match(request("TORSO_0"));
assertThat(part(original, "TORSO_0").path("componentCode").asText()).isEqualTo("CW-A");
assertThat(alternatives(original, "TORSO_0").findValuesAsText("componentCode")).contains("CW-B", "CW-C");
jdbc.update("UPDATE component SET status='DISABLED',version=version+1 WHERE component_code IN ('CW-A','CW-C')");
JsonNode refreshed = match(request("TORSO_0"));
assertThat(part(refreshed, "TORSO_0").path("componentCode").asText()).isEqualTo("CW-B");
assertThat(refreshed.path("alternatives").findValuesAsText("componentCode")).doesNotContain("CW-A", "CW-C");
mvc.perform(get("/api/components/CW-A")).andExpect(status().isOk())
.andExpect(jsonPath("$.data.componentCode").value("CW-A"))
.andExpect(jsonPath("$.data.id").doesNotExist());
jdbc.update("UPDATE component SET status='DISABLED' WHERE component_code='CW-B'");
JsonNode empty = match(request("TORSO_0"));
assertThat(empty.path("status").asText()).isEqualTo("NO_MATCH");
assertThat(empty.path("parts")).isEmpty();
assertThat(empty.path("alternatives")).isEmpty();
jdbc.update("UPDATE component SET status='ENABLED',version=version+1 WHERE component_code='CW-A'");
assertThat(part(match(request("TORSO_0")), "TORSO_0").path("componentCode").asText()).isEqualTo("CW-A");
}
@Test
void disablingCandidateBeforeResultLoadReturnsRevisionConflict() throws Exception {
save("CW-A", "TORSO_0", 0, "1", "0", "");
Map<String, ?> enabled = ReflectionTestUtils.invokeMethod(components, "load", List.of("CW-A"));
assertThat(enabled).containsKey("CW-A");
jdbc.update("UPDATE component SET status='DISABLED' WHERE component_code='CW-A'");
assertThatThrownBy(() -> ReflectionTestUtils.invokeMethod(components, "load", List.of("CW-A")))
.isInstanceOf(BizException.class).extracting("code").isEqualTo("COMPONENT_REVISION_CONFLICT");
}
private JsonNode metadata(String root, String... ports) {
List<Map<String, Object>> frames = new ArrayList<>();
for (int index = 0; index < ports.length; index++) {
@@ -146,6 +146,20 @@ class ProjectApiTest {
assertThat(detail.path("snapshot")).isEqualTo(created.path("snapshot"));
}
@Test
void disabledComponentDoesNotChangeSavedProjectSnapshot() throws Exception {
// 项目只依赖独立快照,此表仅模拟组件状态变化,不参与项目查询。
jdbc.execute("CREATE TABLE IF NOT EXISTS component (component_code VARCHAR(64) PRIMARY KEY,status VARCHAR(16) NOT NULL)");
jdbc.update("DELETE FROM component");
jdbc.update("INSERT INTO component (component_code,status) VALUES ('C-TORSO','ENABLED')");
JsonNode created = create(source(false));
jdbc.update("UPDATE component SET status='DISABLED' WHERE component_code='C-TORSO'");
JsonNode detail = data(mvc.perform(get("/api/projects/" + created.path("projectCode").asText())
.header("Authorization", bearer(token))).andExpect(status().isOk()).andReturn());
assertThat(detail.path("snapshot")).isEqualTo(created.path("snapshot"));
assertThat(detail.findValues("id")).isEmpty();
}
@Test
void privateOperationsRequireLoginAndOwnership() throws Exception {
String code = create(source(false)).path("projectCode").asText();
@@ -1,6 +1,7 @@
package com.linkerbot.cadworld.dto.component;
import com.fasterxml.jackson.databind.JsonNode;
import com.linkerbot.cadworld.enums.ComponentStatus;
import com.linkerbot.cadworld.enums.RotationAxis;
import java.math.BigDecimal;
import java.util.List;
@@ -9,6 +10,7 @@ import java.util.List;
public interface ComponentForm {
String componentName();
String category();
ComponentStatus status();
String description();
String material();
BigDecimal massKg();
@@ -1,12 +1,14 @@
package com.linkerbot.cadworld.dto.component;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.linkerbot.cadworld.enums.ComponentStatus;
import com.linkerbot.cadworld.enums.RotationAxis;
import java.math.BigDecimal;
import java.time.LocalDateTime;
public record ComponentListItemResponse(
Long id, String componentCode, String componentName, String category,
ComponentStatus status,
String description, Integer degreesOfFreedom, @JsonInclude(JsonInclude.Include.ALWAYS) RotationAxis rotationAxis,
String functionDescription, String shape,
String size, BigDecimal torqueNm, String stepUrl, String urdfUrl, Long version,
@@ -2,6 +2,7 @@ package com.linkerbot.cadworld.dto.component;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.linkerbot.cadworld.enums.ComponentStatus;
import com.linkerbot.cadworld.enums.RotationAxis;
import java.math.BigDecimal;
import java.time.LocalDateTime;
@@ -9,6 +10,7 @@ import java.util.List;
public record ComponentResponse(
Long id, String componentCode, String componentName, String category,
ComponentStatus status,
String description, String material, BigDecimal massKg, Integer degreesOfFreedom,
@JsonInclude(JsonInclude.Include.ALWAYS) RotationAxis rotationAxis,
String functionDescription, String shape, String size, BigDecimal torqueNm, JsonNode bomList,
@@ -2,6 +2,7 @@ package com.linkerbot.cadworld.dto.component;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.linkerbot.cadworld.enums.ComponentStatus;
import com.linkerbot.cadworld.enums.RotationAxis;
import jakarta.validation.Valid;
import jakarta.validation.constraints.*;
@@ -11,6 +12,7 @@ import java.util.List;
public record CreateComponentRequest(
@Size(max = 128) String componentName,
@Size(max = 64) String category,
ComponentStatus status,
String description,
@Size(max = 128) String material,
@DecimalMin("0") @Digits(integer = 12, fraction = 6) BigDecimal massKg,
@@ -2,6 +2,7 @@ package com.linkerbot.cadworld.dto.component;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.linkerbot.cadworld.enums.ComponentStatus;
import com.linkerbot.cadworld.enums.RotationAxis;
import jakarta.validation.Valid;
import jakarta.validation.constraints.*;
@@ -12,6 +13,7 @@ public record UpdateComponentRequest(
@Size(max = 64) String componentCode,
@NotBlank @Size(max = 128) String componentName,
@NotBlank @Size(max = 64) String category,
ComponentStatus status,
String description,
@Size(max = 128) String material,
@DecimalMin("0") @Digits(integer = 12, fraction = 6) BigDecimal massKg,
@@ -8,6 +8,7 @@ import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.databind.JsonNode;
import com.linkerbot.cadworld.common.mybatis.JsonNodeTypeHandler;
import com.linkerbot.cadworld.enums.ComponentStatus;
import com.linkerbot.cadworld.enums.RotationAxis;
import java.math.BigDecimal;
import lombok.Getter;
@@ -22,6 +23,8 @@ public class Component extends BaseEntity {
private String componentCode;
private String componentName;
private String category;
/** 组件状态:ENABLED-启用,DISABLED-禁用。 */
private ComponentStatus status;
private String description;
private String material;
private BigDecimal massKg;
@@ -0,0 +1,14 @@
package com.linkerbot.cadworld.enums;
import com.fasterxml.jackson.annotation.JsonCreator;
/** 组件状态:启用或禁用。 */
public enum ComponentStatus {
ENABLED,
DISABLED;
@JsonCreator(mode = JsonCreator.Mode.DELEGATING)
public static ComponentStatus fromValue(String value) {
return value == null ? null : ComponentStatus.valueOf(value);
}
}
@@ -14,6 +14,7 @@ import com.linkerbot.cadworld.dto.matching.RobotMatchResponse;
import com.linkerbot.cadworld.dto.matching.RobotRequirements;
import com.linkerbot.cadworld.dto.matching.TemplatePartGroup;
import com.linkerbot.cadworld.entity.Component;
import com.linkerbot.cadworld.enums.ComponentStatus;
import com.linkerbot.cadworld.mapper.ComponentMapper;
import com.linkerbot.cadworld.service.impl.ObjectStorageUrlResolver;
import com.linkerbot.cadworld.service.matching.RobotMatchingService;
@@ -118,8 +119,13 @@ public final class DemandMatchService {
private ObjectNode component(String matchId, PublicComponentResponse part) {
Component stored = mapper.selectOne(new LambdaQueryWrapper<Component>().select(Component::getComponentCode, Component::getVersion,
Component::getUrdfPrefix, Component::getUrdfMainObjectKey, Component::getUrdfFiles).eq(Component::getComponentCode, part.componentCode()));
if (stored == null || !part.version().equals(stored.getVersion())) throw changed();
Component::getUrdfPrefix, Component::getUrdfMainObjectKey, Component::getUrdfFiles)
.eq(Component::getComponentCode, part.componentCode()).eq(Component::getStatus, ComponentStatus.ENABLED));
if (stored == null || !part.version().equals(stored.getVersion())) {
log.warn("拼装资源组件已变化 componentCode={} expectedVersion={} currentVersion={} requestId={}",
part.componentCode(), part.version(), stored == null ? null : stored.getVersion(), RequestIdHolder.get());
throw changed();
}
ObjectNode result = json.createObjectNode().put("instanceId", DemandAssemblyValidator.instance(matchId, part.instanceId()));
result.set("component", json.valueToTree(part.withInstanceId(null)));
ArrayNode resources = result.putArray("resources");
@@ -10,6 +10,7 @@ import com.linkerbot.cadworld.dto.component.ComponentResponse;
import com.linkerbot.cadworld.dto.component.CustomField;
import com.linkerbot.cadworld.dto.component.UrdfFile;
import com.linkerbot.cadworld.entity.Component;
import com.linkerbot.cadworld.enums.ComponentStatus;
import com.linkerbot.cadworld.service.impl.ComponentUploadSupport.VerifiedUrdf;
import com.linkerbot.cadworld.service.support.StorageObjectKeys;
import java.math.BigDecimal;
@@ -35,6 +36,12 @@ public class ComponentConverter {
public void applyForm(Component component, ComponentForm form, boolean requireUrdfInfo) {
component.setComponentName(text(form.componentName()));
component.setCategory(text(form.category()));
// 状态省略时保留已有值,新增组件默认启用,避免旧客户端编辑时意外启用组件。
if (form.status() != null) {
component.setStatus(form.status());
} else if (component.getStatus() == null) {
component.setStatus(ComponentStatus.ENABLED);
}
String description = form.description() == null ? "" : form.description();
if (description.getBytes(StandardCharsets.UTF_8).length > 65535) {
throw new BizException(422, "INVALID_COMPONENT_FORM", "零件说明超过TEXT字段容量");
@@ -79,7 +86,7 @@ public class ComponentConverter {
String prefix = keys.resolveComponentPath(component.getUrdfPrefix());
String main = keys.resolveComponentPath(component.getUrdfMainObjectKey());
return new ComponentResponse(component.getId(), component.getComponentCode(), component.getComponentName(),
component.getCategory(), component.getDescription(), component.getMaterial(),
component.getCategory(), component.getStatus(), component.getDescription(), component.getMaterial(),
component.getMassKg(), component.getDegreesOfFreedom(), component.getRotationAxis(), component.getFunctionDescription(),
component.getShape(), component.getSize(), component.getTorqueNm(), component.getBomList(),
component.getUrdfInfo(), read(component.getBasicFields(), FIELDS),
@@ -92,7 +99,7 @@ public class ComponentConverter {
public ComponentListItemResponse toListItem(Component component) {
return new ComponentListItemResponse(component.getId(), component.getComponentCode(), component.getComponentName(),
component.getCategory(), component.getDescription(), component.getDegreesOfFreedom(), component.getRotationAxis(),
component.getCategory(), component.getStatus(), component.getDescription(), component.getDegreesOfFreedom(), component.getRotationAxis(),
component.getFunctionDescription(), component.getShape(), component.getSize(), component.getTorqueNm(),
urls.resolvePublicUrl(keys.resolveComponentPath(component.getStepObjectKey())),
urls.resolvePublicUrl(keys.resolveComponentPath(component.getUrdfMainObjectKey())), component.getVersion(),
@@ -12,6 +12,7 @@ import com.linkerbot.cadworld.dto.component.ComponentResponse;
import com.linkerbot.cadworld.dto.component.CreateComponentRequest;
import com.linkerbot.cadworld.dto.component.UpdateComponentRequest;
import com.linkerbot.cadworld.entity.Component;
import com.linkerbot.cadworld.enums.ComponentStatus;
import com.linkerbot.cadworld.mapper.ComponentMapper;
import com.linkerbot.cadworld.service.ComponentService;
import com.linkerbot.cadworld.service.impl.ComponentUploadSupport.VerifiedUrdf;
@@ -49,14 +50,15 @@ public class ComponentServiceImpl implements ComponentService {
} catch (DuplicateKeyException exception) {
throw new BizException(409, "COMPONENT_CODE_DUPLICATE", "组件编码已存在,请勿重复新增");
}
log.info("组件新增成功 componentId={} componentCode={} rotationAxis={} normalizedStorageFields={} userId={} requestId={}",
component.getId(), component.getComponentCode(), component.getRotationAxis(), normalizedStorageFields, userId, RequestIdHolder.get());
log.info("组件新增成功 componentId={} componentCode={} status={} rotationAxis={} normalizedStorageFields={} userId={} requestId={}",
component.getId(), component.getComponentCode(), component.getStatus(), component.getRotationAxis(), normalizedStorageFields, userId, RequestIdHolder.get());
return response;
}
@Override
public ComponentResponse updateComponent(Long userId, Long id, UpdateComponentRequest request) {
Component current = require(id);
ComponentStatus previousStatus = current.getStatus();
snapshot(current);
validateUpdate(current, request);
replaceResources(userId, current, request);
@@ -72,8 +74,8 @@ public class ComponentServiceImpl implements ComponentService {
snapshot(current);
return converter.toResponse(require(id));
});
log.info("组件修改成功 componentId={} componentCode={} version={} rotationAxis={} normalizedStorageFields={} userId={} requestId={}",
id, current.getComponentCode(), current.getVersion(), current.getRotationAxis(), normalizedStorageFields, userId, RequestIdHolder.get());
log.info("组件修改成功 componentId={} componentCode={} version={} previousStatus={} status={} rotationAxis={} normalizedStorageFields={} userId={} requestId={}",
id, current.getComponentCode(), current.getVersion(), previousStatus, current.getStatus(), current.getRotationAxis(), normalizedStorageFields, userId, RequestIdHolder.get());
return response;
}
@@ -104,7 +106,7 @@ public class ComponentServiceImpl implements ComponentService {
String normalizedCategory = text(category);
LambdaQueryWrapper<Component> query = new LambdaQueryWrapper<Component>()
.select(Component::getId, Component::getComponentCode, Component::getComponentName,
Component::getCategory, Component::getDescription, Component::getDegreesOfFreedom, Component::getRotationAxis,
Component::getCategory, Component::getStatus, Component::getDescription, Component::getDegreesOfFreedom, Component::getRotationAxis,
Component::getFunctionDescription, Component::getShape, Component::getSize,
Component::getTorqueNm, Component::getStepObjectKey, Component::getUrdfMainObjectKey,
Component::getVersion, Component::getCreatedAt, Component::getUpdatedAt)
@@ -1,9 +1,11 @@
package com.linkerbot.cadworld.service.matching;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.linkerbot.cadworld.common.api.RequestIdHolder;
import com.linkerbot.cadworld.common.exception.BizException;
import com.linkerbot.cadworld.dto.matching.PublicComponentResponse;
import com.linkerbot.cadworld.entity.Component;
import com.linkerbot.cadworld.enums.ComponentStatus;
import com.linkerbot.cadworld.mapper.ComponentMapper;
import com.linkerbot.cadworld.service.impl.ObjectStorageUrlResolver;
import com.linkerbot.cadworld.service.support.StorageObjectKeys;
@@ -15,10 +17,12 @@ import java.util.Map;
import java.util.function.Consumer;
import java.util.stream.Stream;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Slf4j
@RequiredArgsConstructor
public class PublicComponentQueryService {
private final ComponentMapper mapper;
@@ -38,6 +42,7 @@ public class PublicComponentQueryService {
long cursor = 0;
while (true) {
List<Component> page = mapper.selectList(candidateFields().in(Component::getCategory, aliases)
.eq(Component::getStatus, ComponentStatus.ENABLED)
.isNotNull(Component::getStepObjectKey).ne(Component::getStepObjectKey, "")
.isNotNull(Component::getUrdfMainObjectKey).ne(Component::getUrdfMainObjectKey, "")
.gt(Component::getId, cursor).orderByAsc(Component::getId).last("LIMIT 200"));
@@ -52,10 +57,13 @@ public class PublicComponentQueryService {
Map<String, PublicComponentResponse> load(Collection<String> codes) {
Map<String, PublicComponentResponse> result = new LinkedHashMap<>();
if (codes.isEmpty()) return result;
for (Component component : mapper.selectList(publicFields().in(Component::getComponentCode, codes))) {
for (Component component : mapper.selectList(publicFields().in(Component::getComponentCode, codes)
.eq(Component::getStatus, ComponentStatus.ENABLED))) {
result.put(component.getComponentCode(), toResponse(component));
}
if (result.size() != codes.size()) {
log.warn("拼装结果组件已变化 requestedCount={} availableCount={} requestId={}",
codes.size(), result.size(), RequestIdHolder.get());
throw new BizException(409, "COMPONENT_REVISION_CONFLICT", "组件已变化,请重新匹配");
}
return result;
@@ -35,7 +35,7 @@ class ComponentServiceImplTest {
new ObjectStorageUrlResolver(properties), new StorageObjectKeys(properties)),
mock(ComponentUploadSessionSupport.class),
mock(ComponentUploadSupport.class),new TransactionTemplate(manager));
UpdateComponentRequest request = new UpdateComponentRequest(null,"测试","分类",null,null,null,
UpdateComponentRequest request = new UpdateComponentRequest(null,"测试","分类",null,null,null,null,
null,null,null,null,null,null,null,new ObjectMapper().createObjectNode(),null,null,1L,null,null,null);
try {
assertThatThrownBy(() -> service.updateComponent(0L,1L,request))