Compare commits
31 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 93b922aea2 | |||
| 61db606c94 | |||
| 6e23b18f2a | |||
| e3207f1138 | |||
| a3434d12d5 | |||
| 7eef6e3994 | |||
| 5d94bc7871 | |||
| a9a6ad6028 | |||
| 0631bd5ecc | |||
| 2ddf750e5b | |||
| 99d05489c4 | |||
| c09dab33f7 | |||
| 3a0a3c388c | |||
| d7bad75558 | |||
| 54d4f3f981 | |||
| dca5a8799f | |||
| abf819eed6 | |||
| ef80cebb73 | |||
| 9754a5d818 | |||
| 06d2d87ec0 | |||
| 693f25acc5 | |||
| 8347ed5127 | |||
| d4db7fba69 | |||
| b2ff01e5e8 | |||
| 9e3bc846e8 | |||
| 13bdd2538d | |||
| 357a24869f | |||
| da3d956429 | |||
| 0d103c3285 | |||
| edd727ca9c | |||
| b591e87850 |
@@ -0,0 +1,26 @@
|
|||||||
|
# Shell environment only: copy to .env, fill the values, then source it as described in README.
|
||||||
|
SPRING_PROFILES_ACTIVE=test
|
||||||
|
SERVER_PORT=8992
|
||||||
|
APP_DB_URL='jdbc:mysql://39.105.93.138:3306/cadworld?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai'
|
||||||
|
APP_DB_USERNAME=
|
||||||
|
APP_DB_PASSWORD=
|
||||||
|
# Maximum bytes per OSS object, enforced in policy and when saving (default 100 MiB).
|
||||||
|
APP_STORAGE_MAX_UPLOAD_BYTES=104857600
|
||||||
|
OSS_ACCESS_KEY_ID=
|
||||||
|
OSS_ACCESS_KEY_SECRET=
|
||||||
|
OSS_REGION=oss-cn-beijing
|
||||||
|
OSS_BUCKET=linkerbot
|
||||||
|
# 默认 test: cadworld_dev,prod: cadworld;需要覆盖时取消注释。
|
||||||
|
# OSS_ROOT_PREFIX=cadworld_dev
|
||||||
|
APP_STORAGE_PUBLIC_BASE_URL=http://127.0.0.1:8992/admin-api/component-assets
|
||||||
|
# At least 32 UTF-8 bytes. Empty uses a random key and invalidates sessions on restart.
|
||||||
|
APP_UPLOAD_SESSION_SECRET=
|
||||||
|
# 管理端验证码与登录态有效期(单实例进程内缓存)
|
||||||
|
APP_ADMIN_AUTH_CAPTCHA_TTL=PT2M
|
||||||
|
APP_ADMIN_AUTH_TOKEN_TTL=PT24H
|
||||||
|
LOG_PATH=logs
|
||||||
|
|
||||||
|
# OSS 目录上传签名有效期(不超过会话剩余有效期)
|
||||||
|
OSS_UPLOAD_SIGNATURE_TTL=PT5M
|
||||||
|
# 上传会话有效期,续签不会延长此时间。
|
||||||
|
OSS_UPLOAD_SESSION_TTL=PT30M
|
||||||
+59
@@ -0,0 +1,59 @@
|
|||||||
|
# Maven 构建产物
|
||||||
|
target/
|
||||||
|
*.class
|
||||||
|
|
||||||
|
# IDE 本地配置
|
||||||
|
.idea/
|
||||||
|
*.iml
|
||||||
|
*.ipr
|
||||||
|
*.iws
|
||||||
|
.vscode/
|
||||||
|
.classpath
|
||||||
|
.project
|
||||||
|
.settings/
|
||||||
|
.factorypath
|
||||||
|
|
||||||
|
# 本地环境配置(保留配置示例和 test/prod 配置)
|
||||||
|
.env
|
||||||
|
.env.*
|
||||||
|
!.env.example
|
||||||
|
application-local.yml
|
||||||
|
application-local.yaml
|
||||||
|
application-local.properties
|
||||||
|
|
||||||
|
# Python 环境和缓存
|
||||||
|
.venv/
|
||||||
|
venv/
|
||||||
|
__pycache__/
|
||||||
|
*.py[cod]
|
||||||
|
.pytest_cache/
|
||||||
|
.mypy_cache/
|
||||||
|
.ruff_cache/
|
||||||
|
.coverage
|
||||||
|
.coverage.*
|
||||||
|
htmlcov/
|
||||||
|
|
||||||
|
# 运行日志、本地上传文件和 JVM 转储
|
||||||
|
**/logs/*
|
||||||
|
!**/logs/.gitkeep
|
||||||
|
*.log
|
||||||
|
*.log.*
|
||||||
|
/data/
|
||||||
|
/cadworld-*/data/
|
||||||
|
*.pid
|
||||||
|
*.hprof
|
||||||
|
hs_err_pid*
|
||||||
|
replay_pid*
|
||||||
|
|
||||||
|
# 操作系统文件和编辑器临时文件
|
||||||
|
.DS_Store
|
||||||
|
._*
|
||||||
|
Thumbs.db
|
||||||
|
Desktop.ini
|
||||||
|
*.swp
|
||||||
|
*.swo
|
||||||
|
*~
|
||||||
|
*.tmp
|
||||||
|
*.temp
|
||||||
|
# 用户需求图片保存在私有目录,禁止提交到仓库。
|
||||||
|
/data/demand-attachments/
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
## 代码实现原则
|
||||||
|
- 优先保证业务正确性、可维护性、可读性,再考虑炫技。
|
||||||
|
- Java代码统一使用显式类型声明,不使用var,包括局部变量、循环变量和try-with-resources资源变量。
|
||||||
|
- 修改代码时忽略.sql文件,如果遇到需要改表结构,直接发我sql,要求表字段规范且有中文注释。
|
||||||
|
- /api的用户请求返回数据不要暴露数据表id字段,只返回编码,增删改查都用唯一编码字段
|
||||||
|
## 日志规范
|
||||||
|
- 关键业务节点必须补充必要日志,方便线上排查。
|
||||||
|
- 不要打印密码、Token、手机号、身份证、支付密钥等敏感信息。
|
||||||
|
- 异常日志必须包含足够定位问题的信息。
|
||||||
|
## 回复规范
|
||||||
|
- 永远用中文回复。
|
||||||
@@ -1,2 +1,137 @@
|
|||||||
# cadworld
|
# cadworld
|
||||||
|
|
||||||
|
Java 21 / Spring Boot 3.4.4 / MyBatis-Plus 多模块项目。管理端提供组件库、用户管理和操作日志,默认端口 `8992`;用户端提供组件匹配与文字/图片需求解析,默认端口 `8991`。
|
||||||
|
|
||||||
|
## 项目模块
|
||||||
|
|
||||||
|
| 模块 | 内容 |
|
||||||
|
| --- | --- |
|
||||||
|
| cadworld-adminapi | 后台启动应用、Controller、Web 配置、运行日志和审计 |
|
||||||
|
| cadworld-service | 业务服务、Mapper、阿里云 OSS 签名、资源校验 |
|
||||||
|
| cadworld-bean | 实体、请求和响应 DTO、枚举 |
|
||||||
|
| cadworld-common | 统一响应、异常、JSON 类型处理、请求编号和操作目标上下文 |
|
||||||
|
| cadworld-api | 独立用户端 API:组件详情、匹配、需求会话、图文理解、自动选件与装配 |
|
||||||
|
| cadworld-security | 用户端及管理端 Spring Security、独立登录态、共用图片验证码与 Token 基础实现 |
|
||||||
|
|
||||||
|
用户端支持[邮箱与图片验证码登录](cadworld-api/docs/auth-api.md),首次自动注册,所有业务接口需要 Bearer Token。管理端支持[管理员邮箱登录](cadworld-adminapi/docs/auth-api.md),仅允许已启用的 ADMIN 账号,全部后台业务接口要求管理端 Bearer Token。上传会话和审计使用实际登录管理员。两端 Token 和验证码不能互用。
|
||||||
|
|
||||||
|
## 数据库
|
||||||
|
|
||||||
|
管理端访问 `component`、`sys_user`、`sys_operation_log`。用户端登录使用 `sys_user`,组件匹配复用 `component`,需求解析流程另外使用五张独立表;新增表的中文注释建表语句见 [需求流程建表说明](cadworld-api/docs/demand-schema.md),需要部署时手动执行,应用不自动建表。组件旋转轴字段 `rotation_axis` 的迁移 SQL 见 [管理端字段部署说明](cadworld-adminapi/docs/admin-api.md#43-旋转轴字段部署),部署两端新代码前须执行。
|
||||||
|
|
||||||
|
组件存储基本信息、自由度、旋转轴、功能、形状、大小描述、扭矩、BOM 清单、URDF 信息、两组自定义字段、STEP 对象键、URDF 目录及实际文件清单、`version`、`deleted` 删除标记和维护时间。旋转轴通过 `rotationAxis` 接收和返回,仅接受 `X`、`Y`、`Z`,未设置时为 null。BOM 和 URDF 信息均为 JSON 对象或数组,创建和修改必填 `urdfInfo`;可选 `bomList` 缺失或为 null 时写入 `[]`。列表返回旋转轴和描述字段,BOM 和 URDF 信息仅在详情及保存结果中返回。通用日志存储模块、动作、目标快照、操作人、请求元信息和结果,不依赖组件专属列。
|
||||||
|
|
||||||
|
用户登录改造发布前需手动执行[用户编码迁移 SQL](cadworld-api/docs/auth-api.md#4-发布前手动执行的迁移-sql)。应用启动不建表、不迁移旧数据。本次未修改 `.sql` 文件;仓库中历史 SQL 不代表当前组件和日志结构,请使用已经建好的表。MySQL 需支持现有建表语句中的 JSON / TEXT 表达式默认值。
|
||||||
|
|
||||||
|
组件名称允许重复,编码唯一且不可修改。新增编码为 `CW-` 加 16 位随机数字或大写字母(排除 `I/L/O/U`),总长 19,例如 `CW-7K3M9Q2R6V8X4T5N`;使用 80 位密码学安全随机空间,数据库唯一索引约束重复。旧版 35 字符编码和已有上传会话继续兼容,无需修改表结构或迁移已有编码。组件逻辑删除;用户删除入口改为禁用账号,可重新启用,邮箱仍被占用。已删除组件的编码仍被占用。组件替换资源或逻辑删除均不自动删除 OSS 文件。
|
||||||
|
|
||||||
|
现有 `component` 表包含 `deleted TINYINT UNSIGNED NOT NULL DEFAULT 0` 字段,中文注释为“删除标记:0-未删除,1-已删除”。运行代码通过 MyBatis-Plus 自动过滤已删除组件,列表、详情、修改和编辑上传签名均只处理未删除记录。
|
||||||
|
|
||||||
|
## 配置与启动
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cp .env.example .env
|
||||||
|
# 填写数据库、OSS 参数和上传会话密钥。
|
||||||
|
set -a
|
||||||
|
source .env
|
||||||
|
set +a
|
||||||
|
mvn -pl cadworld-adminapi -am -DskipTests package
|
||||||
|
java -jar cadworld-adminapi/target/cadworld-adminapi-0.0.1-SNAPSHOT.jar
|
||||||
|
```
|
||||||
|
|
||||||
|
Spring Boot 不自动读取 `.env`,需要通过 shell 导入。默认 profile 为 `test`;生产使用 `SPRING_PROFILES_ACTIVE=prod`,提供数据库连接变量。生产 Swagger 默认关闭。
|
||||||
|
|
||||||
|
Maven 命令在仓库根目录执行。首次构建或共享模块新增 DTO、方法后,使用 `mvn install` 将所有模块的最新产物安装到本地仓库。只构建管理端或用户端时,分别使用 `mvn -pl cadworld-adminapi -am install`、`mvn -pl cadworld-api -am install`,`-am` 会同时构建它们依赖的模块。
|
||||||
|
|
||||||
|
在子模块目录直接执行 `mvn install` 不会重建兄弟模块,可能引用本地旧包并出现程序包不存在或“找不到合适的方法”等错误。可用 `-f` 指定根 POM,从任意目录构建;将下方路径替换为实际仓库路径:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
mvn -f /path/to/cadworld/pom.xml -pl cadworld-api -am install
|
||||||
|
```
|
||||||
|
|
||||||
|
| 环境变量 | 用途 |
|
||||||
|
| --- | --- |
|
||||||
|
| APP_DB_URL / APP_DB_USERNAME / APP_DB_PASSWORD | MySQL 连接配置 |
|
||||||
|
| SERVER_PORT | 后台端口,默认 8992 |
|
||||||
|
| APP_ADMIN_ALLOWED_ORIGINS | 管理端 `/admin-api/**` 跨域白名单;`test` 默认 `https://dev-cadworld-admin.robotquan.com`,`prod` 默认 `https://cadworld-admin.robotquan.com`;可用逗号分隔的完整 origin 覆盖,显式留空关闭跨域,禁止通配符 |
|
||||||
|
| OSS_ACCESS_KEY_ID / OSS_ACCESS_KEY_SECRET | 阿里云 OSS 凭证,通过环境变量或被 Git 忽略的 `.env` 提供 |
|
||||||
|
| OSS_REGION / OSS_BUCKET | 默认 `oss-cn-beijing / linkerbot`,签名地域使用 `cn-beijing` |
|
||||||
|
| OSS_ROOT_PREFIX | 桶内环境根目录;`test` 默认 `cadworld_dev`,`prod` 默认 `cadworld` |
|
||||||
|
| APP_STORAGE_PUBLIC_BASE_URL | 返回资源访问地址所用的前缀,默认指向 `/admin-api/component-assets` |
|
||||||
|
| APP_STORAGE_MAX_UPLOAD_BYTES | 每个 OSS 文件的大小上限,默认 104857600 字节(100 MiB),签名策略与保存检查一致 |
|
||||||
|
| OSS_UPLOAD_SESSION_TTL | 上传会话有效期,默认 `PT30M`;续签不延长会话 |
|
||||||
|
| OSS_UPLOAD_SIGNATURE_TTL | OSS 签名有效期,默认 `PT5M`,不超过会话剩余时间 |
|
||||||
|
| APP_UPLOAD_SESSION_SECRET | 至少 32 个 UTF-8 字节;留空使用进程随机密钥,重启后原会话失效;多实例需配置相同密钥 |
|
||||||
|
| APP_ADMIN_AUTH_CAPTCHA_TTL / APP_ADMIN_AUTH_TOKEN_TTL | 管理端验证码与登录态有效期,默认 `PT2M / PT24H`;未设置时沿用通用 APP_AUTH_* 配置 |
|
||||||
|
| LOG_PATH | 运行日志目录,默认 `logs` |
|
||||||
|
|
||||||
|
运行时使用已有 OSS 桶,不自动创建桶。前端通过 OSS V4 表单签名直接上传,后端通过 HEAD 检查文件,资源下载仍由后台代理。OSS 需配置前端站点的 CORS,允许表单 POST;上传字段原样使用,`file` 放在表单最后。凭证需有目标目录上传和读取权限。
|
||||||
|
|
||||||
|
对象路径:
|
||||||
|
|
||||||
|
```text
|
||||||
|
{环境根目录}/components/{组件编码}/step/{上传批次}/{文件名}
|
||||||
|
{环境根目录}/components/{组件编码}/urdf/{上传批次}/{相对路径}
|
||||||
|
```
|
||||||
|
|
||||||
|
组件数据库中的文件键和目录前缀仅保存从 `components/` 开始的相对路径,不包含环境根目录或完整 URL;旧记录在再次成功保存时转换。上传授权、保存请求和详情响应仍使用带环境根目录的完整对象键,访问 URL 在响应时根据当前环境补全根目录并逐段编码。访问路径区分大小写;根目录不要填写 URL。跨环境上传、越界、非法路径会被拒绝。更改环境根目录不会移动 OSS 中的文件,新根目录须具备对应资源。
|
||||||
|
|
||||||
|
## 实例连接规则
|
||||||
|
|
||||||
|
先选定最符合需求的唯一躯干,再沿接口逐层选件。interfaceType 优先确定目标类型,缺失/无效时从 child 的 LINK_ 后解析现有类别;双方 frames[].child 严格一致才连接,name 不参与匹配。每个数组元素独立占用,同款组件可复用为多个实例;明确 quantity 优先,省略时填满所需类型的可匹配接口,单次最多24个实例。汇总和替代均按实例处理。
|
||||||
|
|
||||||
|
后端只返回实例及接口下标的连接关系,不再计算装配矩阵;原始 urdfInfo 保留,由前端决定摆放。组件类型统一使用[完整16类大写编码](cadworld-api/docs/api.md#36-角色映射),足部为 LEG_L/LEG_R/LEG_0;旧小写及 pedal_l/pedal_r 兼容输入。默认人形按实际接口选择 L/R/0,臂、手、足、脚各合计至少两个;六足需求使用 hexapod 模板,只要求躯干和 LEG/FOOT 各至少六个实例。接口仍为 0 接 0、L 接 L、R 接 R;其他未配置形态保留差异。历史结果通过新消息重新生成,无需数据库迁移。
|
||||||
|
|
||||||
|
## 上传与接口
|
||||||
|
|
||||||
|
上传只使用 `POST /admin-api/storage/upload-signature`。新增首次传 `{}`,获得后端编码、一个上传会话令牌和 STEP / URDF 两组授权;编辑传 `componentId`;续签传原 `uploadSessionToken`。申请签名不创建组件记录。
|
||||||
|
|
||||||
|
前端流程为:**获取编码和签名 → STEP 文件和 URDF 文件夹直传 OSS → POST / PUT 保存组件**。URDF 去掉选中文件夹最外层目录,保留内部结构。保存提交对象键,后端校验归属、实际存在性、大小及主文件后才写数据库。PUT 必须带详情中的 `version`,并发修改返回 409。
|
||||||
|
|
||||||
|
完整请求、响应及浏览器上传代码见 [后台接口文档](cadworld-adminapi/docs/admin-api.md)。
|
||||||
|
|
||||||
|
用户端接口入参、返回和公开模型加载见 [组件匹配文档](cadworld-api/docs/api.md);文字/图片理解、SSE 与自动生成装配方案见 [前端需求联调文档](cadworld-api/docs/robot-demand-api.md)。用户端部署变量、私有附件目录与接口连接约定见 [后端接入说明](cadworld-api/docs/demand-integration.md)。需求解析需配置后端 `ARK_API_KEY`;普通用户组件接口不需要管理员身份、上传令牌或 OSS 凭证。
|
||||||
|
|
||||||
|
AI 对话流程为:**文字/图片 → 理解需求 → 自动选件与装配校验 → 返回机器人方案**。发送消息后无需追问、确认或接受降级,`analysis.completed` 与状态查询直接返回 `match`。信息不足时使用默认双足模板或可辨认的部位,缺单位、冲突和不支持的要求作为未验证项保留;组件仍须有STEP和URDF主文件引用;安装基准、位姿和资源清单问题作为提示,不阻塞已有组合。SSE 意外断开后任务继续执行,可查询恢复。此次流程优化复用已有五张需求表,无需调整表结构。对话拼装已收敛为 7 个接口,旧确认、重新匹配、按匹配编码查询及接受降级接口已删除;结果统一由消息事件和任务查询返回,需要刷新时发送新消息。
|
||||||
|
|
||||||
|
| 路径 | 方法 |
|
||||||
|
| --- | --- |
|
||||||
|
| /admin-api/storage/upload-signature | POST,新增签名、编辑签名、续签 |
|
||||||
|
| /admin-api/components | GET 分页列表,POST 新增 |
|
||||||
|
| /admin-api/components/{id} | GET 详情,PUT 全量表单修改,DELETE 逻辑删除 |
|
||||||
|
| /admin-api/component-assets/{objectKey} | GET 下载资源 |
|
||||||
|
| /admin-api/users | GET 分页列表,POST 新增 |
|
||||||
|
| /admin-api/users/{id} | GET 详情,PUT 修改,DELETE 逻辑删除 |
|
||||||
|
| /admin-api/operation-logs | GET 分页列表,支持通用目标与模块筛选 |
|
||||||
|
| /admin-api/operation-logs/{id} | GET 详情 |
|
||||||
|
|
||||||
|
统一响应为 `{code, message, data, requestId}`,成功 `code=OK`。分页为 `{items, page, size, total}`,页码从 1 开始,默认每页 20,上限 100。下载成功直接返回文件流。
|
||||||
|
|
||||||
|
接口库、端口、姿态和 BREP 路由已移除,Python 工具不再需要。旧上传会话、上传确认、封面和后台文件流上传路由均返回 404。
|
||||||
|
|
||||||
|
## 日志
|
||||||
|
|
||||||
|
当前业务操作日志仅持久化组件 `CREATE / UPDATE / DELETE` 的成功和失败。资源校验及替换结果归入对应保存事件。日志表、审计基础设施和查询仍支持其他业务模块。
|
||||||
|
|
||||||
|
日志保留目标主键、编码和名称快照,删除后仍可追溯;写入使用独立事务,失败不改变业务结果。签名、续签、查询、下载和用户管理只输出运行日志。日志不保存请求体、表单值、令牌、签名或敏感信息,定位使用请求编号、路由模板和安全的异常信息。
|
||||||
|
|
||||||
|
运行日志配置集中在 `cadworld-common`,输出 `cadworld-adminapi.log` 与 `cadworld-adminapi-error.log`,按时间和大小归档。Mapper 日志保持 INFO,避免输出 SQL 参数。
|
||||||
|
|
||||||
|
测试环境 Swagger:`http://127.0.0.1:8992/swagger-ui.html`;OpenAPI:`/api-docs`。
|
||||||
|
|
||||||
|
## 验证
|
||||||
|
|
||||||
|
```bash
|
||||||
|
mvn -pl cadworld-api,cadworld-adminapi -am test
|
||||||
|
mvn -pl cadworld-api,cadworld-adminapi -am -DskipTests package
|
||||||
|
```
|
||||||
|
|
||||||
|
自动测试通过 Java 在 H2 创建临时表,使用内存 OSS,不连接业务 MySQL、不执行业务数据库 DDL。覆盖签名与续签、资源校验及替换、默认值、自定义字段、版本冲突、审计、逻辑删除及目标快照、旧路由 404 和用户管理回归,并校验 OSS V4 签名策略。
|
||||||
|
|
||||||
|
真实 OSS 的独立测试需显式配置凭证并启用 `oss-integration` profile:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
mvn -pl cadworld-adminapi -am -Poss-integration verify
|
||||||
|
```
|
||||||
|
|
||||||
|
该测试默认写入 `cadworld_dev/verification/{UUID}` 目录,完成后清理测试对象;可通过 `-Dcadworld.it.oss-root-prefix=测试根目录` 覆盖根目录,默认生产目录被禁止使用。清理失败时保留准确对象键记录,常规测试和打包不执行它。
|
||||||
|
|||||||
@@ -0,0 +1,557 @@
|
|||||||
|
# 后台 API 联调文档
|
||||||
|
|
||||||
|
后台保留组件库、用户管理、操作日志三个模块。以下路径以 `/admin-api` 为前缀,默认服务地址 `http://127.0.0.1:8992`。
|
||||||
|
|
||||||
|
用户端匹配与拼装接口由独立的 `cadworld-api` 服务提供,默认端口8991,详见[用户端 API 文档](../../cadworld-api/docs/api.md)。用户端默认组件、替代候选和详情同时返回 `bomList`、`urdfInfo`,通过编码访问组件,模型直接使用公开OSS/CDN地址。
|
||||||
|
|
||||||
|
## 1. 通用约定
|
||||||
|
|
||||||
|
JSON 请求设置 `Content-Type: application/json`。先完成[管理员邮箱与图片验证码登录](auth-api.md),业务接口统一携带 `Authorization: Bearer <token>`。仅允许已启用的 ADMIN 账号,不自动注册;上传会话及审计使用真实登录管理员。
|
||||||
|
|
||||||
|
`/admin-api/**` 跨域白名单按 profile 区分:`test` 允许 `https://dev-cadworld-admin.robotquan.com`,`prod` 允许 `https://cadworld-admin.robotquan.com`。可通过 `APP_ADMIN_ALLOWED_ORIGINS` 覆盖,多个完整 origin 用逗号分隔,禁止通配符;显式留空关闭跨域。允许 `GET / HEAD / POST / PUT / DELETE / OPTIONS`,请求头允许 `Content-Type / Authorization / X-Request-Id`,支持凭证,并向前端暴露 `X-Request-Id`;预检缓存 3600 秒。OSS 直传上传的 CORS 仍需在 OSS 单独配置。
|
||||||
|
|
||||||
|
成功返回 HTTP 200,包括新增和删除:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{"code":"OK","message":"success","data":{"success":true},"requestId":"请求编号"}
|
||||||
|
```
|
||||||
|
|
||||||
|
失败返回对应 HTTP 状态和错误码,`data` 可能省略:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{"code":"COMPONENT_REVISION_CONFLICT","message":"组件已修改或删除,请刷新后保存","requestId":"请求编号"}
|
||||||
|
```
|
||||||
|
|
||||||
|
分页返回 `data={"items":[],"page":1,"size":20,"total":0}`。页码从 1 开始,默认每页 20,超过 100 按 100 处理。组件和日志按更新时间/操作时间、ID 倒序。数据库时间及日志筛选时间使用上海时区本地时间,例如 `2026-10-10T16:00:00`;上传会话与签名到期时间为 UTC ISO 时间,例如 `2026-10-10T08:30:00Z`。
|
||||||
|
|
||||||
|
前端保存响应中的 `requestId` 用于排查问题。避免在浏览器日志中输出上传令牌和签名字段。
|
||||||
|
|
||||||
|
## 2. 接口列表
|
||||||
|
|
||||||
|
| 方法 | 路径 | 作用 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| GET | /admin-api/auth/captcha | 获取图片验证码,无需登录 |
|
||||||
|
| POST | /admin-api/auth/login | 管理员邮箱登录,无需登录 |
|
||||||
|
| POST | /admin-api/auth/logout | 退出当前管理端登录态 |
|
||||||
|
| GET | /admin-api/users/me | 当前管理员,不返回主键 |
|
||||||
|
| POST | /admin-api/storage/upload-signature | 分配编码及上传授权,或续签 |
|
||||||
|
| GET | /admin-api/components | 组件分页查询 |
|
||||||
|
| POST | /admin-api/components | 新增组件,校验上传文件后入库 |
|
||||||
|
| GET | /admin-api/components/{id} | 组件完整详情 |
|
||||||
|
| PUT | /admin-api/components/{id} | 全量更新表单,可替换资源 |
|
||||||
|
| DELETE | /admin-api/components/{id} | 逻辑删除组件 |
|
||||||
|
| GET | /admin-api/component-assets/{objectKey} | 下载资源文件 |
|
||||||
|
| GET | /admin-api/users | 用户分页查询 |
|
||||||
|
| POST | /admin-api/users | 创建用户 |
|
||||||
|
| GET | /admin-api/users/{id} | 用户详情 |
|
||||||
|
| PUT | /admin-api/users/{id} | 修改用户 |
|
||||||
|
| DELETE | /admin-api/users/{id} | 禁用用户,可重新启用 |
|
||||||
|
| GET | /admin-api/operation-logs | 通用操作日志分页查询 |
|
||||||
|
| GET | /admin-api/operation-logs/{id} | 操作日志详情 |
|
||||||
|
|
||||||
|
接口库、端口、姿态、BREP、封面、后台文件流上传以及所有旧上传会话/确认路由均已删除,访问返回 404。上传没有独立的创建会话、上传确认接口。
|
||||||
|
|
||||||
|
## 3. 单签名接口
|
||||||
|
|
||||||
|
### 3.1 请求
|
||||||
|
|
||||||
|
`POST /admin-api/storage/upload-signature`,以下三种请求互斥:
|
||||||
|
|
||||||
|
| 场景 | JSON 请求 |
|
||||||
|
| --- | --- |
|
||||||
|
| 新增组件首次上传 | `{}` |
|
||||||
|
| 已有组件替换模型 | `{"componentId":123}` |
|
||||||
|
| 原会话签名到期后续签 | `{"uploadSessionToken":"原令牌"}` |
|
||||||
|
|
||||||
|
新增无需组件编码。后端生成 `CW-` 加 16 位随机字符,总长 19,例如 `CW-7K3M9Q2R6V8X4T5N`。随机字符使用数字及大写字母,排除容易混淆的 `I/L/O/U`;使用密码学安全随机数生成,具有 80 位随机空间,保存时仍由 `component_code` 唯一索引约束。申请签名不创建组件记录。编辑使用原编码,生成新的上传批次;组件不存在返回 404。
|
||||||
|
|
||||||
|
旧版 `CW-` 加 32 位大写十六进制字符的组件编码和上传会话继续有效,包括升级前申请、尚未保存的上传会话。已有组件不重编码,资源目录保持原编码;前端必须直接使用接口返回的编码,不能假定固定为 35 字符。
|
||||||
|
|
||||||
|
续签不能同时提交 `componentId`。续签验证签名、有效期、操作人、环境及绑定组件,保持原编码、批次、令牌和目录。默认会话有效期 30 分钟、OSS 授权有效期 5 分钟;授权不超过会话到期时间,续签不延长会话。
|
||||||
|
|
||||||
|
### 3.2 响应
|
||||||
|
|
||||||
|
以下签名值仅为占位示例,实际表单字段必须使用后端返回值:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"code":"OK",
|
||||||
|
"message":"success",
|
||||||
|
"requestId":"请求编号",
|
||||||
|
"data":{
|
||||||
|
"componentCode":"CW-7K3M9Q2R6V8X4T5N",
|
||||||
|
"uploadSessionToken":"组件上传令牌",
|
||||||
|
"sessionExpiresAt":"2026-10-10T08:30:00Z",
|
||||||
|
"expiresAt":"2026-10-10T08:05:00Z",
|
||||||
|
"step":{
|
||||||
|
"uploadUrl":"https://linkerbot.oss-cn-beijing.aliyuncs.com/",
|
||||||
|
"keyPrefix":"cadworld_dev/components/CW-7K3M9Q2R6V8X4T5N/step/abcdef0123456789abcdef0123456789/",
|
||||||
|
"uploadMethod":"POST",
|
||||||
|
"uploadFields":{
|
||||||
|
"x-oss-signature-version":"OSS4-HMAC-SHA256",
|
||||||
|
"x-oss-credential":"访问凭证范围",
|
||||||
|
"x-oss-date":"20261010T080000Z",
|
||||||
|
"success_action_status":"204",
|
||||||
|
"x-oss-forbid-overwrite":"true",
|
||||||
|
"policy":"Base64策略",
|
||||||
|
"x-oss-signature":"签名"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"urdf":{
|
||||||
|
"uploadUrl":"https://linkerbot.oss-cn-beijing.aliyuncs.com/",
|
||||||
|
"keyPrefix":"cadworld_dev/components/CW-7K3M9Q2R6V8X4T5N/urdf/abcdef0123456789abcdef0123456789/",
|
||||||
|
"uploadMethod":"POST",
|
||||||
|
"uploadFields":{
|
||||||
|
"x-oss-signature-version":"OSS4-HMAC-SHA256",
|
||||||
|
"x-oss-credential":"访问凭证范围",
|
||||||
|
"x-oss-date":"20261010T080000Z",
|
||||||
|
"success_action_status":"204",
|
||||||
|
"x-oss-forbid-overwrite":"true",
|
||||||
|
"policy":"另一组Base64策略",
|
||||||
|
"x-oss-signature":"另一组签名"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
一个 `uploadSessionToken` 同时绑定 STEP 和 URDF 两组目录,两组使用相同编码、批次。不得修改、互换授权字段或手工构造目录。
|
||||||
|
|
||||||
|
### 3.3 OSS 直传
|
||||||
|
|
||||||
|
每个文件分别向对应 `uploadUrl` 发一个 `multipart/form-data` POST:原样加入 `uploadFields`,再加入 `key=keyPrefix+相对路径`,最后加入 `file`。让浏览器自动设置 Content-Type 和 boundary。OSS 成功返回 HTTP 204。
|
||||||
|
|
||||||
|
对象键包含环境根目录,默认测试为 `cadworld_dev`,生产为 `cadworld`:
|
||||||
|
|
||||||
|
```text
|
||||||
|
{环境根目录}/components/{组件编码}/step/{批次}/{STEP文件名}
|
||||||
|
{环境根目录}/components/{组件编码}/urdf/{批次}/{URDF内部相对路径}
|
||||||
|
```
|
||||||
|
|
||||||
|
STEP 直接使用文件名。URDF 使用文件夹选择器提供的 `webkitRelativePath`,去掉最外层选中目录,保留内部结构。例如 `L20/robot.urdf`、`L20/meshes/base.stl` 分别上传为 `urdf.keyPrefix + robot.urdf`、`urdf.keyPrefix + meshes/base.stl`。不要打包 ZIP,也不要扁平化内部目录。
|
||||||
|
|
||||||
|
默认单文件上限 100 MiB。禁止同名覆盖字段已纳入签名;同批次相同对象键重复上传会被 OSS 拒绝。续签只刷新授权,已确认上传成功的文件无需再次上传。会话过期需要重新申请签名并上传至新批次;新增重新申请会分配新编码。
|
||||||
|
|
||||||
|
OSS CORS 需允许前端源站的表单 POST。OSS 上传失败由前端按 OSS 返回状态处理;OSS 成功后仍须保存组件。
|
||||||
|
|
||||||
|
## 4. 组件表单及资源规则
|
||||||
|
|
||||||
|
### 4.1 表单字段
|
||||||
|
|
||||||
|
POST 和 PUT 使用扁平 JSON。新增业务字段仅 `stepObjectKey` 必填,仍须提交有效的 `uploadSessionToken`;全量修改保留名称、分类和 URDF 信息必填规则:
|
||||||
|
|
||||||
|
| 字段 | 类型 | 必填 / 默认值 / 限制 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 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,千克,非负 |
|
||||||
|
| degreesOfFreedom | integer | 默认 0,范围 0 至 2147483647,仅接受 JSON 整数,不接受小数或字符串 |
|
||||||
|
| rotationAxis | string / null | 可选,默认 null;仅接受大写 `X`、`Y`、`Z`,不接受空字符串、小写或数字 |
|
||||||
|
| functionDescription | string | 默认 `""`,最多 512 字符 |
|
||||||
|
| shape | string | 默认 `""`,最多 128 字符 |
|
||||||
|
| size | string | 默认 `""`,最多 128 字符,大小描述,可包含单位 |
|
||||||
|
| torqueNm | number | 默认 0,单位 N·m,非负 |
|
||||||
|
| bomList | JSON 对象或数组 | 默认 `[]`,内部结构自由 |
|
||||||
|
| urdfInfo | JSON 对象或数组 | POST 可选,默认 `[]`;PUT 必填;内部结构自由,允许 `{}` 或 `[]` |
|
||||||
|
| basicFields | 自定义字段数组 | 默认 `[]`,基本信息扩展字段 |
|
||||||
|
| parameterFields | 自定义字段数组 | 默认 `[]`,零件参数扩展字段 |
|
||||||
|
|
||||||
|
质量和扭矩最多 12 位整数、6 位小数,与 `DECIMAL(18,6)` 一致;不要在数值中提交单位文本。除 PUT 的 `status` 保留原值外,可选字段省略或传 null 会恢复默认值。名称、分类、材质、功能、形状和大小会裁剪首尾空白。
|
||||||
|
|
||||||
|
`bomList` 和 `urdfInfo` 直接提交 JSON 对象或数组,不接受字符串化的 JSON、数字或布尔值。`bomList` 省略或为 null 时保存为空数组;新增时 `urdfInfo` 省略或为 null 也保存为空数组,修改时仍须提供 JSON 对象或数组。两者内部字段不做固定结构校验,`urdfInfo` 由前端提供,不由后端解析 URDF 文件生成。
|
||||||
|
|
||||||
|
自定义字段格式:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"basicFields":[{"name":"供应商型号","value":"L20-RIGHT"}],
|
||||||
|
"parameterFields":[{"name":"额定电压","value":"24V"},{"name":"额定扭矩","value":"20 Nm"}]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
每组最多 100 项,名称非空且最多 64 字符,值为非 null 字符串、最多 2000 字符,可以为空字符串。同组名称裁剪后不可重复,两组之间可以重名;顺序与请求一致。
|
||||||
|
|
||||||
|
PUT 是全量表单更新,前端应提交完整表单,每次都必须提交 `urdfInfo`。除 `status` 外,省略可选字段会恢复默认值,提交空数组可清空 BOM 或自定义字段。
|
||||||
|
|
||||||
|
`status` 对应数据库 `status`,新增和存量组件默认 `ENABLED`。通过现有 PUT 编辑接口切换状态,仍须提交完整必填表单和最新 `version`,保存成功后版本递增。非法状态(包括小写、空字符串和数字)返回 422。禁用组件仍可在管理端列表、详情中查看和编辑,也可重新启用;禁用后不参与新生成的结构化匹配、AI 拼装或替代候选。用户端按编码查询详情、历史生成结果和已保存项目继续可查看。
|
||||||
|
|
||||||
|
`rotationAxis` 对应数据库 `rotation_axis`,下拉选项值使用 `X`、`Y`、`Z`;未设置时返回 null。PUT 省略该字段或传 null 会清空已有旋转轴。该字段是组件元数据,不替代 `urdfInfo` 中每个关节的 axis。
|
||||||
|
|
||||||
|
### 4.2 保存时的资源校验
|
||||||
|
|
||||||
|
新增必须提交 STEP,URDF 可选,`urdfObjectKeys` 省略、为 null 或空数组均表示未上传 URDF;此时 `urdfPrefix`、`urdfMainObjectKey` 保存为 `""`,`urdfFiles` 保存为 `[]`。修改可只替换一种,未提交的资源保持原引用。文件引用只能来自当前操作人、当前组件的有效令牌和对应目录。
|
||||||
|
|
||||||
|
后端检查全部对象键合法、无重复、无路径越界且实际存在,按 OSS HEAD 返回的实际大小校验,不接受前端提供的文件大小。STEP 是直接位于 STEP 批次目录的一个非空 `.step` 或 `.stp` 文件。提交非空 URDF 清单时,清单须为 1 至 1000 项,必须恰好包含一个非空 `.urdf` 主文件,不支持以 `.rfs` 为主文件;扩展名大小写均可。
|
||||||
|
|
||||||
|
后端根据实际对象生成 `urdfPrefix`、`urdfMainObjectKey` 和 `urdfFiles`,清单保留请求顺序,元素为 `relativePath` 和 `sizeBytes`。无需提交这些数据库维护字段。
|
||||||
|
|
||||||
|
数据库中的 `step_object_key`、`urdf_main_object_key`、`urdf_prefix` 仅保存从 `components/` 开始的相对路径,不包含 `app.storage.root-prefix` 环境根目录;目录前缀保留末尾 `/`。上传授权、保存请求和详情响应中的对象键仍包含环境根目录,访问 URL 根据当前环境配置生成,前端用法不变。兼容读取带当前环境根目录的旧记录,组件再次成功保存时统一转换这三个字段(仅修改业务信息也会转换),读取不会修改数据库,无需批量更新旧数据。
|
||||||
|
|
||||||
|
检查全部通过才写数据库。失败不切换原资源引用。旧批次、上传后未保存及删除组件后的文件暂不自动清理。校验覆盖清单的结构和对象存在性,不解析 URDF XML 内部的依赖引用。
|
||||||
|
|
||||||
|
### 4.3 旋转轴字段部署
|
||||||
|
|
||||||
|
部署管理端和用户端新代码前,在两端使用的组件数据库中执行以下 SQL。已有记录保持 null,应用不会自动执行迁移;仓库 `.sql` 文件不修改。
|
||||||
|
|
||||||
|
```sql
|
||||||
|
ALTER TABLE `component`
|
||||||
|
ADD COLUMN `rotation_axis` ENUM('X','Y','Z')
|
||||||
|
CHARACTER SET ascii COLLATE ascii_bin
|
||||||
|
NULL DEFAULT NULL
|
||||||
|
COMMENT '旋转轴:X、Y、Z;NULL表示未设置'
|
||||||
|
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 新增
|
||||||
|
|
||||||
|
`POST /admin-api/components`。编码由令牌读取,不接受前端指定编码。仅上传 STEP 后即可提交最小请求:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"uploadSessionToken":"签名接口返回的令牌",
|
||||||
|
"stepObjectKey":"cadworld_dev/components/CW-7K3M9Q2R6V8X4T5N/step/abcdef0123456789abcdef0123456789/model.step"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
其余业务字段按默认值保存;`bomList`、`urdfInfo` 虽为 NOT NULL,后端会显式写入空数组。部署前须完成上面的旋转轴和组件状态字段迁移。需要填写元数据或上传 URDF 时,可提交完整请求:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"componentName":"四孔安装板",
|
||||||
|
"category":"安装板",
|
||||||
|
"status":"ENABLED",
|
||||||
|
"description":"用于固定机械组件",
|
||||||
|
"material":"铝合金",
|
||||||
|
"massKg":0.35,
|
||||||
|
"degreesOfFreedom":0,
|
||||||
|
"rotationAxis":"Z",
|
||||||
|
"functionDescription":"固定机械组件",
|
||||||
|
"shape":"平板",
|
||||||
|
"size":"120 × 80 × 8 mm",
|
||||||
|
"torqueNm":0,
|
||||||
|
"bomList":[{"componentCode":"PART-001","name":"安装螺钉","quantity":4}],
|
||||||
|
"urdfInfo":{"robotName":"mounting_plate","links":[{"name":"base_link"}]},
|
||||||
|
"basicFields":[{"name":"供应商型号","value":"L20-RIGHT"}],
|
||||||
|
"parameterFields":[{"name":"额定电压","value":"24V"}],
|
||||||
|
"uploadSessionToken":"签名接口返回的令牌",
|
||||||
|
"stepObjectKey":"cadworld_dev/components/CW-7K3M9Q2R6V8X4T5N/step/abcdef0123456789abcdef0123456789/model.step",
|
||||||
|
"urdfObjectKeys":[
|
||||||
|
"cadworld_dev/components/CW-7K3M9Q2R6V8X4T5N/urdf/abcdef0123456789abcdef0123456789/robot.urdf",
|
||||||
|
"cadworld_dev/components/CW-7K3M9Q2R6V8X4T5N/urdf/abcdef0123456789abcdef0123456789/meshes/base.stl"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
成功返回完整组件详情,初始 `version=1`。重复使用已保存编码新增返回 409,包含已逻辑删除组件的编码。
|
||||||
|
|
||||||
|
### 5.2 详情及保存响应
|
||||||
|
|
||||||
|
`GET /admin-api/components/123`,POST / PUT 成功的 `data` 也使用此结构:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"id":123,
|
||||||
|
"componentCode":"CW-7K3M9Q2R6V8X4T5N",
|
||||||
|
"componentName":"四孔安装板",
|
||||||
|
"category":"安装板",
|
||||||
|
"status":"ENABLED",
|
||||||
|
"description":"用于固定机械组件",
|
||||||
|
"material":"铝合金",
|
||||||
|
"massKg":0.35,
|
||||||
|
"degreesOfFreedom":0,
|
||||||
|
"rotationAxis":"Z",
|
||||||
|
"functionDescription":"固定机械组件",
|
||||||
|
"shape":"平板",
|
||||||
|
"size":"120 × 80 × 8 mm",
|
||||||
|
"torqueNm":0,
|
||||||
|
"bomList":[{"componentCode":"PART-001","name":"安装螺钉","quantity":4}],
|
||||||
|
"urdfInfo":{"robotName":"mounting_plate","links":[{"name":"base_link"}]},
|
||||||
|
"basicFields":[{"name":"供应商型号","value":"L20-RIGHT"}],
|
||||||
|
"parameterFields":[{"name":"额定电压","value":"24V"}],
|
||||||
|
"stepObjectKey":"cadworld_dev/components/CW-7K3M9Q2R6V8X4T5N/step/abcdef0123456789abcdef0123456789/model.step",
|
||||||
|
"stepUrl":"http://127.0.0.1:8992/admin-api/component-assets/cadworld_dev/components/CW-7K3M9Q2R6V8X4T5N/step/abcdef0123456789abcdef0123456789/model.step",
|
||||||
|
"urdfPrefix":"cadworld_dev/components/CW-7K3M9Q2R6V8X4T5N/urdf/abcdef0123456789abcdef0123456789/",
|
||||||
|
"urdfBaseUrl":"http://127.0.0.1:8992/admin-api/component-assets/cadworld_dev/components/CW-7K3M9Q2R6V8X4T5N/urdf/abcdef0123456789abcdef0123456789/",
|
||||||
|
"urdfMainObjectKey":"cadworld_dev/components/CW-7K3M9Q2R6V8X4T5N/urdf/abcdef0123456789abcdef0123456789/robot.urdf",
|
||||||
|
"urdfUrl":"http://127.0.0.1:8992/admin-api/component-assets/cadworld_dev/components/CW-7K3M9Q2R6V8X4T5N/urdf/abcdef0123456789abcdef0123456789/robot.urdf",
|
||||||
|
"urdfFiles":[{"relativePath":"robot.urdf","sizeBytes":4200},{"relativePath":"meshes/base.stl","sizeBytes":15000}],
|
||||||
|
"version":1,
|
||||||
|
"createdAt":"2026-10-10T16:01:00.123",
|
||||||
|
"updatedAt":"2026-10-10T16:01:00.123"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
数据库只保存 Key。URL 在响应时生成,路径段经过编码。获取依赖文件时按 `/` 分段编码 `relativePath` 后拼接 `urdfBaseUrl`,不要对整个路径使用一次 `encodeURIComponent`。
|
||||||
|
|
||||||
|
### 5.3 修改
|
||||||
|
|
||||||
|
`PUT /admin-api/components/123`,必须提交最新 `version`,成功后递增。只改表单无需签名:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"version":1,
|
||||||
|
"componentName":"四孔安装板 V2",
|
||||||
|
"category":"安装板",
|
||||||
|
"status":"ENABLED",
|
||||||
|
"description":"更新说明",
|
||||||
|
"material":"铝合金",
|
||||||
|
"massKg":0.35,
|
||||||
|
"degreesOfFreedom":0,
|
||||||
|
"rotationAxis":"Z",
|
||||||
|
"functionDescription":"固定机械组件",
|
||||||
|
"shape":"平板",
|
||||||
|
"size":"120 × 80 × 8 mm",
|
||||||
|
"torqueNm":0,
|
||||||
|
"bomList":[],
|
||||||
|
"urdfInfo":{"robotName":"mounting_plate","links":[{"name":"base_link"}]},
|
||||||
|
"basicFields":[],
|
||||||
|
"parameterFields":[{"name":"额定电压","value":"24V"}]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`componentCode` 可省略;若提交必须与原编码一致。`version` 范围 1 至 4294967295,达到上限不能继续修改。版本过期或原子更新冲突返回 409,前端重新加载详情后合并修改再保存。
|
||||||
|
|
||||||
|
替换 STEP:先用 `{"componentId":123}` 申请新批次,直传 STEP,再在完整表单和 version 之外提交:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"uploadSessionToken":"编辑签名返回的令牌",
|
||||||
|
"stepObjectKey":"新授权的step.keyPrefix加文件名"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
替换 URDF 则提交令牌和完整的 `urdfObjectKeys`,不提交 `stepObjectKey`;同时替换则两者一起提交。不替换时省略令牌及文件字段。仅提交令牌、空对象键或空 URDF 清单会被拒绝。
|
||||||
|
|
||||||
|
### 5.4 列表
|
||||||
|
|
||||||
|
`GET /admin-api/components?page=1&size=20&keyword=安装板&category=安装板`
|
||||||
|
|
||||||
|
| 参数 | 说明 |
|
||||||
|
| --- | --- |
|
||||||
|
| page / size | 分页 |
|
||||||
|
| keyword | 名称或编码模糊查询 |
|
||||||
|
| category | 分类精确筛选 |
|
||||||
|
|
||||||
|
`items` 每项包含 `id`、`componentCode`、`componentName`、`category`、`status`、`description`、`degreesOfFreedom`、`rotationAxis`、`functionDescription`、`shape`、`size`、`torqueNm`、`stepUrl`、`urdfUrl`、`version`、`createdAt`、`updatedAt`。列表不查询或返回 `bomList`、`urdfInfo`、自定义表单和 URDF 文件清单。编辑先获取详情;创建和修改成功返回完整组件详情,包含状态和旋转轴。
|
||||||
|
|
||||||
|
列表查询参数 `size` 是每页条数,响应 `items` 内的 `size` 是组件大小描述。
|
||||||
|
|
||||||
|
### 5.5 删除和下载
|
||||||
|
|
||||||
|
`DELETE /admin-api/components/123` 成功返回 `data={"success":true}`。将组件的 `deleted` 标记从 `0` 改为 `1`,保留数据库记录、删除前的日志目标快照和 OSS 文件。找不到组件或组件已删除时返回 404。
|
||||||
|
|
||||||
|
已删除组件不出现在列表和详情中,不能修改、申请编辑上传签名或续签绑定该组件的上传会话。组件编码仍保持唯一,不能复用原新增会话重新创建同编码组件。删除标记仅用于数据库内部,不增加到接口响应中。
|
||||||
|
|
||||||
|
使用详情中的 `stepUrl`、`urdfUrl` 或依赖文件 URL 下载。若 URL 指向 `/admin-api/component-assets/**`,fetch 或模型加载器须携带管理端 Authorization 头,文件可转 Blob URL 展示或下载;Token 不放在 URL 中。若指向公开 OSS/CDN,则沿用公开资源加载方式。下载成功返回原文件流,不包 JSON;对象不存在返回 404。对象键区分大小写且必须属于当前环境根目录。
|
||||||
|
|
||||||
|
## 6. 浏览器完整上传示例
|
||||||
|
|
||||||
|
页面文件选择器:
|
||||||
|
|
||||||
|
```html
|
||||||
|
<input id="step" type="file" accept=".step,.stp">
|
||||||
|
<input id="urdf" type="file" webkitdirectory multiple>
|
||||||
|
```
|
||||||
|
|
||||||
|
以下示例使用一次签名完成两类文件上传,授权即将到期时调用同一接口续签,上传全部成功后直接保存。表单取当前页面值;示例按顺序上传以便展示流程,实际页面可使用受控并发。
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
// adminToken 为管理员登录返回的 Token,保存在应用登录状态中。
|
||||||
|
async function adminApi(path, method, body) {
|
||||||
|
const response = await fetch(`/admin-api${path}`, {
|
||||||
|
method,
|
||||||
|
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${adminToken}` },
|
||||||
|
...(body === undefined ? {} : { body: JSON.stringify(body) })
|
||||||
|
});
|
||||||
|
const result = await response.json();
|
||||||
|
if (!response.ok || result.code !== 'OK') {
|
||||||
|
throw new Error(`${result.message}; requestId=${result.requestId}`);
|
||||||
|
}
|
||||||
|
return result.data;
|
||||||
|
}
|
||||||
|
|
||||||
|
function urdfRelativePath(file) {
|
||||||
|
const path = file.webkitRelativePath;
|
||||||
|
if (!path || !path.includes('/')) throw new Error('请选择完整 URDF 文件夹');
|
||||||
|
return path.slice(path.indexOf('/') + 1); // 去掉选中文件夹的最外层目录
|
||||||
|
}
|
||||||
|
|
||||||
|
async function uploadAndSave(formValues, stepFile, urdfFiles, component = null) {
|
||||||
|
// 新增传 {};编辑传已有组件 ID。编辑可仅替换 STEP 或 URDF。
|
||||||
|
const files = Array.from(urdfFiles || []);
|
||||||
|
if (!component && !stepFile) {
|
||||||
|
throw new Error('新增组件必须选择 STEP 文件');
|
||||||
|
}
|
||||||
|
const body = { ...formValues };
|
||||||
|
if (component) body.version = component.version;
|
||||||
|
if (!stepFile && files.length === 0) {
|
||||||
|
return adminApi(`/components/${component.id}`, 'PUT', body);
|
||||||
|
}
|
||||||
|
let session = await adminApi('/storage/upload-signature', 'POST',
|
||||||
|
component ? { componentId: component.id } : {});
|
||||||
|
|
||||||
|
async function ensureSignature() {
|
||||||
|
if (Date.now() >= Date.parse(session.sessionExpiresAt)) {
|
||||||
|
throw new Error('上传会话已过期,请重新申请签名并重新上传');
|
||||||
|
}
|
||||||
|
if (Date.now() >= Date.parse(session.expiresAt) - 15000) {
|
||||||
|
session = await adminApi('/storage/upload-signature', 'POST', {
|
||||||
|
uploadSessionToken: session.uploadSessionToken
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function upload(kind, file, relativePath) {
|
||||||
|
await ensureSignature();
|
||||||
|
const authorization = session[kind];
|
||||||
|
const key = authorization.keyPrefix + relativePath;
|
||||||
|
const data = new FormData();
|
||||||
|
for (const [name, value] of Object.entries(authorization.uploadFields)) {
|
||||||
|
data.append(name, value);
|
||||||
|
}
|
||||||
|
data.append('key', key);
|
||||||
|
data.append('file', file); // 必须放最后;不要手工设置 Content-Type
|
||||||
|
const response = await fetch(authorization.uploadUrl, {
|
||||||
|
method: authorization.uploadMethod,
|
||||||
|
body: data
|
||||||
|
});
|
||||||
|
if (response.status !== 204) {
|
||||||
|
throw new Error(`OSS 上传失败,HTTP ${response.status}`);
|
||||||
|
}
|
||||||
|
return key;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (stepFile) body.stepObjectKey = await upload('step', stepFile, stepFile.name);
|
||||||
|
if (files.length) {
|
||||||
|
body.urdfObjectKeys = [];
|
||||||
|
for (const file of files) {
|
||||||
|
body.urdfObjectKeys.push(await upload('urdf', file, urdfRelativePath(file)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await ensureSignature(); // 保存前确认会话仍有效
|
||||||
|
body.uploadSessionToken = session.uploadSessionToken;
|
||||||
|
// 不需要 complete 接口;保存接口执行文件检查并写入记录。
|
||||||
|
return adminApi(component ? `/components/${component.id}` : '/components',
|
||||||
|
component ? 'PUT' : 'POST', body);
|
||||||
|
}
|
||||||
|
|
||||||
|
// formValues 只含完整表单字段,不包含详情里的资源 URL、Key 或维护字段。
|
||||||
|
const saved = await uploadAndSave({
|
||||||
|
componentName: '四孔安装板', category: '安装板',
|
||||||
|
description: '', material: '铝合金', massKg: 0, degreesOfFreedom: 0, rotationAxis: 'Z',
|
||||||
|
functionDescription: '固定机械组件', shape: '平板', size: '120 × 80 × 8 mm',
|
||||||
|
torqueNm: 0, bomList: [], urdfInfo: {}, basicFields: [], parameterFields: []
|
||||||
|
}, document.querySelector('#step').files[0], document.querySelector('#urdf').files);
|
||||||
|
// 编辑时第四个参数传 GET 详情返回的 component;未选择的资源保持原引用。
|
||||||
|
```
|
||||||
|
|
||||||
|
保存 409 时先刷新组件并处理版本冲突;保存失败不要把新 Key 当成已有资源展示。签名过期但会话有效可续签,会话过期则重新开始。对象同名覆盖被禁止,上传重试需跟踪已经确认成功的文件。
|
||||||
|
|
||||||
|
## 7. 用户管理
|
||||||
|
|
||||||
|
用户字段以邮箱版 `sys_user` 为准,发布前执行[用户编码迁移 SQL](../../cadworld-api/docs/auth-api.md#4-发布前手动执行的迁移-sql)。列表支持 `page`、`size`、`keyword`(邮箱或昵称)、`userType`(NORMAL / ADMIN)、`status`(ACTIVE / DISABLED)。详情返回 `id`、`userCode`、`email`、`nickname`、`status`、`userType`、`createdAt`、`updatedAt`;后台路径仍使用 `/{id}`,用户端只返回业务编码。
|
||||||
|
|
||||||
|
POST / PUT 请求:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{"email":"user@example.com","nickname":"测试用户","status":"ACTIVE","userType":"NORMAL"}
|
||||||
|
```
|
||||||
|
|
||||||
|
邮箱去除首尾空格并转小写后校验,最多 254 字符且唯一,重复返回 `409 / USER_EMAIL_DUPLICATE`。昵称必填且最多 64 字符。创建自动生成不可变 `userCode`,省略状态和类型时默认为 ACTIVE / NORMAL;修改省略则保留原值。
|
||||||
|
|
||||||
|
`DELETE /admin-api/users/{id}` 将状态设为 DISABLED,不删除记录。禁用用户仍能在列表和详情中查询,邮箱继续占用,可通过 PUT 将状态恢复为 ACTIVE。禁用后用户端登录返回 403,已有登录态的后续请求返回 401。用户管理只记录运行日志。
|
||||||
|
|
||||||
|
## 8. 通用操作日志
|
||||||
|
|
||||||
|
当前仅组件 CREATE / UPDATE / DELETE 的成功、失败写入 `sys_operation_log`。文件校验失败及资源替换属于对应保存操作。签名、续签、列表、详情、下载和用户管理不写业务审计。
|
||||||
|
|
||||||
|
审计保持通用:当前组件事件使用 `module=COMPONENT`、`targetType=COMPONENT`,未来模块可使用其他编码。查询不写死组件模块。目标 ID 为字符串,可兼容其他业务的字符串主键。
|
||||||
|
|
||||||
|
### 8.1 查询条件
|
||||||
|
|
||||||
|
`GET /admin-api/operation-logs`
|
||||||
|
|
||||||
|
| 参数 | 说明 |
|
||||||
|
| --- | --- |
|
||||||
|
| page / size | 分页 |
|
||||||
|
| module / action | 模块及动作精确筛选,支持其他业务编码 |
|
||||||
|
| success | true / false |
|
||||||
|
| operatorId | 操作人 ID |
|
||||||
|
| targetType / targetId / targetCode | 目标类型、主键、业务编码精确筛选 |
|
||||||
|
| keyword | 目标名称或编码模糊筛选 |
|
||||||
|
| from / to | 操作时间闭区间,ISO 本地时间,from 不可晚于 to |
|
||||||
|
|
||||||
|
例如:`/admin-api/operation-logs?module=COMPONENT&action=DELETE&success=true&targetId=123`。
|
||||||
|
|
||||||
|
### 8.2 列表元素及详情
|
||||||
|
|
||||||
|
`GET /admin-api/operation-logs/{id}` 返回相同日志结构:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"id":900,
|
||||||
|
"module":"COMPONENT",
|
||||||
|
"action":"DELETE",
|
||||||
|
"targetType":"COMPONENT",
|
||||||
|
"targetId":"123",
|
||||||
|
"targetCode":"CW-7K3M9Q2R6V8X4T5N",
|
||||||
|
"targetName":"四孔安装板",
|
||||||
|
"operatorId":0,
|
||||||
|
"operatorName":"TEST_OPERATOR",
|
||||||
|
"requestPath":"/admin-api/components/{id:[0-9]+}",
|
||||||
|
"requestMethod":"DELETE",
|
||||||
|
"clientIp":"127.0.0.1",
|
||||||
|
"requestId":"请求编号",
|
||||||
|
"operatedAt":"2026-10-10T16:05:00.123",
|
||||||
|
"durationMs":35,
|
||||||
|
"success":true,
|
||||||
|
"httpStatus":200,
|
||||||
|
"errorCode":"",
|
||||||
|
"errorSummary":""
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
删除保留操作前目标快照。失败事件记录已安全确认的目标标识,无法确定的字段为空字符串;新增失败可能尚无目标 ID。请求路径为路由模板,不保存查询参数。日志不保存请求体、表单自定义值、上传令牌或 OSS 签名。
|
||||||
|
|
||||||
|
审计写入独立事务,写日志失败不改变业务结果,运行日志记录安全定位信息和 requestId。
|
||||||
|
|
||||||
|
## 9. 常见错误
|
||||||
|
|
||||||
|
| HTTP | code | 处理 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 422 | INVALID_REQUEST | 必填、类型、长度、精度、版本参数等错误,修正请求 |
|
||||||
|
| 422 | INVALID_UPLOAD_SIGNATURE_REQUEST | 续签令牌为空或与 componentId 同时提交 |
|
||||||
|
| 422 | INVALID_COMPONENT_UPLOAD_SESSION | 令牌无效、过期、操作人/环境/组件不匹配 |
|
||||||
|
| 422 | INVALID_STORAGE_OBJECT_KEY | 非当前环境相对对象键,或非法/越界路径 |
|
||||||
|
| 422 | INVALID_COMPONENT_UPLOAD_OBJECT | 文件类型、清单、目录、主文件数量或实际大小信息无效 |
|
||||||
|
| 422 | COMPONENT_UPLOAD_OBJECT_MISSING | OSS 未检测到文件,确认直传完成及 Key 正确 |
|
||||||
|
| 422 | DUPLICATE_CUSTOM_FIELD | 同一组自定义字段名称重复 |
|
||||||
|
| 422 | INVALID_COMPONENT_FORM | 说明超出 TEXT 字段容量 |
|
||||||
|
| 422 | COMPONENT_CODE_IMMUTABLE | 修改请求试图改变编码 |
|
||||||
|
| 413 | UPLOAD_TOO_LARGE | 实际文件超过大小限制 |
|
||||||
|
| 409 | COMPONENT_REVISION_CONFLICT | 重新加载最新组件并处理冲突 |
|
||||||
|
| 409 | COMPONENT_CODE_DUPLICATE | 同一编码已保存,不要重复新增 |
|
||||||
|
| 404 | COMPONENT_NOT_FOUND | 组件不存在或已删除 |
|
||||||
|
| 404 | USER_NOT_FOUND / OPERATION_LOG_NOT_FOUND | 对应记录不存在 |
|
||||||
|
| 409 | USER_PHONE_DUPLICATE | 手机号已占用,包含逻辑删除用户 |
|
||||||
|
| 500 | OSS_UPLOAD_SIGN_FAILED | 根据 requestId 排查签名配置或 OSS 调用 |
|
||||||
|
|
||||||
|
OSS 直传错误直接来自 OSS,不使用后台统一响应。后台保存成功才表示组件及资源引用已生效。
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
# 管理端邮箱与图片验证码登录
|
||||||
|
|
||||||
|
服务默认端口 `8992`。仅允许 `sys_user` 中 `status=ACTIVE`、`user_type=ADMIN` 的账号登录;未知邮箱和普通用户返回 `403 / ADMIN_ACCESS_DENIED`,不自动创建账号或提升权限。流程不发送邮件、不验证邮箱归属,与用户端采用相同的图片验证码交互。
|
||||||
|
|
||||||
|
## 1. 接口与调用
|
||||||
|
|
||||||
|
| 方法 | 路径 | 说明 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| GET | `/admin-api/auth/captcha` | 无需登录,获取一次性图片验证码 |
|
||||||
|
| POST | `/admin-api/auth/login` | 无需登录,邮箱与图片验证码登录 |
|
||||||
|
| POST | `/admin-api/auth/logout` | 撤销当前管理员 Token |
|
||||||
|
| GET | `/admin-api/users/me` | 获取当前管理员,不返回数据库主键 |
|
||||||
|
|
||||||
|
除验证码、登录和 OPTIONS 预检外,所有 `/admin-api/**` 业务接口都要求 `Authorization: Bearer <token>`,包含组件、用户、操作日志、上传签名和代理资源下载。Swagger 文档可直接打开,在 Authorize 中填入登录返回的 Token 后调试业务接口。
|
||||||
|
|
||||||
|
验证码响应 `data`:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{"captchaCode":"一次性编码","image":"data:image/png;base64,...","expiresIn":120}
|
||||||
|
```
|
||||||
|
|
||||||
|
图片为 180×60 PNG,答案 5 位,不区分大小写,忽略首尾空格。默认有效期 2 分钟,每次通过参数校验的登录提交都会消费验证码,答错后也需重新获取。
|
||||||
|
|
||||||
|
登录请求:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{"email":"admin@example.com","captchaCode":"验证码编码","captchaAnswer":"ABCDE"}
|
||||||
|
```
|
||||||
|
|
||||||
|
邮箱去除首尾空格并转小写后校验,最多 254 字符。成功响应沿用 `{code,message,data,requestId}`,`data` 如下:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"token":"登录凭证",
|
||||||
|
"tokenType":"Bearer",
|
||||||
|
"expiresIn":86400,
|
||||||
|
"user":{"userCode":"0123456789ABCDEF0123456789ABCDEF","nickname":"管理员","email":"admin@example.com"}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`GET /admin-api/users/me` 返回同样的 `user` 字段内容。Token 默认有效期 24 小时,不滑动续期;同一管理员可同时保持多个登录态,退出仅撤销当前 Token。验证码和登录响应均设置 `Cache-Control: no-store`。
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
const challenge = (await (await fetch('/admin-api/auth/captcha')).json()).data;
|
||||||
|
// challenge.image 用于展示图片;answer 为管理员输入的答案。
|
||||||
|
const response = await fetch('/admin-api/auth/login', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ email, captchaCode: challenge.captchaCode, captchaAnswer: answer })
|
||||||
|
});
|
||||||
|
if (!response.ok) throw await response.json();
|
||||||
|
const { token } = (await response.json()).data;
|
||||||
|
|
||||||
|
const current = await fetch('/admin-api/users/me', {
|
||||||
|
headers: { Authorization: `Bearer ${token}` }
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
不要将 Token 放在 URL 中。代理图片、模型或下载文件也需通过带认证头的 fetch 或加载器读取。公开 OSS/CDN 地址按资源服务原有方式访问,OSS 直传表单仍使用签名字段,不向 OSS 发送管理端 Token。
|
||||||
|
|
||||||
|
## 2. 权限、上传与审计
|
||||||
|
|
||||||
|
- 每次请求从数据库检查状态和角色。禁用或删除用户后已有 Token 返回 `401 / UNAUTHORIZED`;管理员降级为普通用户后返回 `403 / ADMIN_ACCESS_DENIED`。
|
||||||
|
- 上传会话绑定当前登录管理员的内部用户主键;不同管理员不能续签或使用对方的上传会话。原配置操作人签发的上传会话需要重新申请。
|
||||||
|
- 组件操作的审计操作人来自当前管理员的主键和昵称;认证失败只记录运行日志,不伪造业务操作人。multipart 等早期业务失败仍记录真实管理员。
|
||||||
|
- 用户端和管理端共用验证码与 Token 基础代码,但拥有独立进程缓存和独立身份主体;两端 Token 和验证码不能互用。退出某一端不影响另一端。
|
||||||
|
|
||||||
|
| HTTP 状态 | code | 处理方式 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 400 | `CAPTCHA_INVALID` | 验证码错误、过期或已消费,重新获取 |
|
||||||
|
| 401 | `UNAUTHORIZED` | 未登录、Token 无效或用户已不可用,重新登录 |
|
||||||
|
| 403 | `ADMIN_ACCESS_DENIED` | 账号没有管理员权限 |
|
||||||
|
| 403 | `ACCOUNT_DISABLED` | 管理员账号已禁用 |
|
||||||
|
| 422 | `INVALID_REQUEST` | 邮箱、必填字段或长度不合法 |
|
||||||
|
| 503 | `DATABASE_UNAVAILABLE` | 数据库暂不可用,稍后重试 |
|
||||||
|
|
||||||
|
## 3. 配置和初始管理员
|
||||||
|
|
||||||
|
验证码和登录态分别使用最多 10000 条的进程内 Caffeine 缓存,按单实例部署;重启、容量淘汰或过期后凭证失效。缓存不影响数据库中的用户和业务数据。
|
||||||
|
|
||||||
|
| 配置 | 默认值与说明 |
|
||||||
|
| --- | --- |
|
||||||
|
| `APP_ADMIN_AUTH_CAPTCHA_TTL` | `PT2M`,至少 1 秒;未设置时沿用 `APP_AUTH_CAPTCHA_TTL` |
|
||||||
|
| `APP_ADMIN_AUTH_TOKEN_TTL` | `PT24H`,至少 1 秒;未设置时沿用 `APP_AUTH_TOKEN_TTL` |
|
||||||
|
| `APP_ADMIN_ALLOWED_ORIGINS` | 沿用管理端域名白名单,允许 Authorization 请求头;401/403 保留跨域响应头 |
|
||||||
|
|
||||||
|
`APP_ADMIN_OPERATOR_ID / APP_ADMIN_OPERATOR_NAME` 已不再使用。此改造无需新增表字段,沿用上次邮箱用户及 `user_code` 迁移后的表结构。
|
||||||
|
|
||||||
|
首次管理员由数据库预先授权。选择以下一种方式手动执行,替换为实际邮箱或已有用户编码,应用不会自动执行,也未修改 `.sql` 文件。
|
||||||
|
|
||||||
|
新建管理员:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
INSERT INTO `sys_user` (`user_code`, `email`, `nickname`, `status`, `user_type`)
|
||||||
|
VALUES (UPPER(REPLACE(UUID(), '-', '')), LOWER(TRIM('your-admin@example.com')),
|
||||||
|
'管理员', 'ACTIVE', 'ADMIN');
|
||||||
|
```
|
||||||
|
|
||||||
|
将已有用户授权为管理员:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
UPDATE `sys_user`
|
||||||
|
SET `user_type` = 'ADMIN', `status` = 'ACTIVE'
|
||||||
|
WHERE `user_code` = '替换为已有用户唯一编码';
|
||||||
|
```
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.linkerbot</groupId>
|
||||||
|
<artifactId>cadworld</artifactId>
|
||||||
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
<relativePath>../pom.xml</relativePath>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<artifactId>cadworld-adminapi</artifactId>
|
||||||
|
<packaging>jar</packaging>
|
||||||
|
<name>cadworld-adminapi</name>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.linkerbot</groupId>
|
||||||
|
<artifactId>cadworld-security-admin</artifactId>
|
||||||
|
<version>${project.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.linkerbot</groupId>
|
||||||
|
<artifactId>cadworld-service</artifactId>
|
||||||
|
<version>${project.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.mysql</groupId>
|
||||||
|
<artifactId>mysql-connector-j</artifactId>
|
||||||
|
<scope>runtime</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springdoc</groupId>
|
||||||
|
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.h2database</groupId>
|
||||||
|
<artifactId>h2</artifactId>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<resources>
|
||||||
|
<resource>
|
||||||
|
<directory>src/main/resources</directory>
|
||||||
|
</resource>
|
||||||
|
</resources>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
<profiles>
|
||||||
|
<profile>
|
||||||
|
<id>oss-integration</id>
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-failsafe-plugin</artifactId>
|
||||||
|
<configuration>
|
||||||
|
<includes>
|
||||||
|
<include>**/OssObjectStorageIT.java</include>
|
||||||
|
</includes>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
</profile>
|
||||||
|
</profiles>
|
||||||
|
</project>
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
package com.linkerbot.cadworld;
|
||||||
|
|
||||||
|
import org.mybatis.spring.annotation.MapperScan;
|
||||||
|
import org.springframework.boot.SpringApplication;
|
||||||
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
import org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration;
|
||||||
|
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
|
||||||
|
|
||||||
|
@SpringBootApplication(exclude = UserDetailsServiceAutoConfiguration.class)
|
||||||
|
@ConfigurationPropertiesScan("com.linkerbot.cadworld.config")
|
||||||
|
@MapperScan("com.linkerbot.cadworld.mapper")
|
||||||
|
public class AdminApiApplication {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
SpringApplication.run(AdminApiApplication.class, args);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
package com.linkerbot.cadworld.audit;
|
||||||
|
|
||||||
|
import java.lang.annotation.ElementType;
|
||||||
|
import java.lang.annotation.Retention;
|
||||||
|
import java.lang.annotation.RetentionPolicy;
|
||||||
|
import java.lang.annotation.Target;
|
||||||
|
|
||||||
|
@Target(ElementType.METHOD)
|
||||||
|
@Retention(RetentionPolicy.RUNTIME)
|
||||||
|
public @interface AuditOperation {
|
||||||
|
String module();
|
||||||
|
String action();
|
||||||
|
String targetType() default "";
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
package com.linkerbot.cadworld.audit;
|
||||||
|
|
||||||
|
import com.linkerbot.cadworld.common.api.ApiCode;
|
||||||
|
import com.linkerbot.cadworld.common.api.ApiResponse;
|
||||||
|
import org.springframework.core.MethodParameter;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.http.converter.HttpMessageConverter;
|
||||||
|
import org.springframework.http.server.ServerHttpRequest;
|
||||||
|
import org.springframework.http.server.ServerHttpResponse;
|
||||||
|
import org.springframework.http.server.ServletServerHttpRequest;
|
||||||
|
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||||
|
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
|
||||||
|
|
||||||
|
/** 只读取通用响应结果,目标快照由业务上下文提供,不读取表单或上传签名。 */
|
||||||
|
@RestControllerAdvice
|
||||||
|
public class AuditResponseAdvice implements ResponseBodyAdvice<Object> {
|
||||||
|
@Override
|
||||||
|
public boolean supports(MethodParameter parameter, Class<? extends HttpMessageConverter<?>> converter) { return true; }
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Object beforeBodyWrite(Object body, MethodParameter parameter, MediaType type,
|
||||||
|
Class<? extends HttpMessageConverter<?>> converter,
|
||||||
|
ServerHttpRequest request, ServerHttpResponse response) {
|
||||||
|
if (request instanceof ServletServerHttpRequest servlet && body instanceof ApiResponse<?> envelope
|
||||||
|
&& !ApiCode.OK.equals(envelope.getCode())
|
||||||
|
&& servlet.getServletRequest().getAttribute(OperationAuditInterceptor.CONTEXT)
|
||||||
|
instanceof OperationAuditInterceptor.Context context) {
|
||||||
|
context.event().setErrorCode(OperationAuditInterceptor.limit(envelope.getCode(), 64));
|
||||||
|
context.event().setErrorSummary(OperationAuditInterceptor.limit(envelope.getMessage(), 1000));
|
||||||
|
}
|
||||||
|
return body;
|
||||||
|
}
|
||||||
|
}
|
||||||
+87
@@ -0,0 +1,87 @@
|
|||||||
|
package com.linkerbot.cadworld.audit;
|
||||||
|
|
||||||
|
import com.linkerbot.cadworld.common.api.RequestIdHolder;
|
||||||
|
import jakarta.servlet.FilterChain;
|
||||||
|
import jakarta.servlet.ServletException;
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.Map;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.beans.factory.annotation.Qualifier;
|
||||||
|
import org.springframework.boot.autoconfigure.security.SecurityProperties;
|
||||||
|
import org.springframework.core.annotation.Order;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.web.filter.OncePerRequestFilter;
|
||||||
|
import org.springframework.web.servlet.mvc.condition.PathPatternsRequestCondition;
|
||||||
|
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
|
||||||
|
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
|
||||||
|
import org.springframework.web.method.HandlerMethod;
|
||||||
|
import org.springframework.web.servlet.HandlerMapping;
|
||||||
|
import org.springframework.web.util.ServletRequestPathUtils;
|
||||||
|
import org.springframework.web.util.pattern.PathPattern;
|
||||||
|
|
||||||
|
/** Multipart size failures can occur before an MVC interceptor is invoked. */
|
||||||
|
@Slf4j
|
||||||
|
@Component
|
||||||
|
@Order(SecurityProperties.DEFAULT_FILTER_ORDER + 1)
|
||||||
|
public class EarlyFailureAuditFilter extends OncePerRequestFilter {
|
||||||
|
private final RequestMappingHandlerMapping mappings;
|
||||||
|
private final OperationAuditInterceptor audit;
|
||||||
|
|
||||||
|
public EarlyFailureAuditFilter(@Qualifier("requestMappingHandlerMapping") RequestMappingHandlerMapping mappings,
|
||||||
|
OperationAuditInterceptor audit) {
|
||||||
|
this.mappings = mappings;
|
||||||
|
this.audit = audit;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
|
||||||
|
throws ServletException, IOException {
|
||||||
|
long started = System.nanoTime();
|
||||||
|
try {
|
||||||
|
chain.doFilter(request, response);
|
||||||
|
} finally {
|
||||||
|
if (response.getStatus() >= 400 && request.getAttribute(OperationAuditInterceptor.CONTEXT) == null
|
||||||
|
&& request.getRequestURI().startsWith(request.getContextPath() + "/admin-api/")) {
|
||||||
|
try {
|
||||||
|
// DispatcherServlet clears its parsed path before returning to filters.
|
||||||
|
HandlerMethod handler = resolveWriteHandler(request);
|
||||||
|
if (handler != null) {
|
||||||
|
audit.preHandle(request, response, handler);
|
||||||
|
if (request.getAttribute(OperationAuditInterceptor.CONTEXT) instanceof OperationAuditInterceptor.Context context) {
|
||||||
|
request.setAttribute(OperationAuditInterceptor.CONTEXT, new OperationAuditInterceptor.Context(context.event(), started));
|
||||||
|
audit.afterCompletion(request, response, handler, null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (Exception failure) {
|
||||||
|
log.error("早期审计失败 method={} requestId={} exceptionType={}",
|
||||||
|
request.getMethod(), RequestIdHolder.get(), failure.getClass().getSimpleName());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private HandlerMethod resolveWriteHandler(HttpServletRequest request) {
|
||||||
|
ServletRequestPathUtils.parseAndCache(request);
|
||||||
|
HandlerMethod best = null;
|
||||||
|
PathPattern bestPattern = null;
|
||||||
|
for (Map.Entry<RequestMappingInfo, HandlerMethod> entry : mappings.getHandlerMethods().entrySet()) {
|
||||||
|
if (!entry.getValue().hasMethodAnnotation(AuditOperation.class)
|
||||||
|
|| entry.getKey().getMethodsCondition().getMatchingCondition(request) == null) continue;
|
||||||
|
PathPatternsRequestCondition paths = entry.getKey().getPathPatternsCondition().getMatchingCondition(request);
|
||||||
|
if (paths == null) continue;
|
||||||
|
PathPattern pattern = paths.getFirstPattern();
|
||||||
|
if (bestPattern == null || pattern.compareTo(bestPattern) < 0) {
|
||||||
|
best = entry.getValue();
|
||||||
|
bestPattern = pattern;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (bestPattern != null) {
|
||||||
|
request.setAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE, bestPattern);
|
||||||
|
PathPattern.PathMatchInfo match = bestPattern.matchAndExtract(ServletRequestPathUtils.getParsedRequestPath(request).pathWithinApplication());
|
||||||
|
if (match != null) request.setAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, match.getUriVariables());
|
||||||
|
}
|
||||||
|
return best;
|
||||||
|
}
|
||||||
|
}
|
||||||
+91
@@ -0,0 +1,91 @@
|
|||||||
|
package com.linkerbot.cadworld.audit;
|
||||||
|
|
||||||
|
import com.linkerbot.cadworld.common.api.OperationTargetHolder;
|
||||||
|
import com.linkerbot.cadworld.common.api.RequestIdHolder;
|
||||||
|
import com.linkerbot.cadworld.entity.OperationLog;
|
||||||
|
import com.linkerbot.cadworld.service.AdminOperatorProvider;
|
||||||
|
import com.linkerbot.cadworld.service.OperationLogService;
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.time.ZoneId;
|
||||||
|
import java.util.Map;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.web.method.HandlerMethod;
|
||||||
|
import org.springframework.web.servlet.HandlerInterceptor;
|
||||||
|
import org.springframework.web.servlet.HandlerMapping;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
@Component
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class OperationAuditInterceptor implements HandlerInterceptor {
|
||||||
|
static final String CONTEXT = "cadworld.auditContext";
|
||||||
|
private final OperationLogService service;
|
||||||
|
private final AdminOperatorProvider operator;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
|
||||||
|
if (!(handler instanceof HandlerMethod method)) return true;
|
||||||
|
AuditOperation annotation = method.getMethodAnnotation(AuditOperation.class);
|
||||||
|
if (annotation == null) return true;
|
||||||
|
OperationTargetHolder.clear();
|
||||||
|
OperationLog event = new OperationLog();
|
||||||
|
event.setModule(annotation.module());
|
||||||
|
event.setAction(annotation.action());
|
||||||
|
event.setTargetType(annotation.targetType());
|
||||||
|
event.setOperatorId(operator.userId());
|
||||||
|
event.setOperatorName(limit(operator.name(), 128));
|
||||||
|
Object pattern = request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
|
||||||
|
event.setRequestPath(limit(pattern == null ? "<unmatched>" : pattern.toString(), 512));
|
||||||
|
event.setRequestMethod(limit(request.getMethod(), 16));
|
||||||
|
event.setClientIp(limit(request.getRemoteAddr(), 64));
|
||||||
|
event.setRequestId(limit(RequestIdHolder.get(), 64));
|
||||||
|
event.setOperatedAt(LocalDateTime.now(ZoneId.of("Asia/Shanghai")));
|
||||||
|
Object variables = request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
|
||||||
|
if (variables instanceof Map<?, ?> values && values.get("id") != null) {
|
||||||
|
event.setTargetId(limit(values.get("id").toString(), 128));
|
||||||
|
}
|
||||||
|
request.setAttribute(CONTEXT, new Context(event, System.nanoTime()));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) {
|
||||||
|
if (!(request.getAttribute(CONTEXT) instanceof Context context)) return;
|
||||||
|
try {
|
||||||
|
OperationLog event = context.event();
|
||||||
|
OperationTargetHolder.Target target = OperationTargetHolder.get();
|
||||||
|
if (target != null) {
|
||||||
|
event.setTargetType(limit(target.type(), 64));
|
||||||
|
event.setTargetId(limit(target.id(), 128));
|
||||||
|
event.setTargetCode(limit(target.code(), 128));
|
||||||
|
event.setTargetName(limit(target.name(), 256));
|
||||||
|
}
|
||||||
|
Object error = request.getAttribute("cadworld.operationError");
|
||||||
|
boolean success = response.getStatus() < 400 && exception == null && error == null && event.getErrorCode().isEmpty();
|
||||||
|
event.setSuccess(success);
|
||||||
|
event.setHttpStatus(response.getStatus());
|
||||||
|
event.setDurationMs((System.nanoTime() - context.started()) / 1_000_000);
|
||||||
|
if (!success && event.getErrorSummary().isEmpty()) {
|
||||||
|
event.setErrorCode(exception == null ? "HTTP_" + response.getStatus() : "INTERNAL_ERROR");
|
||||||
|
event.setErrorSummary("请求失败,请根据请求编号查询运行日志");
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
service.record(event);
|
||||||
|
} catch (Exception failure) {
|
||||||
|
// 数据库异常原文可能包含SQL参数,只记录定位字段和异常类型。
|
||||||
|
log.error("操作日志写入失败 requestId={} module={} action={} exceptionType={}",
|
||||||
|
event.getRequestId(), event.getModule(), event.getAction(), failure.getClass().getSimpleName());
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
OperationTargetHolder.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static String limit(String value, int length) {
|
||||||
|
return value == null ? "" : value.substring(0, Math.min(length, value.length()));
|
||||||
|
}
|
||||||
|
record Context(OperationLog event, long started) { }
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
package com.linkerbot.cadworld.config;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||||
|
|
||||||
|
@ConfigurationProperties(prefix = "app.admin.cors")
|
||||||
|
public record AdminCorsProperties(List<String> allowedOrigins) {
|
||||||
|
}
|
||||||
+18
@@ -0,0 +1,18 @@
|
|||||||
|
package com.linkerbot.cadworld.config;
|
||||||
|
|
||||||
|
import io.swagger.v3.oas.models.Components;
|
||||||
|
import io.swagger.v3.oas.models.OpenAPI;
|
||||||
|
import io.swagger.v3.oas.models.security.SecurityRequirement;
|
||||||
|
import io.swagger.v3.oas.models.security.SecurityScheme;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
|
||||||
|
@Configuration(proxyBeanMethods = false)
|
||||||
|
public class AdminOpenApiConfiguration {
|
||||||
|
@Bean
|
||||||
|
OpenAPI adminOpenApi() {
|
||||||
|
return new OpenAPI().components(new Components().addSecuritySchemes("adminBearer",
|
||||||
|
new SecurityScheme().type(SecurityScheme.Type.HTTP).scheme("bearer")))
|
||||||
|
.addSecurityItem(new SecurityRequirement().addList("adminBearer"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
package com.linkerbot.cadworld.config;
|
||||||
|
|
||||||
|
import com.linkerbot.cadworld.audit.OperationAuditInterceptor;
|
||||||
|
import java.util.List;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.web.servlet.config.annotation.CorsRegistry;
|
||||||
|
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
|
||||||
|
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
@Configuration
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class WebConfig implements WebMvcConfigurer {
|
||||||
|
private final OperationAuditInterceptor audit;
|
||||||
|
private final AdminCorsProperties cors;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void addCorsMappings(CorsRegistry registry) {
|
||||||
|
List<String> origins = cors.allowedOrigins();
|
||||||
|
if (origins == null || origins.isEmpty()) return;
|
||||||
|
String[] allowed = origins.stream().map(String::trim).filter((String origin) -> !origin.isBlank()).toArray(String[]::new);
|
||||||
|
if (allowed.length == 0) return;
|
||||||
|
for (String origin : allowed) {
|
||||||
|
if (origin.contains("*")) throw new IllegalArgumentException("管理接口凭证跨域必须配置具体前端域名");
|
||||||
|
}
|
||||||
|
registry.addMapping("/admin-api/**")
|
||||||
|
.allowedOrigins(allowed)
|
||||||
|
.allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
|
||||||
|
.allowedHeaders("Content-Type", "Authorization", "X-Request-Id")
|
||||||
|
.exposedHeaders("X-Request-Id")
|
||||||
|
.allowCredentials(true)
|
||||||
|
.maxAge(3600);
|
||||||
|
log.info("管理接口跨域配置已启用 path=/admin-api/** allowedOrigins={}", List.of(allowed));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(audit).addPathPatterns("/admin-api/**"); }
|
||||||
|
}
|
||||||
+81
@@ -0,0 +1,81 @@
|
|||||||
|
package com.linkerbot.cadworld.controller;
|
||||||
|
|
||||||
|
import com.linkerbot.cadworld.common.api.ApiResponse;
|
||||||
|
import com.linkerbot.cadworld.common.api.RequestIdHolder;
|
||||||
|
import com.linkerbot.cadworld.dto.auth.CaptchaResponse;
|
||||||
|
import com.linkerbot.cadworld.dto.auth.LoginRequest;
|
||||||
|
import com.linkerbot.cadworld.dto.auth.LoginResponse;
|
||||||
|
import com.linkerbot.cadworld.dto.auth.LoginUserResponse;
|
||||||
|
import com.linkerbot.cadworld.entity.SysUser;
|
||||||
|
import com.linkerbot.cadworld.logging.ApiRequestLog;
|
||||||
|
import com.linkerbot.cadworld.security.admin.CurrentAdmin;
|
||||||
|
import com.linkerbot.cadworld.security.common.AuthProperties;
|
||||||
|
import com.linkerbot.cadworld.security.common.CaptchaService;
|
||||||
|
import com.linkerbot.cadworld.security.common.TokenService;
|
||||||
|
import com.linkerbot.cadworld.service.auth.AdminLoginService;
|
||||||
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
|
import io.swagger.v3.oas.annotations.security.SecurityRequirements;
|
||||||
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
|
import jakarta.validation.Valid;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.http.HttpHeaders;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestBody;
|
||||||
|
import org.springframework.web.bind.annotation.RequestHeader;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
@RestController
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
@Tag(name = "管理员登录")
|
||||||
|
public class AdminAuthController {
|
||||||
|
private final CaptchaService captcha;
|
||||||
|
private final TokenService tokens;
|
||||||
|
private final AdminLoginService users;
|
||||||
|
private final AuthProperties properties;
|
||||||
|
|
||||||
|
@ApiRequestLog("获取管理员图片验证码")
|
||||||
|
@Operation(summary = "获取一次性图片验证码")
|
||||||
|
@SecurityRequirements
|
||||||
|
@GetMapping("/admin-api/auth/captcha")
|
||||||
|
public ApiResponse<CaptchaResponse> captcha(HttpServletResponse response) {
|
||||||
|
response.setHeader(HttpHeaders.CACHE_CONTROL, "no-store");
|
||||||
|
return ApiResponse.success(captcha.issue());
|
||||||
|
}
|
||||||
|
|
||||||
|
@ApiRequestLog("管理员邮箱登录")
|
||||||
|
@Operation(summary = "邮箱与图片验证码登录,仅允许已启用的管理员")
|
||||||
|
@SecurityRequirements
|
||||||
|
@PostMapping("/admin-api/auth/login")
|
||||||
|
public ApiResponse<LoginResponse> login(@Valid @RequestBody LoginRequest input, HttpServletResponse response) {
|
||||||
|
response.setHeader(HttpHeaders.CACHE_CONTROL, "no-store");
|
||||||
|
captcha.verify(input.captchaCode(), input.captchaAnswer());
|
||||||
|
SysUser user = users.login(input.email());
|
||||||
|
return ApiResponse.success(new LoginResponse(tokens.issue(user.getUserCode()), "Bearer",
|
||||||
|
properties.tokenTtl().toSeconds(), view(user)));
|
||||||
|
}
|
||||||
|
|
||||||
|
@ApiRequestLog("管理员退出登录")
|
||||||
|
@Operation(summary = "退出当前管理员登录态")
|
||||||
|
@PostMapping("/admin-api/auth/logout")
|
||||||
|
public ApiResponse<Void> logout(@RequestHeader(HttpHeaders.AUTHORIZATION) String authorization) {
|
||||||
|
String userCode = CurrentAdmin.required().userCode();
|
||||||
|
tokens.revoke(authorization.substring(7));
|
||||||
|
log.info("管理员退出登录 userCode={} requestId={}", userCode, RequestIdHolder.get());
|
||||||
|
return ApiResponse.success(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@ApiRequestLog("查询当前管理员")
|
||||||
|
@Operation(summary = "获取当前登录管理员")
|
||||||
|
@GetMapping("/admin-api/users/me")
|
||||||
|
public ApiResponse<LoginUserResponse> me() {
|
||||||
|
return ApiResponse.success(view(users.requireActive(CurrentAdmin.required().userCode())));
|
||||||
|
}
|
||||||
|
|
||||||
|
private LoginUserResponse view(SysUser user) {
|
||||||
|
return new LoginUserResponse(user.getUserCode(), user.getNickname(), user.getEmail());
|
||||||
|
}
|
||||||
|
}
|
||||||
+50
@@ -0,0 +1,50 @@
|
|||||||
|
package com.linkerbot.cadworld.controller;
|
||||||
|
|
||||||
|
import com.linkerbot.cadworld.logging.ApiRequestLog;
|
||||||
|
import com.linkerbot.cadworld.service.client.ObjectStorageClient;
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.http.HttpHeaders;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
import org.springframework.web.util.UriUtils;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/admin-api/component-assets")
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class ComponentAssetController {
|
||||||
|
private static final String ASSET_PATH_PREFIX = "/admin-api/component-assets/";
|
||||||
|
|
||||||
|
private final ObjectStorageClient objectStorageClient;
|
||||||
|
|
||||||
|
@ApiRequestLog("下载组件资源文件")
|
||||||
|
// 对象键至少包含环境根目录和文件名两段路径。
|
||||||
|
@GetMapping("/*/*/**")
|
||||||
|
public void download(HttpServletRequest request, HttpServletResponse response) throws IOException {
|
||||||
|
String requestUri = request.getRequestURI();
|
||||||
|
int prefixIndex = requestUri.indexOf(ASSET_PATH_PREFIX);
|
||||||
|
if (prefixIndex < 0) {
|
||||||
|
response.sendError(HttpStatus.NOT_FOUND.value());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
String encodedKey = requestUri.substring(prefixIndex + ASSET_PATH_PREFIX.length());
|
||||||
|
String objectKey = UriUtils.decode(encodedKey, StandardCharsets.UTF_8);
|
||||||
|
ObjectStorageClient.StoredObject object = objectStorageClient.statObject(objectKey);
|
||||||
|
|
||||||
|
response.setStatus(HttpStatus.OK.value());
|
||||||
|
response.setContentType(object.contentType() == null || object.contentType().isBlank()
|
||||||
|
? MediaType.APPLICATION_OCTET_STREAM_VALUE
|
||||||
|
: object.contentType());
|
||||||
|
if (object.contentLength() >= 0) {
|
||||||
|
response.setContentLengthLong(object.contentLength());
|
||||||
|
}
|
||||||
|
response.setHeader(HttpHeaders.CACHE_CONTROL, "private, max-age=3600");
|
||||||
|
objectStorageClient.writeObjectTo(objectKey, response.getOutputStream());
|
||||||
|
}
|
||||||
|
}
|
||||||
+63
@@ -0,0 +1,63 @@
|
|||||||
|
package com.linkerbot.cadworld.controller;
|
||||||
|
|
||||||
|
import com.linkerbot.cadworld.audit.AuditOperation;
|
||||||
|
import com.linkerbot.cadworld.common.api.ApiResponse;
|
||||||
|
import com.linkerbot.cadworld.common.api.PageResponse;
|
||||||
|
import com.linkerbot.cadworld.dto.common.SuccessResponse;
|
||||||
|
import com.linkerbot.cadworld.dto.component.*;
|
||||||
|
import com.linkerbot.cadworld.logging.ApiRequestLog;
|
||||||
|
import com.linkerbot.cadworld.service.AdminOperatorProvider;
|
||||||
|
import com.linkerbot.cadworld.service.ComponentService;
|
||||||
|
import jakarta.validation.Valid;
|
||||||
|
import jakarta.validation.constraints.Min;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.validation.annotation.Validated;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/admin-api/components")
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
@Validated
|
||||||
|
public class ComponentController {
|
||||||
|
private final AdminOperatorProvider operatorProvider;
|
||||||
|
private final ComponentService componentService;
|
||||||
|
|
||||||
|
@AuditOperation(module = "COMPONENT", action = "CREATE", targetType = "COMPONENT")
|
||||||
|
@ApiRequestLog("新增组件")
|
||||||
|
@PostMapping
|
||||||
|
public ApiResponse<ComponentResponse> create(@Valid @RequestBody CreateComponentRequest request) {
|
||||||
|
return ApiResponse.success(componentService.createComponent(operatorProvider.userId(), request));
|
||||||
|
}
|
||||||
|
|
||||||
|
@ApiRequestLog("查询组件列表")
|
||||||
|
@GetMapping
|
||||||
|
public ApiResponse<PageResponse<ComponentListItemResponse>> list(
|
||||||
|
@RequestParam(defaultValue = "1") @Min(1) long page,
|
||||||
|
@RequestParam(defaultValue = "20") @Min(1) long size,
|
||||||
|
@RequestParam(required = false) String keyword,
|
||||||
|
@RequestParam(required = false) String category) {
|
||||||
|
return ApiResponse.success(componentService.listComponents(page, Math.min(size, 100), keyword, category));
|
||||||
|
}
|
||||||
|
|
||||||
|
@ApiRequestLog("查询组件详情")
|
||||||
|
@GetMapping("/{id:[0-9]+}")
|
||||||
|
public ApiResponse<ComponentResponse> detail(@PathVariable @Min(1) Long id) {
|
||||||
|
return ApiResponse.success(componentService.getComponent(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
@AuditOperation(module = "COMPONENT", action = "UPDATE", targetType = "COMPONENT")
|
||||||
|
@ApiRequestLog("修改组件")
|
||||||
|
@PutMapping("/{id:[0-9]+}")
|
||||||
|
public ApiResponse<ComponentResponse> update(@PathVariable @Min(1) Long id,
|
||||||
|
@Valid @RequestBody UpdateComponentRequest request) {
|
||||||
|
return ApiResponse.success(componentService.updateComponent(operatorProvider.userId(), id, request));
|
||||||
|
}
|
||||||
|
|
||||||
|
@AuditOperation(module = "COMPONENT", action = "DELETE", targetType = "COMPONENT")
|
||||||
|
@ApiRequestLog("逻辑删除组件")
|
||||||
|
@DeleteMapping("/{id:[0-9]+}")
|
||||||
|
public ApiResponse<SuccessResponse> delete(@PathVariable @Min(1) Long id) {
|
||||||
|
componentService.deleteComponent(operatorProvider.userId(), id);
|
||||||
|
return ApiResponse.success(SuccessResponse.ok());
|
||||||
|
}
|
||||||
|
}
|
||||||
+44
@@ -0,0 +1,44 @@
|
|||||||
|
package com.linkerbot.cadworld.controller;
|
||||||
|
|
||||||
|
import com.linkerbot.cadworld.logging.ApiRequestLog;
|
||||||
|
|
||||||
|
import com.linkerbot.cadworld.common.api.ApiResponse;
|
||||||
|
import com.linkerbot.cadworld.common.api.PageResponse;
|
||||||
|
import com.linkerbot.cadworld.entity.OperationLog;
|
||||||
|
import com.linkerbot.cadworld.service.OperationLogService;
|
||||||
|
import jakarta.validation.constraints.Min;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.format.annotation.DateTimeFormat;
|
||||||
|
import org.springframework.validation.annotation.Validated;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/admin-api/operation-logs")
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
@Validated
|
||||||
|
public class OperationLogController {
|
||||||
|
private final OperationLogService service;
|
||||||
|
|
||||||
|
@ApiRequestLog("查询操作日志列表")
|
||||||
|
@GetMapping
|
||||||
|
public ApiResponse<PageResponse<OperationLog>> list(
|
||||||
|
@RequestParam(defaultValue = "1") @Min(1) long page,
|
||||||
|
@RequestParam(defaultValue = "20") @Min(1) long size,
|
||||||
|
@RequestParam(required = false) String module,
|
||||||
|
@RequestParam(required = false) String action,
|
||||||
|
@RequestParam(required = false) Boolean success,
|
||||||
|
@RequestParam(required = false) Long operatorId,
|
||||||
|
@RequestParam(required = false) String targetType,
|
||||||
|
@RequestParam(required = false) String targetId,
|
||||||
|
@RequestParam(required = false) String targetCode,
|
||||||
|
@RequestParam(required = false) String keyword,
|
||||||
|
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime from,
|
||||||
|
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime to) {
|
||||||
|
return ApiResponse.success(service.list(page, Math.min(size, 100), module, action, success, operatorId, targetType, targetId, targetCode, keyword, from, to));
|
||||||
|
}
|
||||||
|
|
||||||
|
@ApiRequestLog("查询操作日志详情")
|
||||||
|
@GetMapping("/{id}")
|
||||||
|
public ApiResponse<OperationLog> get(@PathVariable Long id) { return ApiResponse.success(service.get(id)); }
|
||||||
|
}
|
||||||
+25
@@ -0,0 +1,25 @@
|
|||||||
|
package com.linkerbot.cadworld.controller;
|
||||||
|
|
||||||
|
import com.linkerbot.cadworld.common.api.ApiResponse;
|
||||||
|
import com.linkerbot.cadworld.dto.storage.UploadSignatureRequest;
|
||||||
|
import com.linkerbot.cadworld.dto.storage.UploadSignatureResponse;
|
||||||
|
import com.linkerbot.cadworld.logging.ApiRequestLog;
|
||||||
|
import com.linkerbot.cadworld.service.AdminOperatorProvider;
|
||||||
|
import com.linkerbot.cadworld.service.UploadSignatureService;
|
||||||
|
import jakarta.validation.Valid;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/admin-api/storage")
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class StorageController {
|
||||||
|
private final UploadSignatureService signatures;
|
||||||
|
private final AdminOperatorProvider operatorProvider;
|
||||||
|
|
||||||
|
@ApiRequestLog("获取组件 OSS 上传签名")
|
||||||
|
@PostMapping("/upload-signature")
|
||||||
|
public ApiResponse<UploadSignatureResponse> sign(@Valid @RequestBody UploadSignatureRequest request) {
|
||||||
|
return ApiResponse.success(signatures.sign(operatorProvider.userId(), request));
|
||||||
|
}
|
||||||
|
}
|
||||||
+55
@@ -0,0 +1,55 @@
|
|||||||
|
package com.linkerbot.cadworld.controller;
|
||||||
|
|
||||||
|
import com.linkerbot.cadworld.logging.ApiRequestLog;
|
||||||
|
|
||||||
|
import com.linkerbot.cadworld.common.api.ApiResponse;
|
||||||
|
import com.linkerbot.cadworld.common.api.PageResponse;
|
||||||
|
import com.linkerbot.cadworld.dto.common.SuccessResponse;
|
||||||
|
import com.linkerbot.cadworld.dto.user.SaveUserRequest;
|
||||||
|
import com.linkerbot.cadworld.dto.user.UserResponse;
|
||||||
|
import com.linkerbot.cadworld.enums.UserStatus;
|
||||||
|
import com.linkerbot.cadworld.enums.UserType;
|
||||||
|
import com.linkerbot.cadworld.service.UserManagementService;
|
||||||
|
import jakarta.validation.Valid;
|
||||||
|
import jakarta.validation.constraints.Min;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.validation.annotation.Validated;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/admin-api/users")
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
@Validated
|
||||||
|
public class UserManagementController {
|
||||||
|
private final UserManagementService service;
|
||||||
|
|
||||||
|
@ApiRequestLog("查询用户列表")
|
||||||
|
@GetMapping
|
||||||
|
public ApiResponse<PageResponse<UserResponse>> list(
|
||||||
|
@RequestParam(defaultValue = "1") @Min(1) long page,
|
||||||
|
@RequestParam(defaultValue = "20") @Min(1) long size,
|
||||||
|
@RequestParam(required = false) String keyword,
|
||||||
|
@RequestParam(required = false) UserType userType,
|
||||||
|
@RequestParam(required = false) UserStatus status) {
|
||||||
|
return ApiResponse.success(service.list(page, Math.min(size, 100), keyword, userType, status));
|
||||||
|
}
|
||||||
|
|
||||||
|
@ApiRequestLog("查询用户详情")
|
||||||
|
@GetMapping("/{id}")
|
||||||
|
public ApiResponse<UserResponse> get(@PathVariable Long id) { return ApiResponse.success(service.get(id)); }
|
||||||
|
|
||||||
|
@ApiRequestLog("创建用户")
|
||||||
|
@PostMapping
|
||||||
|
public ApiResponse<UserResponse> create(@Valid @RequestBody SaveUserRequest request) { return ApiResponse.success(service.create(request)); }
|
||||||
|
|
||||||
|
@ApiRequestLog("修改用户")
|
||||||
|
@PutMapping("/{id}")
|
||||||
|
public ApiResponse<UserResponse> update(@PathVariable Long id, @Valid @RequestBody SaveUserRequest request) { return ApiResponse.success(service.update(id, request)); }
|
||||||
|
|
||||||
|
@ApiRequestLog("禁用用户")
|
||||||
|
@DeleteMapping("/{id}")
|
||||||
|
public ApiResponse<SuccessResponse> delete(@PathVariable Long id) {
|
||||||
|
service.delete(id);
|
||||||
|
return ApiResponse.success(SuccessResponse.ok());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
package com.linkerbot.cadworld.logging;
|
||||||
|
|
||||||
|
import java.lang.annotation.ElementType;
|
||||||
|
import java.lang.annotation.Retention;
|
||||||
|
import java.lang.annotation.RetentionPolicy;
|
||||||
|
import java.lang.annotation.Target;
|
||||||
|
|
||||||
|
/** 接口运行日志中的业务说明,不改变数据库操作日志的记录范围。 */
|
||||||
|
@Target(ElementType.METHOD)
|
||||||
|
@Retention(RetentionPolicy.RUNTIME)
|
||||||
|
public @interface ApiRequestLog {
|
||||||
|
String value();
|
||||||
|
}
|
||||||
+31
@@ -0,0 +1,31 @@
|
|||||||
|
package com.linkerbot.cadworld.logging;
|
||||||
|
|
||||||
|
import com.linkerbot.cadworld.common.api.ApiResponse;
|
||||||
|
import org.springframework.core.MethodParameter;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.http.converter.HttpMessageConverter;
|
||||||
|
import org.springframework.http.server.ServerHttpRequest;
|
||||||
|
import org.springframework.http.server.ServerHttpResponse;
|
||||||
|
import org.springframework.http.server.ServletServerHttpRequest;
|
||||||
|
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||||
|
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
|
||||||
|
|
||||||
|
/** 只提取业务错误码,不记录响应数据或可能包含敏感字段的错误提示。 */
|
||||||
|
@RestControllerAdvice
|
||||||
|
public class ApiRequestLogResponseAdvice implements ResponseBodyAdvice<Object> {
|
||||||
|
@Override
|
||||||
|
public boolean supports(MethodParameter parameter, Class<? extends HttpMessageConverter<?>> converter) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Object beforeBodyWrite(Object body, MethodParameter parameter, MediaType contentType,
|
||||||
|
Class<? extends HttpMessageConverter<?>> converter,
|
||||||
|
ServerHttpRequest request, ServerHttpResponse response) {
|
||||||
|
if (request instanceof ServletServerHttpRequest servlet && body instanceof ApiResponse<?> envelope) {
|
||||||
|
servlet.getServletRequest().setAttribute(ApiRequestLoggingFilter.RESULT_CODE_ATTRIBUTE,
|
||||||
|
envelope.getCode());
|
||||||
|
}
|
||||||
|
return body;
|
||||||
|
}
|
||||||
|
}
|
||||||
+124
@@ -0,0 +1,124 @@
|
|||||||
|
package com.linkerbot.cadworld.logging;
|
||||||
|
|
||||||
|
import com.linkerbot.cadworld.common.api.ApiCode;
|
||||||
|
import com.linkerbot.cadworld.common.api.RequestIdHolder;
|
||||||
|
import jakarta.servlet.FilterChain;
|
||||||
|
import jakarta.servlet.ServletException;
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.List;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.beans.factory.annotation.Qualifier;
|
||||||
|
import org.springframework.core.Ordered;
|
||||||
|
import org.springframework.core.annotation.Order;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.web.filter.OncePerRequestFilter;
|
||||||
|
import org.springframework.web.servlet.mvc.condition.PathPatternsRequestCondition;
|
||||||
|
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
|
||||||
|
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
|
||||||
|
import org.springframework.web.util.ServletRequestPathUtils;
|
||||||
|
import org.springframework.web.util.pattern.PathPattern;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 在 multipart 解析前记录接口开始,在响应完成后记录结果;不读取请求参数、文件或响应内容。
|
||||||
|
* 路径只输出路由模板,避免关键词、文件名等用户输入进入日志。
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@Component
|
||||||
|
@Order(Ordered.HIGHEST_PRECEDENCE + 2)
|
||||||
|
public class ApiRequestLoggingFilter extends OncePerRequestFilter {
|
||||||
|
static final String RESULT_CODE_ATTRIBUTE = "cadworld.runtimeLogResultCode";
|
||||||
|
|
||||||
|
private final List<Endpoint> endpoints;
|
||||||
|
|
||||||
|
public ApiRequestLoggingFilter(
|
||||||
|
@Qualifier("requestMappingHandlerMapping") RequestMappingHandlerMapping mappings) {
|
||||||
|
endpoints = mappings.getHandlerMethods().entrySet().stream()
|
||||||
|
.filter(entry -> entry.getValue().hasMethodAnnotation(ApiRequestLog.class))
|
||||||
|
.map(entry -> new Endpoint(entry.getKey(),
|
||||||
|
entry.getValue().getMethodAnnotation(ApiRequestLog.class).value()))
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected boolean shouldNotFilter(HttpServletRequest request) {
|
||||||
|
return !request.getRequestURI().startsWith(request.getContextPath() + "/admin-api/");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
|
||||||
|
throws ServletException, IOException {
|
||||||
|
MatchedEndpoint endpoint;
|
||||||
|
try {
|
||||||
|
endpoint = resolveEndpoint(request);
|
||||||
|
} catch (RuntimeException failure) {
|
||||||
|
// 日志定位失败不能改变原接口的处理结果,也不输出可能包含用户输入的异常消息。
|
||||||
|
log.warn("接口日志定位失败 method={} exceptionType={}",
|
||||||
|
request.getMethod(), failure.getClass().getSimpleName());
|
||||||
|
endpoint = null;
|
||||||
|
}
|
||||||
|
if (endpoint == null) {
|
||||||
|
chain.doFilter(request, response);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
long started = System.nanoTime();
|
||||||
|
String requestId = RequestIdHolder.get();
|
||||||
|
log.info("接口开始 description={} method={} path={} requestId={}",
|
||||||
|
endpoint.description(), request.getMethod(), endpoint.pattern().getPatternString(), requestId);
|
||||||
|
Throwable failure = null;
|
||||||
|
try {
|
||||||
|
chain.doFilter(request, response);
|
||||||
|
} catch (IOException | ServletException | RuntimeException | Error exception) {
|
||||||
|
failure = exception;
|
||||||
|
throw exception;
|
||||||
|
} finally {
|
||||||
|
long durationMs = (System.nanoTime() - started) / 1_000_000;
|
||||||
|
String code = (String) request.getAttribute(RESULT_CODE_ATTRIBUTE);
|
||||||
|
boolean success = failure == null && response.getStatus() < 400
|
||||||
|
&& (code == null || ApiCode.OK.equals(code));
|
||||||
|
String resultCode = code == null ? "HTTP_" + response.getStatus() : code;
|
||||||
|
String exceptionType = failure == null ? "-" : failure.getClass().getSimpleName();
|
||||||
|
String message = "接口结束 description={} method={} path={} requestId={} result={} httpStatus={} "
|
||||||
|
+ "code={} durationMs={} exceptionType={}";
|
||||||
|
Object[] values = {endpoint.description(), request.getMethod(), endpoint.pattern().getPatternString(),
|
||||||
|
requestId, success ? "SUCCESS" : "FAILURE", response.getStatus(), resultCode,
|
||||||
|
durationMs, exceptionType};
|
||||||
|
if (failure != null || response.getStatus() >= 500) {
|
||||||
|
log.error(message, values);
|
||||||
|
} else if (!success) {
|
||||||
|
log.warn(message, values);
|
||||||
|
} else {
|
||||||
|
log.info(message, values);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private MatchedEndpoint resolveEndpoint(HttpServletRequest request) {
|
||||||
|
if (!ServletRequestPathUtils.hasParsedRequestPath(request)) {
|
||||||
|
ServletRequestPathUtils.parseAndCache(request);
|
||||||
|
}
|
||||||
|
MatchedEndpoint best = null;
|
||||||
|
for (Endpoint endpoint : endpoints) {
|
||||||
|
// 只匹配路径及 HTTP 方法,避免提前解析 multipart 或访问请求参数。
|
||||||
|
// 即使 Content-Type 不合法,也能记录对应接口的最终失败结果。
|
||||||
|
if (endpoint.mapping().getMethodsCondition().getMatchingCondition(request) == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
PathPatternsRequestCondition matchingPaths = endpoint.mapping().getPathPatternsCondition().getMatchingCondition(request);
|
||||||
|
if (matchingPaths == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
PathPattern pattern = matchingPaths.getFirstPattern();
|
||||||
|
if (best == null || pattern.compareTo(best.pattern()) < 0) {
|
||||||
|
best = new MatchedEndpoint(endpoint.description(), pattern);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return best;
|
||||||
|
}
|
||||||
|
|
||||||
|
private record Endpoint(RequestMappingInfo mapping, String description) { }
|
||||||
|
|
||||||
|
private record MatchedEndpoint(String description, PathPattern pattern) { }
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
spring:
|
||||||
|
datasource:
|
||||||
|
url: ${APP_DB_URL}
|
||||||
|
username: ${APP_DB_USERNAME}
|
||||||
|
password: ${APP_DB_PASSWORD}
|
||||||
|
driver-class-name: com.mysql.cj.jdbc.Driver
|
||||||
|
hikari:
|
||||||
|
maximum-pool-size: 20
|
||||||
|
|
||||||
|
app:
|
||||||
|
admin:
|
||||||
|
cors:
|
||||||
|
allowed-origins: ${APP_ADMIN_ALLOWED_ORIGINS:https://cadworld-admin.robotquan.com}
|
||||||
|
storage:
|
||||||
|
root-prefix: ${OSS_ROOT_PREFIX:cadworld}
|
||||||
|
|
||||||
|
springdoc:
|
||||||
|
api-docs:
|
||||||
|
enabled: false
|
||||||
|
swagger-ui:
|
||||||
|
enabled: false
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
spring:
|
||||||
|
datasource:
|
||||||
|
url: ${APP_DB_URL:jdbc:mysql://39.105.93.138:3306/cadworld?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai}
|
||||||
|
username: ${APP_DB_USERNAME:root}
|
||||||
|
password: ${APP_DB_PASSWORD:mysql_QRWm4M}
|
||||||
|
driver-class-name: com.mysql.cj.jdbc.Driver
|
||||||
|
hikari:
|
||||||
|
pool-name: CadworldAdminHikariCP
|
||||||
|
minimum-idle: 1
|
||||||
|
maximum-pool-size: 10
|
||||||
|
connection-timeout: 5000
|
||||||
|
|
||||||
|
app:
|
||||||
|
admin:
|
||||||
|
cors:
|
||||||
|
# Origin 必须包含协议;可用逗号分隔的完整来源覆盖。
|
||||||
|
allowed-origins: ${APP_ADMIN_ALLOWED_ORIGINS:https://dev-cadworld-admin.robotquan.com}
|
||||||
|
storage:
|
||||||
|
root-prefix: ${OSS_ROOT_PREFIX:cadworld_dev}
|
||||||
|
|
||||||
|
springdoc:
|
||||||
|
api-docs:
|
||||||
|
enabled: true
|
||||||
|
swagger-ui:
|
||||||
|
enabled: true
|
||||||
|
|
||||||
|
logging:
|
||||||
|
level:
|
||||||
|
com.linkerbot.cadworld: DEBUG
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
spring:
|
||||||
|
application:
|
||||||
|
name: cadworld-adminapi
|
||||||
|
profiles:
|
||||||
|
default: test
|
||||||
|
sql:
|
||||||
|
init:
|
||||||
|
mode: never
|
||||||
|
servlet:
|
||||||
|
multipart:
|
||||||
|
max-file-size: 100MB
|
||||||
|
max-request-size: 100MB
|
||||||
|
jackson:
|
||||||
|
default-property-inclusion: non_null
|
||||||
|
time-zone: Asia/Shanghai
|
||||||
|
lifecycle:
|
||||||
|
timeout-per-shutdown-phase: 30s
|
||||||
|
|
||||||
|
server:
|
||||||
|
port: ${SERVER_PORT:8992}
|
||||||
|
shutdown: graceful
|
||||||
|
compression:
|
||||||
|
enabled: true
|
||||||
|
min-response-size: 2KB
|
||||||
|
|
||||||
|
mybatis-plus:
|
||||||
|
configuration:
|
||||||
|
map-underscore-to-camel-case: true
|
||||||
|
|
||||||
|
springdoc:
|
||||||
|
api-docs:
|
||||||
|
path: /api-docs
|
||||||
|
swagger-ui:
|
||||||
|
path: /swagger-ui.html
|
||||||
|
|
||||||
|
app:
|
||||||
|
auth:
|
||||||
|
captcha-ttl: ${APP_ADMIN_AUTH_CAPTCHA_TTL:${APP_AUTH_CAPTCHA_TTL:PT2M}}
|
||||||
|
token-ttl: ${APP_ADMIN_AUTH_TOKEN_TTL:${APP_AUTH_TOKEN_TTL:PT24H}}
|
||||||
|
admin:
|
||||||
|
cors:
|
||||||
|
allowed-origins: ${APP_ADMIN_ALLOWED_ORIGINS:}
|
||||||
|
upload-session:
|
||||||
|
issuer: cadworld-upload
|
||||||
|
# Empty means a random, process-local signing key. Set a stable key for restarts/multiple instances.
|
||||||
|
secret: ${APP_UPLOAD_SESSION_SECRET:}
|
||||||
|
storage:
|
||||||
|
root-prefix: ${OSS_ROOT_PREFIX:cadworld}
|
||||||
|
public-base-url: ${APP_STORAGE_PUBLIC_BASE_URL:http://127.0.0.1:${SERVER_PORT:8992}/admin-api/component-assets}
|
||||||
|
upload-session-ttl: ${OSS_UPLOAD_SESSION_TTL:PT30M}
|
||||||
|
upload-signature-ttl: ${OSS_UPLOAD_SIGNATURE_TTL:PT5M}
|
||||||
|
max-upload-bytes: ${APP_STORAGE_MAX_UPLOAD_BYTES:104857600}
|
||||||
|
oss:
|
||||||
|
access-key-id: ${OSS_ACCESS_KEY_ID:}
|
||||||
|
access-key-secret: ${OSS_ACCESS_KEY_SECRET:}
|
||||||
|
region: ${OSS_REGION:oss-cn-beijing}
|
||||||
|
bucket: ${OSS_BUCKET:linkerbot}
|
||||||
|
|
||||||
|
logging:
|
||||||
|
file:
|
||||||
|
path: ${LOG_PATH:logs}
|
||||||
|
level:
|
||||||
|
root: INFO
|
||||||
|
com.linkerbot.cadworld: INFO
|
||||||
|
# 即使测试环境开启项目 DEBUG,也不输出可能包含手机号、模型数据等信息的 SQL 参数。
|
||||||
|
com.linkerbot.cadworld.mapper: INFO
|
||||||
|
org.springframework.web: INFO
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,246 @@
|
|||||||
|
package com.linkerbot.cadworld;
|
||||||
|
|
||||||
|
import ch.qos.logback.classic.Logger;
|
||||||
|
import ch.qos.logback.classic.spi.ILoggingEvent;
|
||||||
|
import ch.qos.logback.core.read.ListAppender;
|
||||||
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import com.linkerbot.cadworld.security.common.AuthProperties;
|
||||||
|
import com.linkerbot.cadworld.security.common.CaptchaService;
|
||||||
|
import com.linkerbot.cadworld.security.common.TokenService;
|
||||||
|
import com.linkerbot.cadworld.service.auth.AdminLoginService;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.boot.test.context.TestConfiguration;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Import;
|
||||||
|
import org.springframework.context.annotation.Primary;
|
||||||
|
import org.springframework.dao.DataAccessResourceFailureException;
|
||||||
|
import org.springframework.http.HttpHeaders;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.jdbc.core.JdbcTemplate;
|
||||||
|
import org.springframework.test.context.ActiveProfiles;
|
||||||
|
import org.springframework.test.context.bean.override.mockito.MockitoSpyBean;
|
||||||
|
import org.springframework.test.web.servlet.MockMvc;
|
||||||
|
import org.springframework.test.web.servlet.MvcResult;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.mockito.Mockito.doThrow;
|
||||||
|
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
|
||||||
|
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||||
|
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.options;
|
||||||
|
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||||
|
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
|
||||||
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
|
||||||
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||||
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||||
|
|
||||||
|
@SpringBootTest(classes = AdminApiApplication.class, properties = {
|
||||||
|
"spring.datasource.url=jdbc:h2:mem:admin-auth;MODE=MySQL;DB_CLOSE_DELAY=-1",
|
||||||
|
"spring.datasource.driver-class-name=org.h2.Driver", "spring.datasource.username=sa", "spring.datasource.password=",
|
||||||
|
"app.storage.root-prefix=cadworld_dev", "logging.file.path=target/test-logs",
|
||||||
|
"logging.level.com.linkerbot.cadworld=DEBUG", "app.admin.cors.allowed-origins=http://localhost:5173"
|
||||||
|
})
|
||||||
|
@ActiveProfiles("verification")
|
||||||
|
@AutoConfigureMockMvc(print = org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrint.NONE)
|
||||||
|
@Import({InMemoryObjectStorageConfiguration.class, AdminAuthApiTest.CaptchaConfiguration.class})
|
||||||
|
class AdminAuthApiTest {
|
||||||
|
private static final String ORIGIN = "http://localhost:5173";
|
||||||
|
@Autowired private MockMvc mvc;
|
||||||
|
@Autowired private JdbcTemplate jdbc;
|
||||||
|
@Autowired private ObjectMapper json;
|
||||||
|
@Autowired private TokenService tokens;
|
||||||
|
@Autowired private AuthProperties properties;
|
||||||
|
@MockitoSpyBean private AdminLoginService users;
|
||||||
|
private AdminAuthTestSupport.Session admin;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void prepare() {
|
||||||
|
for (String table : List.of("component", "sys_user", "sys_operation_log")) jdbc.update("DELETE FROM " + table);
|
||||||
|
admin = AdminAuthTestSupport.create(jdbc, tokens);
|
||||||
|
jdbc.update("UPDATE sys_user SET email=? WHERE user_code=?", "admin@example.test", admin.userCode());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void adminLoginNormalizesEmailAndReturnsCurrentUserWithoutId() throws Exception {
|
||||||
|
JsonNode login = login(" ADMIN@EXAMPLE.TEST ");
|
||||||
|
assertThat(login.path("tokenType").asText()).isEqualTo("Bearer");
|
||||||
|
assertThat(login.path("expiresIn").asLong()).isEqualTo(86400);
|
||||||
|
assertThat(login.path("user").path("userCode").asText()).isEqualTo(admin.userCode());
|
||||||
|
assertThat(login.path("user").size()).isEqualTo(3);
|
||||||
|
mvc.perform(get("/admin-api/users/me").header(HttpHeaders.AUTHORIZATION, bearer(login)))
|
||||||
|
.andExpect(status().isOk()).andExpect(jsonPath("$.data.email").value("admin@example.test"))
|
||||||
|
.andExpect(jsonPath("$.data.userCode").value(admin.userCode()))
|
||||||
|
.andExpect(jsonPath("$.data.id").doesNotExist()).andExpect(header().doesNotExist(HttpHeaders.SET_COOKIE));
|
||||||
|
mvc.perform(get("/admin-api/users/me")).andExpect(status().isUnauthorized());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void unknownAndNormalEmailsAreRejectedWithoutRegistrationOrPrivilegeEscalation() throws Exception {
|
||||||
|
jdbc.update("INSERT INTO sys_user (user_code,email,nickname,status,user_type) VALUES (?,?,'普通用户','ACTIVE','NORMAL')",
|
||||||
|
"B".repeat(32), "normal@example.test");
|
||||||
|
for (String email : List.of("normal@example.test", "unknown@example.test")) {
|
||||||
|
mvc.perform(post("/admin-api/auth/login").contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.content(body(email, captcha(), "ABCDE")))
|
||||||
|
.andExpect(status().isForbidden()).andExpect(jsonPath("$.code").value("ADMIN_ACCESS_DENIED"));
|
||||||
|
}
|
||||||
|
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM sys_user", Long.class)).isEqualTo(2);
|
||||||
|
assertThat(jdbc.queryForObject("SELECT user_type FROM sys_user WHERE email=?", String.class, "normal@example.test")).isEqualTo("NORMAL");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void invalidAndReusedCaptchaCannotLoginAndValidationRejectsBadEmail() throws Exception {
|
||||||
|
String code = captcha();
|
||||||
|
mvc.perform(post("/admin-api/auth/login").contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.content(body("admin@example.test", code, "WRONG")))
|
||||||
|
.andExpect(status().isBadRequest()).andExpect(jsonPath("$.code").value("CAPTCHA_INVALID"));
|
||||||
|
mvc.perform(post("/admin-api/auth/login").contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.content(body("admin@example.test", code, "ABCDE")))
|
||||||
|
.andExpect(status().isBadRequest());
|
||||||
|
mvc.perform(post("/admin-api/auth/login").contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.content(body("invalid-email", captcha(), "ABCDE")))
|
||||||
|
.andExpect(status().isUnprocessableEntity()).andExpect(jsonPath("$.code").value("INVALID_REQUEST"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void disabledAndDemotedAdminsLoseAccessOnTheirNextRequest() throws Exception {
|
||||||
|
JsonNode login = login("admin@example.test");
|
||||||
|
jdbc.update("UPDATE sys_user SET status='DISABLED' WHERE user_code=?", admin.userCode());
|
||||||
|
mvc.perform(get("/admin-api/components").header(HttpHeaders.AUTHORIZATION, bearer(login)))
|
||||||
|
.andExpect(status().isUnauthorized()).andExpect(jsonPath("$.code").value("UNAUTHORIZED"));
|
||||||
|
mvc.perform(post("/admin-api/auth/login").header(HttpHeaders.ORIGIN, ORIGIN).contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.content(body("admin@example.test", captcha(), "ABCDE")))
|
||||||
|
.andExpect(status().isForbidden()).andExpect(jsonPath("$.code").value("ACCOUNT_DISABLED"))
|
||||||
|
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, ORIGIN));
|
||||||
|
jdbc.update("UPDATE sys_user SET status='ACTIVE', user_type='NORMAL' WHERE user_code=?", admin.userCode());
|
||||||
|
mvc.perform(get("/admin-api/users/me").header(HttpHeaders.AUTHORIZATION, bearer(login)))
|
||||||
|
.andExpect(status().isForbidden()).andExpect(jsonPath("$.code").value("ADMIN_ACCESS_DENIED"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void logoutOnlyRevokesCurrentAdminSessionAndOtherTokenStoresAreIndependent() throws Exception {
|
||||||
|
JsonNode first = login("admin@example.test");
|
||||||
|
JsonNode second = login("admin@example.test");
|
||||||
|
mvc.perform(post("/admin-api/auth/logout").header(HttpHeaders.AUTHORIZATION, bearer(first))).andExpect(status().isOk());
|
||||||
|
mvc.perform(get("/admin-api/users/me").header(HttpHeaders.AUTHORIZATION, bearer(first))).andExpect(status().isUnauthorized());
|
||||||
|
mvc.perform(get("/admin-api/users/me").header(HttpHeaders.AUTHORIZATION, bearer(second))).andExpect(status().isOk());
|
||||||
|
TokenService userSideTokens = new TokenService(properties);
|
||||||
|
mvc.perform(get("/admin-api/users/me").header(HttpHeaders.AUTHORIZATION, "Bearer " + userSideTokens.issue(admin.userCode())))
|
||||||
|
.andExpect(status().isUnauthorized());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void everyAdminBusinessRouteRequiresLoginIncludingDownloads() throws Exception {
|
||||||
|
for (String path : List.of("/admin-api/users/me", "/admin-api/components", "/admin-api/users", "/admin-api/operation-logs",
|
||||||
|
"/admin-api/component-assets/cadworld_dev/components/model.step")) {
|
||||||
|
mvc.perform(get(path).header("X-Request-Id", "admin-no-auth"))
|
||||||
|
.andExpect(status().isUnauthorized()).andExpect(jsonPath("$.code").value("UNAUTHORIZED"))
|
||||||
|
.andExpect(jsonPath("$.requestId").value("admin-no-auth"));
|
||||||
|
}
|
||||||
|
for (String path : List.of("/admin-api/components", "/admin-api/users", "/admin-api/storage/upload-signature", "/admin-api/auth/logout")) {
|
||||||
|
mvc.perform(post(path)).andExpect(status().isUnauthorized());
|
||||||
|
}
|
||||||
|
mvc.perform(put("/admin-api/components/1")).andExpect(status().isUnauthorized());
|
||||||
|
mvc.perform(delete("/admin-api/components/1")).andExpect(status().isUnauthorized());
|
||||||
|
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM sys_operation_log", Long.class)).isZero();
|
||||||
|
mvc.perform(get("/admin-api/auth/captcha").header(HttpHeaders.AUTHORIZATION, "Bearer stale"))
|
||||||
|
.andExpect(status().isOk()).andExpect(header().string(HttpHeaders.CACHE_CONTROL, "no-store"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void corsPreflightAndAuthenticationFailuresHaveCorrectHeaders() throws Exception {
|
||||||
|
mvc.perform(options("/admin-api/components").header(HttpHeaders.ORIGIN, ORIGIN)
|
||||||
|
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "PUT")
|
||||||
|
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "authorization,content-type,x-request-id"))
|
||||||
|
.andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, ORIGIN));
|
||||||
|
mvc.perform(get("/admin-api/users/me").header(HttpHeaders.ORIGIN, ORIGIN))
|
||||||
|
.andExpect(status().isUnauthorized()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, ORIGIN));
|
||||||
|
mvc.perform(get("/admin-api/users/me").header(HttpHeaders.ORIGIN, ORIGIN).header(HttpHeaders.AUTHORIZATION, "Bearer invalid"))
|
||||||
|
.andExpect(status().isUnauthorized()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, ORIGIN));
|
||||||
|
mvc.perform(options("/admin-api/components").header(HttpHeaders.ORIGIN, "https://untrusted.example")
|
||||||
|
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST"))
|
||||||
|
.andExpect(status().isForbidden()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void uploadsAndAuditUseActualAdminAndCannotReuseAnotherAdminsUploadSession() throws Exception {
|
||||||
|
JsonNode upload = data(mvc.perform(post("/admin-api/storage/upload-signature")
|
||||||
|
.header(HttpHeaders.AUTHORIZATION, "Bearer " + admin.token()).contentType(MediaType.APPLICATION_JSON).content("{}"))
|
||||||
|
.andExpect(status().isOk()).andReturn());
|
||||||
|
String renewal = json.writeValueAsString(Map.of("uploadSessionToken", upload.path("uploadSessionToken").asText()));
|
||||||
|
mvc.perform(post("/admin-api/storage/upload-signature").header(HttpHeaders.AUTHORIZATION, "Bearer " + admin.token())
|
||||||
|
.contentType(MediaType.APPLICATION_JSON).content(renewal)).andExpect(status().isOk());
|
||||||
|
AdminAuthTestSupport.Session other = AdminAuthTestSupport.create(jdbc, tokens);
|
||||||
|
mvc.perform(post("/admin-api/storage/upload-signature").header(HttpHeaders.AUTHORIZATION, "Bearer " + other.token())
|
||||||
|
.contentType(MediaType.APPLICATION_JSON).content(renewal))
|
||||||
|
.andExpect(status().isUnprocessableEntity()).andExpect(jsonPath("$.code").value("INVALID_COMPONENT_UPLOAD_SESSION"));
|
||||||
|
mvc.perform(post("/admin-api/components").header(HttpHeaders.AUTHORIZATION, "Bearer " + admin.token())
|
||||||
|
.contentType(MediaType.APPLICATION_JSON).content("{}"))
|
||||||
|
.andExpect(status().isUnprocessableEntity());
|
||||||
|
assertThat(jdbc.queryForObject("SELECT operator_id FROM sys_operation_log WHERE action='CREATE'", Long.class)).isEqualTo(admin.userId());
|
||||||
|
assertThat(jdbc.queryForObject("SELECT operator_name FROM sys_operation_log WHERE action='CREATE'", String.class)).isEqualTo("测试管理员");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void databaseFailureDuringAuthenticationUsesExistingErrorEnvelope() throws Exception {
|
||||||
|
doThrow(new DataAccessResourceFailureException("test unavailable")).when(users).requireActive(admin.userCode());
|
||||||
|
mvc.perform(get("/admin-api/users/me").header(HttpHeaders.AUTHORIZATION, "Bearer " + admin.token()))
|
||||||
|
.andExpect(status().isServiceUnavailable()).andExpect(jsonPath("$.code").value("DATABASE_UNAVAILABLE"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void swaggerDocumentsBearerAuthenticationAndLoginRoutesArePublic() throws Exception {
|
||||||
|
mvc.perform(get("/api-docs")).andExpect(status().isOk())
|
||||||
|
.andExpect(jsonPath("$.components.securitySchemes.adminBearer.scheme").value("bearer"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void adminAuthenticationLogsDoNotExposeTokensCaptchaOrEmail() throws Exception {
|
||||||
|
Logger logger = (Logger) LoggerFactory.getLogger("com.linkerbot.cadworld");
|
||||||
|
ListAppender<ILoggingEvent> capture = new ListAppender<>();
|
||||||
|
capture.start(); logger.addAppender(capture);
|
||||||
|
try {
|
||||||
|
JsonNode login = login("admin@example.test");
|
||||||
|
mvc.perform(post("/admin-api/auth/logout").header(HttpHeaders.AUTHORIZATION, bearer(login))).andExpect(status().isOk());
|
||||||
|
mvc.perform(get("/admin-api/users/me").header(HttpHeaders.AUTHORIZATION, "Bearer PRIVATE_ADMIN_TOKEN"))
|
||||||
|
.andExpect(status().isUnauthorized());
|
||||||
|
String logs = String.join("\n", capture.list.stream().map(ILoggingEvent::getFormattedMessage).toList());
|
||||||
|
assertThat(logs).contains("管理员登录成功", "管理员退出登录", "UNAUTHORIZED");
|
||||||
|
assertThat(logs).doesNotContain("admin@example.test", "PRIVATE_ADMIN_TOKEN", "ABCDE", login.path("token").asText(), "data:image/png;base64,");
|
||||||
|
} finally {
|
||||||
|
logger.detachAppender(capture); capture.stop();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private String captcha() throws Exception {
|
||||||
|
return data(mvc.perform(get("/admin-api/auth/captcha")).andExpect(status().isOk()).andReturn()).path("captchaCode").asText();
|
||||||
|
}
|
||||||
|
|
||||||
|
private JsonNode login(String email) throws Exception {
|
||||||
|
return data(mvc.perform(post("/admin-api/auth/login").header(HttpHeaders.AUTHORIZATION, "Bearer stale")
|
||||||
|
.contentType(MediaType.APPLICATION_JSON).content(body(email, captcha(), "abcde")))
|
||||||
|
.andExpect(status().isOk()).andExpect(header().string(HttpHeaders.CACHE_CONTROL, "no-store")).andReturn());
|
||||||
|
}
|
||||||
|
|
||||||
|
private String body(String email, String code, String answer) throws Exception {
|
||||||
|
return json.writeValueAsString(Map.of("email", email, "captchaCode", code, "captchaAnswer", answer));
|
||||||
|
}
|
||||||
|
|
||||||
|
private String bearer(JsonNode login) { return "Bearer " + login.path("token").asText(); }
|
||||||
|
private JsonNode data(MvcResult result) throws Exception { return json.readTree(result.getResponse().getContentAsByteArray()).path("data"); }
|
||||||
|
|
||||||
|
@TestConfiguration(proxyBeanMethods = false)
|
||||||
|
static class CaptchaConfiguration {
|
||||||
|
@Bean @Primary CaptchaService fixedAdminCaptcha(AuthProperties properties) {
|
||||||
|
return new CaptchaService(properties) {
|
||||||
|
@Override protected String generateAnswer() { return "ABCDE"; }
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
package com.linkerbot.cadworld;
|
||||||
|
|
||||||
|
import com.linkerbot.cadworld.security.common.TokenService;
|
||||||
|
import com.linkerbot.cadworld.service.support.UserCodes;
|
||||||
|
import java.util.Locale;
|
||||||
|
import org.springframework.jdbc.core.JdbcTemplate;
|
||||||
|
|
||||||
|
final class AdminAuthTestSupport {
|
||||||
|
private AdminAuthTestSupport() {
|
||||||
|
}
|
||||||
|
|
||||||
|
record Session(long userId, String userCode, String token) {
|
||||||
|
}
|
||||||
|
|
||||||
|
static Session create(JdbcTemplate jdbc, TokenService tokens) {
|
||||||
|
String code = UserCodes.generate();
|
||||||
|
jdbc.update("INSERT INTO sys_user (user_code,email,nickname,status,user_type) VALUES (?,?,?,'ACTIVE','ADMIN')",
|
||||||
|
code, code.toLowerCase(Locale.ROOT) + "@example.test", "测试管理员");
|
||||||
|
Long id = jdbc.queryForObject("SELECT id FROM sys_user WHERE user_code=?", Long.class, code);
|
||||||
|
return new Session(id, code, tokens.issue(code));
|
||||||
|
}
|
||||||
|
}
|
||||||
+96
@@ -0,0 +1,96 @@
|
|||||||
|
package com.linkerbot.cadworld;
|
||||||
|
|
||||||
|
import com.linkerbot.cadworld.common.exception.BizException;
|
||||||
|
import com.linkerbot.cadworld.config.StorageProperties;
|
||||||
|
import com.linkerbot.cadworld.service.client.ObjectStorageClient;
|
||||||
|
import com.linkerbot.cadworld.service.support.StorageObjectKeys;
|
||||||
|
import com.linkerbot.cadworld.service.support.UploadLimits;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.io.OutputStream;
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
import org.springframework.boot.test.context.TestConfiguration;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Primary;
|
||||||
|
|
||||||
|
/** 仅用于自动化业务测试;运行时始终使用真实 OSS。 */
|
||||||
|
@TestConfiguration(proxyBeanMethods = false)
|
||||||
|
class InMemoryObjectStorageConfiguration {
|
||||||
|
@Bean
|
||||||
|
org.springframework.beans.factory.InitializingBean testSchema(org.springframework.jdbc.core.JdbcTemplate jdbc) {
|
||||||
|
return () -> TestSchemaSupport.prepare(jdbc);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
@Primary
|
||||||
|
InMemoryObjectStorageClient inMemoryObjectStorageClient(StorageProperties properties, StorageObjectKeys keys) {
|
||||||
|
return new InMemoryObjectStorageClient(properties, keys);
|
||||||
|
}
|
||||||
|
|
||||||
|
static class InMemoryObjectStorageClient implements ObjectStorageClient {
|
||||||
|
private record Entry(String contentType, byte[] bytes) { }
|
||||||
|
private final Map<String, Entry> objects = new ConcurrentHashMap<>();
|
||||||
|
private final StorageProperties properties;
|
||||||
|
private final StorageObjectKeys keys;
|
||||||
|
|
||||||
|
InMemoryObjectStorageClient(StorageProperties properties, StorageObjectKeys keys) {
|
||||||
|
this.properties = properties;
|
||||||
|
this.keys = keys;
|
||||||
|
}
|
||||||
|
|
||||||
|
void clear() { objects.clear(); }
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public UploadAuthorization createUploadAuthorization(String prefix, Instant expiresAt) {
|
||||||
|
keys.requirePrefix(prefix);
|
||||||
|
return new UploadAuthorization("https://test-bucket.oss-cn-beijing.aliyuncs.com/",
|
||||||
|
Map.of("policy", "FAKE_TEST_POLICY", "x-oss-signature", "FAKE_TEST_SIGNATURE",
|
||||||
|
"success_action_status", "204", "x-oss-forbid-overwrite", "true"), expiresAt);
|
||||||
|
}
|
||||||
|
|
||||||
|
void simulateDirectUpload(String key, String contentType, byte[] bytes) {
|
||||||
|
objects.put(keys.requireKey(key), new Entry(contentType, bytes.clone()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void putObject(String key, String contentType, InputStream input, long length) {
|
||||||
|
String normalized = keys.requireKey(key);
|
||||||
|
UploadLimits.checkLength(length, properties.maxUploadBytes());
|
||||||
|
try {
|
||||||
|
byte[] bytes = UploadLimits.bounded(input, properties.maxUploadBytes()).readAllBytes();
|
||||||
|
objects.put(normalized, new Entry(contentType, bytes));
|
||||||
|
} catch (IOException exception) {
|
||||||
|
throw new IllegalStateException(exception);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean objectExists(String key) { return objects.containsKey(keys.requireKey(key)); }
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void deleteObject(String key) { objects.remove(keys.requireKey(key)); }
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public StoredObject statObject(String key) {
|
||||||
|
Entry entry = require(key);
|
||||||
|
return new StoredObject(entry.contentType(), entry.bytes().length);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void writeObjectTo(String key, OutputStream output) {
|
||||||
|
try {
|
||||||
|
output.write(require(key).bytes());
|
||||||
|
} catch (IOException exception) {
|
||||||
|
throw new IllegalStateException(exception);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Entry require(String key) {
|
||||||
|
Entry entry = objects.get(keys.requireKey(key));
|
||||||
|
if (entry == null) throw new BizException(404, "OSS_OBJECT_NOT_FOUND", "文件不存在");
|
||||||
|
return entry;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,130 @@
|
|||||||
|
package com.linkerbot.cadworld;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.*;
|
||||||
|
|
||||||
|
import com.linkerbot.cadworld.common.exception.BizException;
|
||||||
|
import com.linkerbot.cadworld.config.OssClientConfiguration;
|
||||||
|
import com.linkerbot.cadworld.config.OssProperties;
|
||||||
|
import com.linkerbot.cadworld.config.StorageProperties;
|
||||||
|
import com.linkerbot.cadworld.service.client.ObjectStorageClient.UploadAuthorization;
|
||||||
|
import com.linkerbot.cadworld.service.client.OssObjectStorageClient;
|
||||||
|
import com.linkerbot.cadworld.service.support.StorageObjectKeys;
|
||||||
|
import java.io.ByteArrayOutputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.http.HttpClient;
|
||||||
|
import java.net.http.HttpRequest;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.UUID;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.context.annotation.Import;
|
||||||
|
import org.springframework.test.context.ActiveProfiles;
|
||||||
|
import org.springframework.test.context.DynamicPropertyRegistry;
|
||||||
|
import org.springframework.test.context.DynamicPropertySource;
|
||||||
|
|
||||||
|
/** 通过 -P oss-integration 单独启用;不加载数据库或业务测试内存替身。 */
|
||||||
|
@SpringBootTest(classes = OssObjectStorageIT.Config.class, properties = {
|
||||||
|
"spring.main.web-application-type=none", "app.storage.max-upload-bytes=8",
|
||||||
|
"logging.file.path=target/oss-integration-logs"
|
||||||
|
})
|
||||||
|
@ActiveProfiles("test")
|
||||||
|
class OssObjectStorageIT {
|
||||||
|
private static final String RUN_ID = UUID.randomUUID().toString();
|
||||||
|
@Autowired OssObjectStorageClient storage;
|
||||||
|
@Autowired StorageObjectKeys keys;
|
||||||
|
|
||||||
|
@Configuration(proxyBeanMethods = false)
|
||||||
|
@EnableConfigurationProperties({StorageProperties.class, OssProperties.class})
|
||||||
|
@Import({OssClientConfiguration.class, OssObjectStorageClient.class, StorageObjectKeys.class})
|
||||||
|
static class Config { }
|
||||||
|
|
||||||
|
@DynamicPropertySource
|
||||||
|
static void isolateObjects(DynamicPropertyRegistry registry) {
|
||||||
|
String root = System.getProperty("cadworld.it.oss-root-prefix", "cadworld_dev").trim().replaceAll("/+$", "");
|
||||||
|
if (root.equals("cadworld") || root.startsWith("cadworld/")) {
|
||||||
|
throw new IllegalArgumentException("OSS 集成测试不能使用默认生产目录 cadworld");
|
||||||
|
}
|
||||||
|
registry.add("app.storage.root-prefix", () -> root + "/verification/" + RUN_ID);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void realDirectoryPostUploadsMultipleFilesRejectsOverwriteAndLimitAndCleansExactKeys() throws Exception {
|
||||||
|
String prefix = keys.underRoot("batch") + "/";
|
||||||
|
String model = prefix + "robot.urdf";
|
||||||
|
String mesh = prefix + "meshes/base.stl";
|
||||||
|
String oversized = prefix + "oversized.rfs";
|
||||||
|
String outside = keys.underRoot("outside.rfs");
|
||||||
|
List<String> attempted = List.of(model, mesh, oversized, outside);
|
||||||
|
Path journal = Path.of("logs", "oss-verification-pending", RUN_ID + ".txt");
|
||||||
|
Files.createDirectories(journal.getParent());
|
||||||
|
Files.write(journal, attempted);
|
||||||
|
Throwable originalFailure = null;
|
||||||
|
UploadAuthorization authorization = storage.createUploadAuthorization(prefix, java.time.Instant.now().plusSeconds(300));
|
||||||
|
try (HttpClient http = HttpClient.newBuilder().connectTimeout(java.time.Duration.ofSeconds(10)).build()) {
|
||||||
|
assertThat(post(http, authorization, model, new byte[]{1,2})).isEqualTo(204);
|
||||||
|
assertThat(post(http, authorization, mesh, new byte[]{3,4})).isEqualTo(204);
|
||||||
|
assertThat(storage.statObject(model).contentLength()).isEqualTo(2);
|
||||||
|
assertThat(storage.statObject(mesh).contentLength()).isEqualTo(2);
|
||||||
|
assertThat(post(http, authorization, model, new byte[]{9})).isEqualTo(409);
|
||||||
|
assertThat(post(http, authorization, oversized, new byte[9])).isBetween(400,499);
|
||||||
|
assertThat(post(http, authorization, outside, new byte[]{1})).isBetween(400,499);
|
||||||
|
ByteArrayOutputStream output = new ByteArrayOutputStream();
|
||||||
|
storage.writeObjectTo(model, output);
|
||||||
|
assertThat(output.toByteArray()).containsExactly((byte)1,(byte)2);
|
||||||
|
output.reset(); storage.writeObjectTo(mesh,output);
|
||||||
|
assertThat(output.toByteArray()).containsExactly((byte)3,(byte)4);
|
||||||
|
} catch (Exception | Error failure) {
|
||||||
|
originalFailure = failure;
|
||||||
|
throw failure;
|
||||||
|
} finally {
|
||||||
|
ArrayList<String> pending = new ArrayList<String>();
|
||||||
|
for (String key : attempted) {
|
||||||
|
try {
|
||||||
|
if (storage.objectExists(key)) storage.deleteObject(key);
|
||||||
|
} catch (RuntimeException failure) {
|
||||||
|
pending.add(key);
|
||||||
|
System.err.println("OSS 验证对象清理失败 key=" + key + " errorCode="
|
||||||
|
+ (failure instanceof BizException error ? error.getCode() : failure.getClass().getSimpleName()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (pending.isEmpty()) Files.deleteIfExists(journal);
|
||||||
|
else {
|
||||||
|
Files.write(journal,pending);
|
||||||
|
AssertionError cleanupFailure = new AssertionError("OSS 清理失败,准确 Key 记录在 " + journal);
|
||||||
|
if (originalFailure == null) throw cleanupFailure;
|
||||||
|
originalFailure.addSuppressed(cleanupFailure);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private int post(java.net.http.HttpClient http,
|
||||||
|
com.linkerbot.cadworld.service.client.ObjectStorageClient.UploadAuthorization authorization,
|
||||||
|
String key, byte[] bytes) throws Exception {
|
||||||
|
String boundary = "cadworld-" + UUID.randomUUID();
|
||||||
|
ByteArrayOutputStream body = new ByteArrayOutputStream();
|
||||||
|
for (Map.Entry<String, String> field : authorization.uploadFields().entrySet()) {
|
||||||
|
multipartField(body,boundary,field.getKey(),field.getValue());
|
||||||
|
}
|
||||||
|
multipartField(body,boundary,"key",key);
|
||||||
|
body.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"file\"; filename=\"file.bin\"\r\n"
|
||||||
|
+ "Content-Type: application/octet-stream\r\n\r\n").getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||||||
|
body.write(bytes);
|
||||||
|
body.write(("\r\n--" + boundary + "--\r\n").getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||||||
|
HttpRequest request = HttpRequest.newBuilder(java.net.URI.create(authorization.uploadUrl()))
|
||||||
|
.timeout(java.time.Duration.ofSeconds(30))
|
||||||
|
.header("Content-Type","multipart/form-data; boundary=" + boundary)
|
||||||
|
.POST(java.net.http.HttpRequest.BodyPublishers.ofByteArray(body.toByteArray())).build();
|
||||||
|
return http.send(request,java.net.http.HttpResponse.BodyHandlers.discarding()).statusCode();
|
||||||
|
}
|
||||||
|
private void multipartField(ByteArrayOutputStream body, String boundary, String name, String value) throws IOException {
|
||||||
|
body.write(("--"+boundary+"\r\nContent-Disposition: form-data; name=\""+name+"\"\r\n\r\n"+value+"\r\n")
|
||||||
|
.getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
package com.linkerbot.cadworld;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.*;
|
||||||
|
|
||||||
|
import com.linkerbot.cadworld.config.StorageProperties;
|
||||||
|
import com.linkerbot.cadworld.service.support.StorageObjectKeys;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||||
|
import org.springframework.boot.test.context.ConfigDataApplicationContextInitializer;
|
||||||
|
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
|
||||||
|
class StorageEnvironmentTest {
|
||||||
|
final ApplicationContextRunner runner = new ApplicationContextRunner()
|
||||||
|
.withInitializer(new ConfigDataApplicationContextInitializer())
|
||||||
|
.withUserConfiguration(Config.class);
|
||||||
|
|
||||||
|
@Configuration(proxyBeanMethods = false)
|
||||||
|
@EnableConfigurationProperties(StorageProperties.class)
|
||||||
|
static class Config { }
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testAndProductionHaveSeparateDefaultsAndDefaultProfileIsTest() {
|
||||||
|
runner.run(context -> assertThat(context.getBean(StorageProperties.class).rootPrefix()).isEqualTo("cadworld_dev"));
|
||||||
|
runner.withPropertyValues("spring.profiles.active=test").run(context ->
|
||||||
|
assertThat(context.getBean(StorageProperties.class).rootPrefix()).isEqualTo("cadworld_dev"));
|
||||||
|
runner.withPropertyValues("spring.profiles.active=prod").run(context ->
|
||||||
|
assertThat(context.getBean(StorageProperties.class).rootPrefix()).isEqualTo("cadworld"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void signatureTtlDefaultsToFiveMinutesAndEnvironmentOverrideIsBound() {
|
||||||
|
runner.run(context -> assertThat(context.getBean(StorageProperties.class).uploadSignatureTtl()).isEqualTo(java.time.Duration.ofMinutes(5)));
|
||||||
|
runner.withPropertyValues("OSS_UPLOAD_SIGNATURE_TTL=PT2M").run(context ->
|
||||||
|
assertThat(context.getBean(StorageProperties.class).uploadSignatureTtl()).isEqualTo(java.time.Duration.ofMinutes(2)));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void rootOverrideWorksInBothProfilesAndIsAddedOnce() {
|
||||||
|
for (String profile : new String[]{"test", "prod"}) {
|
||||||
|
runner.withPropertyValues("spring.profiles.active=" + profile, "OSS_ROOT_PREFIX=custom/assets/")
|
||||||
|
.run(context -> {
|
||||||
|
StorageObjectKeys keys = new StorageObjectKeys(context.getBean(StorageProperties.class));
|
||||||
|
String key = keys.underRoot("components/urdf/model.rfs");
|
||||||
|
assertThat(key).isEqualTo("custom/assets/components/urdf/model.rfs");
|
||||||
|
assertThat(keys.requireKey(key)).isEqualTo(key);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
package com.linkerbot.cadworld;
|
||||||
|
|
||||||
|
import org.springframework.jdbc.core.JdbcTemplate;
|
||||||
|
|
||||||
|
/** 只初始化进程内H2测试库,不读取旧SQL脚本,不允许接入业务数据库。 */
|
||||||
|
final class TestSchemaSupport {
|
||||||
|
private TestSchemaSupport() { }
|
||||||
|
static void prepare(JdbcTemplate jdbc) {
|
||||||
|
String product = jdbc.execute((org.springframework.jdbc.core.ConnectionCallback<String>)
|
||||||
|
connection -> connection.getMetaData().getDatabaseProductName());
|
||||||
|
if (!"H2".equals(product)) throw new IllegalStateException("测试初始化只允许使用H2");
|
||||||
|
jdbc.execute("""
|
||||||
|
CREATE TABLE IF NOT EXISTS component (
|
||||||
|
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')) COMMENT '组件状态: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 COMMENT '自由度,非负整数',
|
||||||
|
rotation_axis CHAR(1) DEFAULT NULL CHECK (rotation_axis IN ('X','Y','Z')) COMMENT '旋转轴:X、Y、Z;NULL表示未设置',
|
||||||
|
function_description VARCHAR(512) NOT NULL DEFAULT '' COMMENT '组件功能描述',
|
||||||
|
shape VARCHAR(128) NOT NULL DEFAULT '' COMMENT '组件形状描述',
|
||||||
|
size VARCHAR(128) NOT NULL DEFAULT '' COMMENT '组件大小描述',
|
||||||
|
torque_nm DECIMAL(18,6) NOT NULL DEFAULT 0 COMMENT '扭矩,单位牛顿米,非负',
|
||||||
|
bom_list CLOB NOT NULL COMMENT 'BOM清单,JSON对象或数组',
|
||||||
|
urdf_info CLOB NOT NULL COMMENT 'URDF信息',
|
||||||
|
basic_fields CLOB NOT NULL DEFAULT '[]',
|
||||||
|
parameter_fields CLOB NOT NULL DEFAULT '[]',
|
||||||
|
step_object_key VARCHAR(512) NOT NULL DEFAULT '',
|
||||||
|
urdf_prefix VARCHAR(512) NOT NULL DEFAULT '',
|
||||||
|
urdf_main_object_key VARCHAR(512) NOT NULL DEFAULT '',
|
||||||
|
urdf_files CLOB NOT NULL DEFAULT '[]',
|
||||||
|
version BIGINT NOT NULL DEFAULT 1,
|
||||||
|
deleted TINYINT NOT NULL DEFAULT 0 COMMENT '删除标记:0-未删除,1-已删除',
|
||||||
|
created_at TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
updated_at TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||||
|
)
|
||||||
|
""");
|
||||||
|
jdbc.execute("""
|
||||||
|
CREATE TABLE IF NOT EXISTS sys_operation_log (
|
||||||
|
id BIGINT AUTO_INCREMENT PRIMARY KEY,
|
||||||
|
module VARCHAR(64) NOT NULL DEFAULT '',
|
||||||
|
action VARCHAR(64) NOT NULL DEFAULT '',
|
||||||
|
target_type VARCHAR(64) NOT NULL DEFAULT '',
|
||||||
|
target_id VARCHAR(128) NOT NULL DEFAULT '',
|
||||||
|
target_code VARCHAR(128) NOT NULL DEFAULT '',
|
||||||
|
target_name VARCHAR(256) NOT NULL DEFAULT '',
|
||||||
|
operator_id BIGINT NOT NULL DEFAULT 0,
|
||||||
|
operator_name VARCHAR(128) NOT NULL DEFAULT '',
|
||||||
|
request_path VARCHAR(512) NOT NULL DEFAULT '',
|
||||||
|
request_method VARCHAR(16) NOT NULL DEFAULT '',
|
||||||
|
client_ip VARCHAR(64) NOT NULL DEFAULT '',
|
||||||
|
request_id VARCHAR(64) NOT NULL DEFAULT '',
|
||||||
|
operated_at TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
duration_ms BIGINT NOT NULL DEFAULT 0,
|
||||||
|
success BOOLEAN NOT NULL DEFAULT FALSE,
|
||||||
|
http_status INTEGER NOT NULL DEFAULT 0,
|
||||||
|
error_code VARCHAR(64) NOT NULL DEFAULT '',
|
||||||
|
error_summary VARCHAR(1000) NOT NULL DEFAULT ''
|
||||||
|
)
|
||||||
|
""");
|
||||||
|
jdbc.execute("""
|
||||||
|
CREATE TABLE IF NOT EXISTS sys_user (
|
||||||
|
id BIGINT AUTO_INCREMENT PRIMARY KEY,
|
||||||
|
user_code CHAR(32) NOT NULL UNIQUE,
|
||||||
|
email VARCHAR(254) NOT NULL UNIQUE,
|
||||||
|
nickname VARCHAR(64) NOT NULL DEFAULT '',
|
||||||
|
status VARCHAR(32) NOT NULL DEFAULT 'ACTIVE',
|
||||||
|
user_type VARCHAR(32) NOT NULL DEFAULT 'NORMAL',
|
||||||
|
created_at TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
updated_at TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||||
|
)
|
||||||
|
""");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
package com.linkerbot.cadworld;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
|
import com.linkerbot.cadworld.security.common.TokenService;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.boot.test.web.client.TestRestTemplate;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.jdbc.core.JdbcTemplate;
|
||||||
|
import org.springframework.test.context.ActiveProfiles;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import static org.assertj.core.api.Assertions.*;
|
||||||
|
|
||||||
|
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = {
|
||||||
|
"spring.datasource.url=jdbc:h2:mem:upload-http;MODE=MySQL;DB_CLOSE_DELAY=-1",
|
||||||
|
"spring.datasource.driver-class-name=org.h2.Driver","spring.datasource.username=sa","spring.datasource.password=",
|
||||||
|
"spring.sql.init.mode=never","app.storage.root-prefix=cadworld_dev","app.storage.max-upload-bytes=1024",
|
||||||
|
"logging.file.path=target/test-logs"
|
||||||
|
})
|
||||||
|
@ActiveProfiles("verification")
|
||||||
|
@org.springframework.context.annotation.Import(InMemoryObjectStorageConfiguration.class)
|
||||||
|
class UploadHttpTest {
|
||||||
|
@Autowired TestRestTemplate http;
|
||||||
|
@Autowired TokenService tokens;
|
||||||
|
@Autowired JdbcTemplate jdbc;
|
||||||
|
@Autowired InMemoryObjectStorageConfiguration.InMemoryObjectStorageClient storage;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void oversizeDirectUploadIsRejectedAtComponentSaveWithoutCreatingRowAndAuditedOnce() {
|
||||||
|
AdminAuthTestSupport.Session admin = AdminAuthTestSupport.create(jdbc, tokens);
|
||||||
|
http.getRestTemplate().setInterceptors(List.of((request, body, execution) -> {
|
||||||
|
request.getHeaders().setBearerAuth(admin.token());
|
||||||
|
return execution.execute(request, body);
|
||||||
|
}));
|
||||||
|
JsonNode session = http.postForObject("/admin-api/storage/upload-signature",Map.of(),JsonNode.class).path("data");
|
||||||
|
String step = session.path("step").path("keyPrefix").asText()+"model.step";
|
||||||
|
String main = session.path("urdf").path("keyPrefix").asText()+"robot.urdf";
|
||||||
|
storage.simulateDirectUpload(step,"application/octet-stream",new byte[1025]);
|
||||||
|
storage.simulateDirectUpload(main,"application/xml",new byte[]{1});
|
||||||
|
ResponseEntity<String> response = http.postForEntity("/admin-api/components",Map.of(
|
||||||
|
"componentName","超限测试","category","安装板","uploadSessionToken",session.path("uploadSessionToken").asText(),
|
||||||
|
"stepObjectKey",step,"urdfObjectKeys",List.of(main),"urdfInfo",Map.of()),String.class);
|
||||||
|
assertThat(response.getStatusCode().value()).isEqualTo(413);
|
||||||
|
assertThat(response.getBody()).contains("UPLOAD_TOO_LARGE");
|
||||||
|
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM component",Long.class)).isZero();
|
||||||
|
org.awaitility.Awaitility.await().atMost(java.time.Duration.ofSeconds(5)).untilAsserted(() ->
|
||||||
|
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM sys_operation_log WHERE action='CREATE' AND success=FALSE",Long.class)).isEqualTo(1));
|
||||||
|
assertThat(jdbc.queryForObject("SELECT operator_id FROM sys_operation_log WHERE action='CREATE'", Long.class))
|
||||||
|
.isEqualTo(admin.userId());
|
||||||
|
}
|
||||||
|
}
|
||||||
+62
@@ -0,0 +1,62 @@
|
|||||||
|
package com.linkerbot.cadworld.audit;
|
||||||
|
|
||||||
|
import com.linkerbot.cadworld.entity.OperationLog;
|
||||||
|
import com.linkerbot.cadworld.service.AdminOperatorProvider;
|
||||||
|
import com.linkerbot.cadworld.service.OperationLogService;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.mockito.ArgumentCaptor;
|
||||||
|
import org.springframework.mock.web.MockHttpServletRequest;
|
||||||
|
import org.springframework.mock.web.MockHttpServletResponse;
|
||||||
|
import org.springframework.web.method.HandlerMethod;
|
||||||
|
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
|
||||||
|
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.*;
|
||||||
|
import static org.mockito.Mockito.*;
|
||||||
|
|
||||||
|
class OperationAuditInterceptorTest {
|
||||||
|
@Test
|
||||||
|
void multipartFailureBeforeMvcIsAuditedOnce() throws Exception {
|
||||||
|
OperationLogService service = mock(OperationLogService.class);
|
||||||
|
OperationAuditInterceptor audit = new OperationAuditInterceptor(service, operator());
|
||||||
|
RequestMappingHandlerMapping mappings = mock(RequestMappingHandlerMapping.class);
|
||||||
|
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/admin-api/components");
|
||||||
|
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||||
|
HandlerMethod handler = new HandlerMethod(this, getClass().getDeclaredMethod("operation"));
|
||||||
|
RequestMappingInfo.BuilderConfiguration options = new RequestMappingInfo.BuilderConfiguration();
|
||||||
|
options.setPatternParser(new org.springframework.web.util.pattern.PathPatternParser());
|
||||||
|
RequestMappingInfo mapping = RequestMappingInfo.paths("/admin-api/components")
|
||||||
|
.methods(org.springframework.web.bind.annotation.RequestMethod.POST).options(options).build();
|
||||||
|
when(mappings.getHandlerMethods()).thenReturn(java.util.Map.of(mapping, handler));
|
||||||
|
EarlyFailureAuditFilter filter = new EarlyFailureAuditFilter(mappings, audit);
|
||||||
|
filter.doFilter(request, response, (req, res) -> ((jakarta.servlet.http.HttpServletResponse) res).setStatus(413));
|
||||||
|
ArgumentCaptor<OperationLog> captured = ArgumentCaptor.forClass(OperationLog.class);
|
||||||
|
verify(service).record(captured.capture());
|
||||||
|
assertThat(captured.getValue().getSuccess()).isFalse();
|
||||||
|
assertThat(captured.getValue().getHttpStatus()).isEqualTo(413);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void logFailureDoesNotChangeTheBusinessResponse() throws Exception {
|
||||||
|
OperationLogService service = mock(OperationLogService.class);
|
||||||
|
doThrow(new IllegalStateException("database unavailable")).when(service).record(any());
|
||||||
|
OperationAuditInterceptor audit = new OperationAuditInterceptor(service, operator());
|
||||||
|
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/admin-api/components");
|
||||||
|
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||||
|
HandlerMethod handler = new HandlerMethod(this, getClass().getDeclaredMethod("operation"));
|
||||||
|
audit.preHandle(request, response, handler);
|
||||||
|
audit.afterCompletion(request, response, handler, null);
|
||||||
|
verify(service).record(any());
|
||||||
|
assertThat(response.getStatus()).isEqualTo(200);
|
||||||
|
}
|
||||||
|
|
||||||
|
@AuditOperation(module = "COMPONENT", action = "CREATE")
|
||||||
|
void operation() { }
|
||||||
|
|
||||||
|
private AdminOperatorProvider operator() {
|
||||||
|
AdminOperatorProvider operator = mock(AdminOperatorProvider.class);
|
||||||
|
when(operator.userId()).thenReturn(7L);
|
||||||
|
when(operator.name()).thenReturn("测试管理员");
|
||||||
|
return operator;
|
||||||
|
}
|
||||||
|
}
|
||||||
+116
@@ -0,0 +1,116 @@
|
|||||||
|
package com.linkerbot.cadworld.config;
|
||||||
|
|
||||||
|
import com.linkerbot.cadworld.audit.OperationAuditInterceptor;
|
||||||
|
import com.linkerbot.cadworld.common.web.RequestIdFilter;
|
||||||
|
import com.linkerbot.cadworld.service.AdminOperatorProvider;
|
||||||
|
import com.linkerbot.cadworld.service.OperationLogService;
|
||||||
|
import java.util.List;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.params.ParameterizedTest;
|
||||||
|
import org.junit.jupiter.params.provider.CsvSource;
|
||||||
|
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||||
|
import org.springframework.boot.test.context.ConfigDataApplicationContextInitializer;
|
||||||
|
import org.springframework.boot.test.context.TestConfiguration;
|
||||||
|
import org.springframework.boot.test.context.runner.WebApplicationContextRunner;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Import;
|
||||||
|
import org.springframework.core.env.StandardEnvironment;
|
||||||
|
import org.springframework.http.HttpHeaders;
|
||||||
|
import org.springframework.test.web.servlet.MockMvc;
|
||||||
|
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMethod;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.mockito.Mockito.mock;
|
||||||
|
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||||
|
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.options;
|
||||||
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
||||||
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
|
||||||
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||||
|
|
||||||
|
class AdminCorsConfigurationTest {
|
||||||
|
private final WebApplicationContextRunner runner = new WebApplicationContextRunner()
|
||||||
|
.withInitializer(context -> context.getEnvironment().getPropertySources()
|
||||||
|
.remove(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME))
|
||||||
|
.withInitializer(new ConfigDataApplicationContextInitializer())
|
||||||
|
.withUserConfiguration(CorsTestConfiguration.class);
|
||||||
|
|
||||||
|
@ParameterizedTest
|
||||||
|
@CsvSource({
|
||||||
|
"test, https://dev-cadworld-admin.robotquan.com, https://cadworld-admin.robotquan.com",
|
||||||
|
"prod, https://cadworld-admin.robotquan.com, https://dev-cadworld-admin.robotquan.com"
|
||||||
|
})
|
||||||
|
void profileAllowsItsFrontendAndRejectsOtherOrigins(String profile, String allowedOrigin, String otherOrigin) {
|
||||||
|
runner.withPropertyValues("spring.profiles.active=" + profile).run(context -> {
|
||||||
|
assertThat(context).hasNotFailed();
|
||||||
|
MockMvc mvc = MockMvcBuilders.webAppContextSetup(context).addFilters(new RequestIdFilter()).build();
|
||||||
|
for (String method : List.of("GET", "HEAD", "POST", "PUT", "DELETE")) {
|
||||||
|
mvc.perform(options("/admin-api/cors-probe").header(HttpHeaders.ORIGIN, allowedOrigin)
|
||||||
|
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, method)
|
||||||
|
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "content-type,authorization,x-request-id"))
|
||||||
|
.andExpect(status().isOk())
|
||||||
|
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, allowedOrigin))
|
||||||
|
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"))
|
||||||
|
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "3600"));
|
||||||
|
}
|
||||||
|
mvc.perform(get("/admin-api/cors-probe").header(HttpHeaders.ORIGIN, allowedOrigin)
|
||||||
|
.header("X-Request-Id", "cors-test"))
|
||||||
|
.andExpect(status().isOk()).andExpect(content().string("ok"))
|
||||||
|
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, allowedOrigin))
|
||||||
|
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, "X-Request-Id"))
|
||||||
|
.andExpect(header().string("X-Request-Id", "cors-test"));
|
||||||
|
for (String origin : List.of(otherOrigin, allowedOrigin.replace("https://", "http://"), "https://untrusted.example")) {
|
||||||
|
mvc.perform(options("/admin-api/cors-probe").header(HttpHeaders.ORIGIN, origin)
|
||||||
|
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "PUT"))
|
||||||
|
.andExpect(status().isForbidden())
|
||||||
|
.andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
|
||||||
|
mvc.perform(get("/admin-api/cors-probe").header(HttpHeaders.ORIGIN, origin))
|
||||||
|
.andExpect(status().isForbidden());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void environmentVariableCanOverrideWhitelistWithMultipleOrigins() {
|
||||||
|
runner.withPropertyValues("spring.profiles.active=test",
|
||||||
|
"APP_ADMIN_ALLOWED_ORIGINS=http://localhost:5173,https://custom.example").run(context -> {
|
||||||
|
assertThat(context).hasNotFailed();
|
||||||
|
MockMvc mvc = MockMvcBuilders.webAppContextSetup(context).build();
|
||||||
|
for (String origin : List.of("http://localhost:5173", "https://custom.example")) {
|
||||||
|
mvc.perform(get("/admin-api/cors-probe").header(HttpHeaders.ORIGIN, origin))
|
||||||
|
.andExpect(status().isOk())
|
||||||
|
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, origin));
|
||||||
|
}
|
||||||
|
mvc.perform(get("/admin-api/cors-probe").header(HttpHeaders.ORIGIN, "https://dev-cadworld-admin.robotquan.com"))
|
||||||
|
.andExpect(status().isForbidden());
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void credentialedCorsRejectsWildcardAtStartup() {
|
||||||
|
runner.withPropertyValues("spring.profiles.active=test", "APP_ADMIN_ALLOWED_ORIGINS=*")
|
||||||
|
.run(context -> assertThat(context.getStartupFailure()).hasRootCauseInstanceOf(IllegalArgumentException.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
@TestConfiguration(proxyBeanMethods = false)
|
||||||
|
@EnableWebMvc
|
||||||
|
@EnableConfigurationProperties(AdminCorsProperties.class)
|
||||||
|
@Import(WebConfig.class)
|
||||||
|
static class CorsTestConfiguration {
|
||||||
|
@Bean OperationAuditInterceptor audit() {
|
||||||
|
return new OperationAuditInterceptor(mock(OperationLogService.class), mock(AdminOperatorProvider.class));
|
||||||
|
}
|
||||||
|
@Bean ProbeController probeController() { return new ProbeController(); }
|
||||||
|
}
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
static class ProbeController {
|
||||||
|
@RequestMapping(value = "/admin-api/cors-probe", method = {
|
||||||
|
RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE
|
||||||
|
})
|
||||||
|
public String probe() { return "ok"; }
|
||||||
|
}
|
||||||
|
}
|
||||||
+44
@@ -0,0 +1,44 @@
|
|||||||
|
package com.linkerbot.cadworld.logging;
|
||||||
|
|
||||||
|
import ch.qos.logback.classic.Level;
|
||||||
|
import ch.qos.logback.classic.Logger;
|
||||||
|
import ch.qos.logback.classic.spi.ILoggingEvent;
|
||||||
|
import ch.qos.logback.core.AppenderBase;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.CopyOnWriteArrayList;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
/** 捕获请求日志,包括真实 Servlet 服务线程产生的日志。 */
|
||||||
|
public final class ApiRequestLogCapture implements AutoCloseable {
|
||||||
|
private final Logger logger = (Logger) LoggerFactory.getLogger(ApiRequestLoggingFilter.class);
|
||||||
|
private final Level previousLevel = logger.getLevel();
|
||||||
|
private final List<ILoggingEvent> events = new CopyOnWriteArrayList<>();
|
||||||
|
private final AppenderBase<ILoggingEvent> appender = new AppenderBase<>() {
|
||||||
|
@Override
|
||||||
|
protected void append(ILoggingEvent event) {
|
||||||
|
event.prepareForDeferredProcessing();
|
||||||
|
events.add(event);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
public ApiRequestLogCapture() {
|
||||||
|
appender.start();
|
||||||
|
logger.setLevel(Level.INFO);
|
||||||
|
logger.addAppender(appender);
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<ILoggingEvent> events() {
|
||||||
|
return List.copyOf(events);
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<String> messages() {
|
||||||
|
return events().stream().map(ILoggingEvent::getFormattedMessage).toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void close() {
|
||||||
|
logger.detachAppender(appender);
|
||||||
|
logger.setLevel(previousLevel);
|
||||||
|
appender.stop();
|
||||||
|
}
|
||||||
|
}
|
||||||
+81
@@ -0,0 +1,81 @@
|
|||||||
|
package com.linkerbot.cadworld.logging;
|
||||||
|
|
||||||
|
import ch.qos.logback.classic.Level;
|
||||||
|
import com.linkerbot.cadworld.common.api.RequestIdHolder;
|
||||||
|
import com.linkerbot.cadworld.common.web.RequestIdFilter;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.Map;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.mock.web.MockHttpServletRequest;
|
||||||
|
import org.springframework.mock.web.MockHttpServletResponse;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMethod;
|
||||||
|
import org.springframework.web.method.HandlerMethod;
|
||||||
|
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
|
||||||
|
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
|
||||||
|
import org.springframework.web.util.pattern.PathPatternParser;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.*;
|
||||||
|
import static org.mockito.Mockito.*;
|
||||||
|
|
||||||
|
class ApiRequestLoggingFilterTest {
|
||||||
|
@Test
|
||||||
|
void binaryDownloadLogs200WithoutReadingParametersOrFileContent() throws Exception {
|
||||||
|
ApiRequestLoggingFilter filter = filter("/admin-api/component-assets/**", RequestMethod.GET);
|
||||||
|
MockHttpServletRequest request = spy(new MockHttpServletRequest("GET", "/admin-api/component-assets/test.urdf"));
|
||||||
|
request.setQueryString("objectKey=13800000001-secret-token.txt");
|
||||||
|
request.setContent("private file content".getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||||||
|
request.addHeader("X-Request-Id", "binary-log-test");
|
||||||
|
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||||
|
try (ApiRequestLogCapture captured = new ApiRequestLogCapture()) {
|
||||||
|
new RequestIdFilter().doFilter(request, response, (req, res) ->
|
||||||
|
filter.doFilter(req, res, (innerRequest, innerResponse) -> response.setStatus(200)));
|
||||||
|
|
||||||
|
assertThat(captured.messages()).hasSize(2);
|
||||||
|
assertThat(captured.messages().getLast()).contains("description=测试接口", "result=SUCCESS",
|
||||||
|
"httpStatus=200", "code=HTTP_200", "requestId=binary-log-test");
|
||||||
|
assertThat(String.join("\n", captured.messages()))
|
||||||
|
.doesNotContain("13800000001", "secret-token", "private file content");
|
||||||
|
verify(request, never()).getParameter(anyString());
|
||||||
|
verify(request, never()).getParameterMap();
|
||||||
|
verify(request, never()).getInputStream();
|
||||||
|
assertThat(response.getContentAsByteArray()).isEmpty();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void downloadFailureRetainsOriginalExceptionAndHidesSensitiveMessagesAndFilePath() throws Exception {
|
||||||
|
ApiRequestLoggingFilter filter = filter("/admin-api/component-assets/**", RequestMethod.GET);
|
||||||
|
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/cadworld/admin-api/component-assets/13800000001-private-token.png");
|
||||||
|
request.setContextPath("/cadworld");
|
||||||
|
request.addHeader("X-Request-Id", "download-log-test");
|
||||||
|
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||||
|
IOException failure = new IOException("password=private-password, phone=13800000001");
|
||||||
|
try (ApiRequestLogCapture captured = new ApiRequestLogCapture()) {
|
||||||
|
assertThatThrownBy(() -> new RequestIdFilter().doFilter(request, response, (req, res) ->
|
||||||
|
filter.doFilter(req, res, (innerRequest, innerResponse) -> { throw failure; })))
|
||||||
|
.isSameAs(failure);
|
||||||
|
|
||||||
|
assertThat(captured.events()).hasSize(2);
|
||||||
|
assertThat(captured.events().getLast().getLevel()).isEqualTo(Level.ERROR);
|
||||||
|
assertThat(captured.messages().getLast()).contains("result=FAILURE", "exceptionType=IOException",
|
||||||
|
"path=/admin-api/component-assets/**", "requestId=download-log-test");
|
||||||
|
assertThat(String.join("\n", captured.messages()))
|
||||||
|
.doesNotContain("13800000001", "private-token", "private-password");
|
||||||
|
assertThat(captured.events().getLast().getThrowableProxy()).isNull();
|
||||||
|
assertThat(RequestIdHolder.get()).isNull();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private ApiRequestLoggingFilter filter(String path, RequestMethod method) throws Exception {
|
||||||
|
RequestMappingInfo.BuilderConfiguration options = new RequestMappingInfo.BuilderConfiguration();
|
||||||
|
options.setPatternParser(PathPatternParser.defaultInstance);
|
||||||
|
RequestMappingInfo mapping = RequestMappingInfo.paths(path).methods(method).options(options).build();
|
||||||
|
HandlerMethod handler = new HandlerMethod(this, getClass().getDeclaredMethod("endpoint"));
|
||||||
|
RequestMappingHandlerMapping mappings = mock(RequestMappingHandlerMapping.class);
|
||||||
|
when(mappings.getHandlerMethods()).thenReturn(Map.of(mapping, handler));
|
||||||
|
return new ApiRequestLoggingFilter(mappings);
|
||||||
|
}
|
||||||
|
|
||||||
|
@ApiRequestLog("测试接口")
|
||||||
|
void endpoint() { }
|
||||||
|
}
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
-- Run against a selected empty cadworld database. No database is created or selected here.
|
||||||
|
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS `sys_user` (
|
||||||
|
`id` bigint NOT NULL AUTO_INCREMENT,
|
||||||
|
`phone` varchar(32) NOT NULL,
|
||||||
|
`nickname` varchar(64) NOT NULL,
|
||||||
|
`status` varchar(32) NOT NULL DEFAULT 'ACTIVE',
|
||||||
|
`deleted` tinyint NOT NULL DEFAULT 0,
|
||||||
|
`user_type` varchar(32) NOT NULL DEFAULT 'NORMAL',
|
||||||
|
`created_at` datetime(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||||
|
`updated_at` datetime(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
|
||||||
|
PRIMARY KEY (`id`),
|
||||||
|
UNIQUE KEY `uk_sys_user_phone` (`phone`)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS `component` (
|
||||||
|
`id` bigint NOT NULL AUTO_INCREMENT,
|
||||||
|
`component_name` varchar(64) NOT NULL DEFAULT '',
|
||||||
|
`category` varchar(64) NOT NULL,
|
||||||
|
`robot_type` varchar(32) NOT NULL DEFAULT 'humanoid',
|
||||||
|
`company` varchar(64) NOT NULL DEFAULT '',
|
||||||
|
`model` varchar(64) NOT NULL DEFAULT '',
|
||||||
|
`source` varchar(255) NOT NULL DEFAULT '',
|
||||||
|
`cover_image_key` varchar(512) NOT NULL DEFAULT '',
|
||||||
|
`description` text NOT NULL,
|
||||||
|
`component_json` LONGTEXT NOT NULL,
|
||||||
|
`assembly_metadata` LONGTEXT NOT NULL,
|
||||||
|
`created_at` datetime(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||||
|
`updated_at` datetime(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
|
||||||
|
PRIMARY KEY (`id`),
|
||||||
|
KEY `idx_component_type_company` (`category`,`company`),
|
||||||
|
KEY `idx_component_type_model` (`category`,`model`),
|
||||||
|
KEY `idx_component_robot_type_component_type` (`robot_type`,`category`)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS interface_definition_v2 (
|
||||||
|
id VARCHAR(64) NOT NULL PRIMARY KEY,
|
||||||
|
name VARCHAR(128) NOT NULL,
|
||||||
|
description VARCHAR(500) NULL,
|
||||||
|
geometry_revision INT NOT NULL,
|
||||||
|
geometry_json LONGTEXT NOT NULL,
|
||||||
|
tolerances_json LONGTEXT NOT NULL,
|
||||||
|
connectable_targets_json LONGTEXT NULL,
|
||||||
|
display_forward_json LONGTEXT NULL,
|
||||||
|
source_asset_key VARCHAR(512) NULL,
|
||||||
|
source_geometry_hash VARCHAR(128) NULL,
|
||||||
|
created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||||
|
updated_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS interface_definition_revision (
|
||||||
|
id VARCHAR(96) NOT NULL PRIMARY KEY,
|
||||||
|
definition_id VARCHAR(64) NOT NULL,
|
||||||
|
geometry_revision INT NOT NULL,
|
||||||
|
definition_json LONGTEXT NOT NULL,
|
||||||
|
UNIQUE KEY uk_interface_geometry_revision (definition_id, geometry_revision)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS component_asset (
|
||||||
|
id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
|
||||||
|
component_id BIGINT NOT NULL,
|
||||||
|
object_key VARCHAR(512) NOT NULL,
|
||||||
|
relative_path VARCHAR(512) NOT NULL,
|
||||||
|
asset_kind VARCHAR(32) NOT NULL,
|
||||||
|
content_type VARCHAR(128) NULL,
|
||||||
|
size BIGINT NOT NULL DEFAULT 0,
|
||||||
|
sha256 VARCHAR(128) NULL,
|
||||||
|
is_primary TINYINT NOT NULL DEFAULT 0,
|
||||||
|
created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||||
|
updated_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
|
||||||
|
CONSTRAINT fk_component_asset_component FOREIGN KEY (component_id) REFERENCES component(id) ON DELETE CASCADE,
|
||||||
|
UNIQUE KEY uk_component_asset_object_key (object_key),
|
||||||
|
KEY idx_component_asset_component (component_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS sys_operation_log (
|
||||||
|
id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
|
||||||
|
module VARCHAR(32) NOT NULL,
|
||||||
|
action VARCHAR(32) NOT NULL,
|
||||||
|
target_id VARCHAR(512) NULL,
|
||||||
|
operator_id BIGINT NOT NULL,
|
||||||
|
operator_name VARCHAR(64) NOT NULL,
|
||||||
|
request_path VARCHAR(512) NOT NULL,
|
||||||
|
request_method VARCHAR(16) NOT NULL,
|
||||||
|
client_ip VARCHAR(64) NULL,
|
||||||
|
request_id VARCHAR(64) NULL,
|
||||||
|
operated_at DATETIME(3) NOT NULL,
|
||||||
|
duration_ms BIGINT NOT NULL,
|
||||||
|
success TINYINT NOT NULL,
|
||||||
|
http_status INT NOT NULL,
|
||||||
|
error_summary VARCHAR(1000) NULL,
|
||||||
|
KEY idx_operation_module_time (module, operated_at),
|
||||||
|
KEY idx_operation_operator_time (operator_id, operated_at),
|
||||||
|
KEY idx_operation_result_time (success, operated_at)
|
||||||
|
);
|
||||||
|
|
||||||
@@ -0,0 +1,887 @@
|
|||||||
|
# 用户端组件匹配与拼装 API(前端联调文档)
|
||||||
|
|
||||||
|
本文说明前端如何提交拼装需求、展示匹配结果、切换替代组件及加载模型。示例编码和模型域名仅用于说明,实际结果取决于组件库。
|
||||||
|
|
||||||
|
文字、图片需求的自动理解、选件及装配流程见 [自动生成机器人联调文档](robot-demand-api.md),消息完成事件直接返回 `match`,无需追问或确认。本文中的 `POST /api/robot-matches` 保留为直接提交结构化需求的接口,不调用模型;对话流程使用保存的完整分析,自动返回逐项校验及 `assembly.ready/blocked` 状态。
|
||||||
|
|
||||||
|
## 1. 接口总览
|
||||||
|
|
||||||
|
本地默认服务地址:`http://127.0.0.1:8991`。线上地址由部署环境提供。
|
||||||
|
|
||||||
|
| 方法 | 路径 | 用途 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| POST | `/api/robot-matches` | 按需求匹配组件,返回默认拼装方案和兼容替代组件 |
|
||||||
|
| GET | `/api/components/{componentCode}` | 按组件编码获取详情,包括 BOM、URDF 信息和模型地址 |
|
||||||
|
| POST | `/api/robot-conversations` | 创建文字/图片需求会话,后续接口见上述联调文档 |
|
||||||
|
|
||||||
|
所有 `/api/**` 业务接口均需要 Bearer Token,包括组件匹配和详情;先完成[邮箱与图片验证码登录](auth-api.md),请求头携带 `Authorization: Bearer <token>`。需求会话按登录用户隔离。组件使用 `componentCode` 标识,不返回数据库 ID。模型通过响应中的公开 OSS/CDN 地址加载。
|
||||||
|
|
||||||
|
新增组件编码格式为 `CW-` 加 16 位随机数字或大写字母(排除 `I/L/O/U`),总长 19,例如 `CW-7K3M9Q2R6V8X4T5N`。旧版 35 字符编码继续有效,以下部分示例保留旧编码。前端将编码视为不透明字符串,直接使用返回值查询和加载,不按固定长度截取或重组。
|
||||||
|
|
||||||
|
## 2. 请求与通用返回
|
||||||
|
|
||||||
|
POST 请求头:
|
||||||
|
|
||||||
|
```http
|
||||||
|
Content-Type: application/json
|
||||||
|
X-Request-Id: frontend-match-001
|
||||||
|
```
|
||||||
|
|
||||||
|
`X-Request-Id` 可选,用于联调排查;省略时后端生成。响应头和响应体均返回请求编号。
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"code": "OK",
|
||||||
|
"message": "success",
|
||||||
|
"data": {},
|
||||||
|
"requestId": "frontend-match-001"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
| 字段 | 类型 | 说明 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `code` | string | `OK` 表示接口执行成功;其他值为错误编码 |
|
||||||
|
| `message` | string | 成功时为 `success`,失败时为错误说明 |
|
||||||
|
| `data` | object / null | 成功时为接口数据,失败时为 null |
|
||||||
|
| `requestId` | string | 请求编号,反馈问题时一并提供 |
|
||||||
|
|
||||||
|
**HTTP 200 和 `code=OK` 表示请求执行成功,拼装是否达标需要继续检查 `data.status`。** 没有匹配组件时也返回 HTTP 200;请求参数错误返回 422,详情组件不存在或已删除返回 404,数据库不可用返回 503。
|
||||||
|
|
||||||
|
## 3. 匹配接口
|
||||||
|
|
||||||
|
`POST /api/robot-matches`
|
||||||
|
|
||||||
|
### 3.1 请求示例
|
||||||
|
|
||||||
|
只指定所需角色即可匹配:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"requiredParts": ["TORSO_0", "ARM_R"]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
包含关键词、整机条件和部件条件的请求:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"userInput": "我要一个双足跑步机器人,整体20自由度,质量不超过10kg,躯干用铝合金,右臂扭矩至少20N·m",
|
||||||
|
"requirements": ["双足", "机器人", "跑步"],
|
||||||
|
"requiredParts": [
|
||||||
|
"TORSO_0", "HEAD_0", "WAIST_0", "ARM_L", "ARM_R", "HAND_L", "HAND_R",
|
||||||
|
"LEG_L", "LEG_R", "FOOT_L", "FOOT_R"
|
||||||
|
],
|
||||||
|
"robotRequirements": {
|
||||||
|
"degreesOfFreedom": 20,
|
||||||
|
"functionDescription": "跑步",
|
||||||
|
"massKg": 10,
|
||||||
|
"operators": {"massKg": "lte"}
|
||||||
|
},
|
||||||
|
"partRequirements": [
|
||||||
|
{"category": "TORSO_0", "material": "铝合金"},
|
||||||
|
{"category": "ARM_R", "torqueNm": 20, "operators": {"torqueNm": "gte"}}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.2 顶层入参
|
||||||
|
|
||||||
|
| 字段 | 类型 | 必填 | 说明 |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| `userInput` | string | 否 | 最多 4000 字符,仅作上下文;后端不解析、不存储,也不覆盖结构化条件 |
|
||||||
|
| `requirements` | string[] | 否 | 最多 32 个关键词,每个非空且最多 128 字符;省略/null 表示无关键词要求 |
|
||||||
|
| `requiredParts` | string[] | 是 | 非空,最多 24 项;中英文别名归一化后去重,组件类型去重但支持同类型多个实例;未列出躯干时自动补入唯一 `TORSO_0` |
|
||||||
|
| `robotRequirements` | object | 否 | 整机条件,字段见下表 |
|
||||||
|
| `partRequirements` | object[] | 否 | 最多 16 项;每项对应一个角色的条件,字段见下表 |
|
||||||
|
|
||||||
|
`userInput` 中写出的条件不会自动生效,前端必须同时提供相应结构化字段。例如“质量不超过 10kg”需要传 `massKg: 10` 和 `operators.massKg: "lte"`。
|
||||||
|
|
||||||
|
### 3.3 整机条件 `robotRequirements`
|
||||||
|
|
||||||
|
所有字段均可选。
|
||||||
|
|
||||||
|
| 字段 | 类型 | 说明 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `degreesOfFreedom` | integer | 标称总自由度,非负整数 |
|
||||||
|
| `massKg` | number | 整机质量目标,单位 kg,非负 |
|
||||||
|
| `functionDescription` | string | 整机功能要求,最多 512 字符,例如“跑步” |
|
||||||
|
| `operators` | object | 数值比较方式,只支持已提供的 `degreesOfFreedom`、`massKg` |
|
||||||
|
|
||||||
|
### 3.4 部件条件 `partRequirements[]`
|
||||||
|
|
||||||
|
| 字段 | 类型 | 必填 | 说明 |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| `category` | string | 是 | 组件角色,必须包含在 `requiredParts` 中(躯干固定补入);同一角色不能重复定义条件 |
|
||||||
|
| `componentName` | string | 否 | 组件名称,最多 128 字符;按名称及配置同义词匹配 |
|
||||||
|
| `description` | string | 否 | 描述关键词,最多 20000 字符;仅表示文本相关性 |
|
||||||
|
| `quantity` | integer | 否 | 1–24;仅接受JSON整数,省略/null表示按可匹配接口填充。躯干固定一个 |
|
||||||
|
| `material` | string | 否 | 材质,最多 128 字符,例如“铝合金” |
|
||||||
|
| `degreesOfFreedom` | integer | 否 | 该部件自由度,非负整数 |
|
||||||
|
| `massKg` | number | 否 | 该部件质量目标,单位 kg,非负 |
|
||||||
|
| `torqueNm` | number | 否 | 该部件扭矩目标,单位 N·m,非负 |
|
||||||
|
| `functionDescription` | string | 否 | 功能要求,最多 512 字符 |
|
||||||
|
| `shape` | string | 否 | 形状要求,最多 128 字符 |
|
||||||
|
| `size` | string | 否 | 大小描述要求,最多 128 字符,例如“中型”;不是数值尺寸比较 |
|
||||||
|
| `operators` | object | 否 | 数值比较方式,只支持已提供的 `degreesOfFreedom`、`massKg`、`torqueNm` |
|
||||||
|
|
||||||
|
### 3.5 数值、空值与运算符
|
||||||
|
|
||||||
|
可选条件省略或传 null 表示不约束该字段。字符串裁剪首尾空白,空字符串也表示不约束。显式传 `0` 表示要求数值为 0,与不传条件不同。
|
||||||
|
|
||||||
|
自由度只接受 0 至 2147483647 的 JSON 整数;`1.0`、`"1"`、布尔值和越界值均不合法。质量与扭矩使用 JSON 数值,最多 12 位整数、6 位小数。
|
||||||
|
|
||||||
|
| 运算符 | 含义 | 示例 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `eq` | 等于,省略时的默认值 | `degreesOfFreedom: 20` 表示总自由度等于 20 |
|
||||||
|
| `gte` | 大于或等于 | `torqueNm: 20` 配合 `operators.torqueNm: "gte"` 表示至少 20 N·m |
|
||||||
|
| `lte` | 小于或等于 | `massKg: 10` 配合 `operators.massKg: "lte"` 表示不超过 10 kg |
|
||||||
|
|
||||||
|
`operators` 不能对应未提供目标值的字段,也不能用于文本字段。未知请求字段、非法角色、重复部件条件、负数和非法运算符均返回 HTTP 422。
|
||||||
|
|
||||||
|
材质按同义词归一化后的等值匹配;功能、形状、大小按文本包含关系匹配。这些条件都可能因找不到合适组件而放宽,实际差异见 `unmetRequirements`。
|
||||||
|
|
||||||
|
### 3.6 角色映射
|
||||||
|
|
||||||
|
| 中文类型 | 标准编码 |
|
||||||
|
| --- | --- |
|
||||||
|
| 躯干_0 | TORSO_0 |
|
||||||
|
| 头_0 | HEAD_0 |
|
||||||
|
| 腰_0 | WAIST_0 |
|
||||||
|
| 左臂 | ARM_L |
|
||||||
|
| 右臂 | ARM_R |
|
||||||
|
| 不分左右的臂 | ARM_0 |
|
||||||
|
| 左手 | HAND_L |
|
||||||
|
| 右手 | HAND_R |
|
||||||
|
| 不分左右的手 | HAND_0 |
|
||||||
|
| 左足(腿部) | LEG_L |
|
||||||
|
| 右足(腿部) | LEG_R |
|
||||||
|
| 不分左右的足(腿部) | LEG_0 |
|
||||||
|
| 左脚 | FOOT_L |
|
||||||
|
| 右脚 | FOOT_R |
|
||||||
|
| 不分左右的脚 | FOOT_0 |
|
||||||
|
| 尾_0 | TAIL_0 |
|
||||||
|
|
||||||
|
以上16类为完整组件类型,公开响应统一使用大写标准编码。输入兼容英文大小写和原有中文别名;旧 `pedal_l/pedal_r` 兼容为 `LEG_L/LEG_R`。左右侧、足与脚独立;L/R 互不替代,同部位的 0 类组件可承担 L/R 装配角色。
|
||||||
|
|
||||||
|
ARM、HAND、LEG、FOOT 的父接口采用单向兼容:L 可接 L/0,R 可接 R/0,0 只接 0,L/R 不能互接。除原始 child 完全相等外,仅允许上述标准 `LINK_部位_L/R`(方向位也支持小写 l/r)连接同前缀的 `_0`;其余字符须区分大小写完全一致,不放宽自定义接口编码或跨部位连接。
|
||||||
|
|
||||||
|
组件库分类及 URDF `interfaceType` 均按上述类型识别,候选查询兼容已有大小写分类和旧足部编码;`interfaceType` 缺失时也可从 `LINK_LEG_L/LINK_LEG_R` 等 child 识别目标类型。原始 `urdfInfo` 保持不变,连接按上述单向规则判断。实例编码使用大写装配角色,例如 `LEG_L:1` 的真实组件类别可以是 `LEG_0`。
|
||||||
|
|
||||||
|
### 3.7 匹配结果的业务约定
|
||||||
|
|
||||||
|
先按角色查询未删除组件,再评价参数、材质和关键词。默认同义词包括跑步/奔跑/跑动/running、机器人/robot、双足/两足/biped/bipedal、六足/六足机器人/六腿/六条腿/hexapod/hexapod robot、铝合金/aluminum alloy/aluminium alloy。材质采用同义词归一化后的等值匹配,功能、形状和大小采用扩展后的包含匹配。名称、分类、功能、说明、材质、形状和大小参与关键词评价;例如“六足机器人”可以命中说明“六足蜘蛛机器人躯干”。
|
||||||
|
|
||||||
|
先选定需求评分最高的一个躯干:按躯干自身条件的未满足数量、数值差距、功能文本和关键词相关性评价。关键词先比较命中的不同需求数量,再比较字段权重,避免名称中的泛称“机器人”压过说明中的“六足”等具体要求;需求评分相同时优先所需接口覆盖,最后按编码稳定排序。整机自由度、质量总量在选定躯干后的组合中评价,不直接作为躯干单件目标。组合在既有完整性、参数和整体关键词评分相同后,继续比较各实例的关键词相关性,使带有六足说明的足部候选优先于无相关说明的同接口候选。
|
||||||
|
|
||||||
|
默认方案始终只有一个躯干且以 `TORSO_0` 为根,未列出躯干时自动补入。后续只沿这个躯干的接口路径匹配其他部件,在固定躯干下优先覆盖所需部件,再评价整机条件。选中的躯干不会因为另一个躯干能接更多部件而自动替换。在明确需求和组件齐全优先的前提下,ARM/HAND/LEG/FOOT 同族实例优先选择名称可识别的同型号组件,型号一致性优先于普通关键词相关性;用户明确指定的参数和型号仍优先。参数与材质可降级,角色和连接规则始终保持匹配;不自动加入其他未要求的中间连接件。
|
||||||
|
|
||||||
|
无法覆盖所有角色时返回躯干及可拼的连通部分;选中的躯干没有所需端口时可只返回躯干。没有可用躯干则返回 `NO_MATCH`,不会用其他角色作为根。躯干替代候选用于替换当前躯干,不追加第二个躯干。
|
||||||
|
|
||||||
|
整机自由度和质量按选中实例字段求和,同款组件的每个实例分别计入,**不重复累加BOM,不从URDF再次计算**。质量为0视为未填写;只要一个组件质量未知,`totals.massKg=null`、`massComplete=false`,已知部分保存在 `knownMassKg`。不能据此宣布满足质量上限。功能命中表示元数据相关,不代表动力学验证。
|
||||||
|
|
||||||
|
拼装候选必须同时有非空 STEP 和 URDF 主文件引用,仅上传 STEP 的组件仍只支持详情查询。接口以合法 interfaceType 决定目标 category,缺失/无效时从 child 的 LINK_ 后解析现有类别;双方 frames[].child 须非空并符合上述单向兼容规则,name 不参与判断。每个数组元素为独立接口,同child的多个接口不合并,连接双方各自只能占用一次。固定躯干后优先处理最近层级的接口,先满足所需类型和明确数量,再填充其余可匹配接口,不引入未要求的类型。自动增补不应破坏本可满足的硬要求;例如质量上限或指定总自由度会约束自动填充数量。坐标、安装基准、关节类型和rootLink不作为连接资格的阻塞条件,缺失接口则返回已有连通部分。
|
||||||
|
|
||||||
|
候选还必须处于启用状态(`status=ENABLED`);禁用组件不会进入新拼装方案或替代候选。禁用不影响用户端按编码查看组件详情、历史生成结果或已保存项目。生成结果加载阶段发现组件已禁用时,沿用 `409 / COMPONENT_REVISION_CONFLICT`,需要重新匹配。
|
||||||
|
|
||||||
|
`bomList` 和 `urdfInfo` 始终作为原始 JSON 返回,保留嵌套内容;详情里的 `urdfInfo` 也可能是其他对象或数组。接口匹配只评价元数据和连接类型,不验证机械承载或运动性能。
|
||||||
|
|
||||||
|
## 4. 匹配结果
|
||||||
|
|
||||||
|
响应新增 `missingPartGroups`,每项为 `{family, categories, reason, expectedQuantity, actualQuantity, missingQuantity}`。它用于 AI 默认人形的部位合计缺口,例如 ARM 组允许 `ARM_L/ARM_R/ARM_0`、期望2个、实际1个、缺少1个;具体类别缺口仍放 `missingParts`。任一类缺口存在时为 `PARTIAL`,没有组件仍为 `NO_MATCH`。直接结构化请求不启用模板分组,`missingPartGroups` 返回 `[]`,也不接受 `templatePartGroups` 入参。
|
||||||
|
|
||||||
|
### 4.1 `data` 字段
|
||||||
|
|
||||||
|
| 字段 | 类型 | 内容 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `status` | string | 匹配状态,见下表 |
|
||||||
|
| `rootCategory` | string / null | 有结果时固定为 `TORSO_0`;无结果时为 null |
|
||||||
|
| `parts` | object[] | 默认选中组件,字段见 4.2 |
|
||||||
|
| `connections` | object[] | 默认方案的整套父子连接,字段见 4.4 |
|
||||||
|
| `alternatives` | object[] | 每个已选角色一个分组,每组最多 5 个兼容替代组件,字段见 4.5 |
|
||||||
|
| `totals` | object | 默认方案的整机汇总,字段见 4.6 |
|
||||||
|
| `unmetRequirements` | object[] | 未满足的整机或部件条件,字段见 4.7 |
|
||||||
|
| `unmatchedKeywords` | string[] | 没有任何选中组件元数据命中的关键词 |
|
||||||
|
| `missingParts` | object[] | 未加入组合的角色和原因,字段见 4.7 |
|
||||||
|
| `missingPartGroups` | object[] | 后端模板部位合计缺口;直接结构化请求为 `[]` |
|
||||||
|
| `searchLimited` | boolean | 搜索是否达到候选/搜索限制;true 时仍可展示当前方案,但不代表已找到最优方案或证明组件库无解 |
|
||||||
|
|
||||||
|
| status | 含义 |
|
||||||
|
| --- | --- |
|
||||||
|
| `MATCHED` | 所需角色完整,所有提供条件和关键词均满足 |
|
||||||
|
| `FALLBACK` | 角色完整,部分条件或关键词不满足 |
|
||||||
|
| `PARTIAL` | 返回连通部分,存在缺失角色或模板部位合计数量不足;也可能有参数不满足 |
|
||||||
|
| `NO_MATCH` | 没有可用装配候选,parts和connections为空;HTTP仍为200 |
|
||||||
|
|
||||||
|
`searchLimited` 与 `status` 独立,例如 `MATCHED` 也可能同时返回 `searchLimited=true`。数组无内容时返回 `[]`。`parts` 的顺序不保证与请求一致,前端使用 `instanceId` 定位实例;`componentCode` 标识组件,`category` 是组件真实类别。
|
||||||
|
|
||||||
|
### 4.2 公开组件字段
|
||||||
|
|
||||||
|
`parts[]`、`alternatives[].items[].component` 和详情接口的 `data` 使用同一结构。
|
||||||
|
|
||||||
|
| 字段 | 类型 | 说明 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `componentCode` | string | 组件唯一编码,用于获取详情和区分组件 |
|
||||||
|
| `componentName` | string | 组件名称 |
|
||||||
|
| `category` | string | 组件真实类别,使用标准英文编码;可能与本次装配角色不同 |
|
||||||
|
| `description` | string | 组件说明 |
|
||||||
|
| `material` | string | 材质 |
|
||||||
|
| `massKg` | number | 组件质量,单位 kg;0 表示未填写 |
|
||||||
|
| `degreesOfFreedom` | integer | 组件标称自由度 |
|
||||||
|
| `rotationAxis` | string / null | 组件旋转轴,仅为 `X`、`Y`、`Z`;未设置时为 null,不替代 URDF 关节的 axis |
|
||||||
|
| `functionDescription` | string | 功能描述 |
|
||||||
|
| `shape` | string | 形状描述 |
|
||||||
|
| `size` | string | 大小描述 |
|
||||||
|
| `torqueNm` | number | 扭矩,单位 N·m |
|
||||||
|
| `bomList` | object / array | 原始 BOM JSON,内部结构由组件数据决定;允许 `{}`、`[]` 和嵌套内容 |
|
||||||
|
| `urdfInfo` | object / array | 原始 URDF 信息 JSON,保留完整 frames、axis、limits 等;匹配结果中为带 `rootLink`、`frames` 的对象 |
|
||||||
|
| `version` | integer | 组件数据版本号 |
|
||||||
|
| `stepUrl` | string | 公开 STEP 文件地址;没有文件时为空字符串 |
|
||||||
|
| `urdfUrl` | string | 公开 URDF 主文件地址;详情没有文件时为空字符串 |
|
||||||
|
|
||||||
|
两个 JSON 字段均直接作为对象或数组使用,无需再执行 `JSON.parse`。组件未填写的描述字段可能为空字符串。响应不包含数据库 ID、独立 OSS 对象键、目录前缀、内部文件清单或上传令牌。
|
||||||
|
|
||||||
|
### 4.3 完整成功响应示例
|
||||||
|
|
||||||
|
以下响应对应 3.1 的最小请求 `{"requiredParts":["TORSO_0","ARM_R"]}`,不是包含 11 个角色的整机请求。组件库提供了躯干、默认右臂和一个兼容的替代右臂。
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"code": "OK",
|
||||||
|
"message": "success",
|
||||||
|
"requestId": "example-request",
|
||||||
|
"data": {
|
||||||
|
"status": "MATCHED",
|
||||||
|
"rootCategory": "TORSO_0",
|
||||||
|
"parts": [
|
||||||
|
{
|
||||||
|
"componentCode": "CW-00000000000000000000000000000001",
|
||||||
|
"componentName": "铝合金躯干",
|
||||||
|
"category": "TORSO_0",
|
||||||
|
"description": "机器人躯干",
|
||||||
|
"material": "铝合金",
|
||||||
|
"massKg": 2,
|
||||||
|
"degreesOfFreedom": 0,
|
||||||
|
"rotationAxis": null,
|
||||||
|
"functionDescription": "支撑",
|
||||||
|
"shape": "宽躯干",
|
||||||
|
"size": "中型",
|
||||||
|
"torqueNm": 0,
|
||||||
|
"bomList": {
|
||||||
|
"items": [
|
||||||
|
{
|
||||||
|
"code": "BOLT-M4",
|
||||||
|
"quantity": 4
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"urdfInfo": {
|
||||||
|
"robotName": "torso",
|
||||||
|
"rootLink": "BASE",
|
||||||
|
"frames": [
|
||||||
|
{
|
||||||
|
"name": "J1",
|
||||||
|
"kind": "joint",
|
||||||
|
"type": "fixed",
|
||||||
|
"parent": "BASE",
|
||||||
|
"child": "LINK_arm_r",
|
||||||
|
"interfaceType": "ARM_R",
|
||||||
|
"originExplicit": true,
|
||||||
|
"xyz": [
|
||||||
|
-0.1,
|
||||||
|
0.01,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"rpy": [
|
||||||
|
0,
|
||||||
|
-1.5707963267949,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"axis": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"limits": {}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"version": 1,
|
||||||
|
"stepUrl": "https://models.example.com/cadworld/components/CW-00000000000000000000000000000001/step/batch/model.STEP",
|
||||||
|
"urdfUrl": "https://models.example.com/cadworld/components/CW-00000000000000000000000000000001/urdf/batch/robot.urdf",
|
||||||
|
"instanceId": "TORSO_0:1"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"componentCode": "CW-00000000000000000000000000000002",
|
||||||
|
"componentName": "右臂",
|
||||||
|
"category": "ARM_R",
|
||||||
|
"description": "机器人右臂",
|
||||||
|
"material": "铝合金",
|
||||||
|
"massKg": 1,
|
||||||
|
"degreesOfFreedom": 4,
|
||||||
|
"rotationAxis": null,
|
||||||
|
"functionDescription": "摆臂",
|
||||||
|
"shape": "",
|
||||||
|
"size": "",
|
||||||
|
"torqueNm": 20,
|
||||||
|
"bomList": [
|
||||||
|
{
|
||||||
|
"code": "ACTUATOR",
|
||||||
|
"quantity": 4
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"urdfInfo": {
|
||||||
|
"robotName": "arm",
|
||||||
|
"rootLink": "ARM_BASE",
|
||||||
|
"frames": [
|
||||||
|
{
|
||||||
|
"name": "INCOMING_arm_r",
|
||||||
|
"kind": "joint",
|
||||||
|
"type": "fixed",
|
||||||
|
"parent": "ARM_BASE",
|
||||||
|
"child": "LINK_arm_r",
|
||||||
|
"interfaceType": "ARM_R",
|
||||||
|
"xyz": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"rpy": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"version": 1,
|
||||||
|
"stepUrl": "https://models.example.com/cadworld/components/CW-00000000000000000000000000000002/step/batch/model.STEP",
|
||||||
|
"urdfUrl": "https://models.example.com/cadworld/components/CW-00000000000000000000000000000002/urdf/batch/robot.urdf",
|
||||||
|
"instanceId": "ARM_R:1"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"connections": [
|
||||||
|
{
|
||||||
|
"parentCategory": "TORSO_0",
|
||||||
|
"parentComponentCode": "CW-00000000000000000000000000000001",
|
||||||
|
"parentLink": "BASE",
|
||||||
|
"frameName": "J1",
|
||||||
|
"childCategory": "ARM_R",
|
||||||
|
"childComponentCode": "CW-00000000000000000000000000000002",
|
||||||
|
"childRootLink": "ARM_BASE",
|
||||||
|
"parentInstanceId": "TORSO_0:1",
|
||||||
|
"childInstanceId": "ARM_R:1",
|
||||||
|
"interfaceChild": "LINK_arm_r",
|
||||||
|
"parentFrameIndex": 0,
|
||||||
|
"childFrameIndex": 0
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"alternatives": [
|
||||||
|
{
|
||||||
|
"category": "TORSO_0",
|
||||||
|
"items": [],
|
||||||
|
"instanceId": "TORSO_0:1"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"category": "ARM_R",
|
||||||
|
"items": [
|
||||||
|
{
|
||||||
|
"component": {
|
||||||
|
"componentCode": "CW-00000000000000000000000000000003",
|
||||||
|
"componentName": "高扭矩右臂",
|
||||||
|
"category": "ARM_R",
|
||||||
|
"description": "机器人右臂",
|
||||||
|
"material": "铝合金",
|
||||||
|
"massKg": 1.2,
|
||||||
|
"degreesOfFreedom": 4,
|
||||||
|
"rotationAxis": null,
|
||||||
|
"functionDescription": "摆臂",
|
||||||
|
"shape": "",
|
||||||
|
"size": "",
|
||||||
|
"torqueNm": 25,
|
||||||
|
"bomList": [
|
||||||
|
{
|
||||||
|
"code": "ACTUATOR-25",
|
||||||
|
"quantity": 4,
|
||||||
|
"spec": {
|
||||||
|
"torqueNm": 25
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"urdfInfo": {
|
||||||
|
"robotName": "arm_v2",
|
||||||
|
"rootLink": "ARM_V2_BASE",
|
||||||
|
"frames": [
|
||||||
|
{
|
||||||
|
"name": "INCOMING_arm_r",
|
||||||
|
"kind": "joint",
|
||||||
|
"type": "fixed",
|
||||||
|
"parent": "ARM_V2_BASE",
|
||||||
|
"child": "LINK_arm_r",
|
||||||
|
"interfaceType": "ARM_R",
|
||||||
|
"xyz": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"rpy": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"version": 1,
|
||||||
|
"stepUrl": "https://models.example.com/cadworld/components/CW-00000000000000000000000000000003/step/batch/model.STEP",
|
||||||
|
"urdfUrl": "https://models.example.com/cadworld/components/CW-00000000000000000000000000000003/urdf/batch/robot.urdf",
|
||||||
|
"instanceId": "ARM_R:1"
|
||||||
|
},
|
||||||
|
"connections": [
|
||||||
|
{
|
||||||
|
"parentCategory": "TORSO_0",
|
||||||
|
"parentComponentCode": "CW-00000000000000000000000000000001",
|
||||||
|
"parentLink": "BASE",
|
||||||
|
"frameName": "J1",
|
||||||
|
"childCategory": "ARM_R",
|
||||||
|
"childComponentCode": "CW-00000000000000000000000000000003",
|
||||||
|
"childRootLink": "ARM_V2_BASE",
|
||||||
|
"parentInstanceId": "TORSO_0:1",
|
||||||
|
"childInstanceId": "ARM_R:1",
|
||||||
|
"interfaceChild": "LINK_arm_r",
|
||||||
|
"parentFrameIndex": 0,
|
||||||
|
"childFrameIndex": 0
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"totals": {
|
||||||
|
"degreesOfFreedom": 4,
|
||||||
|
"massKg": 3.2,
|
||||||
|
"knownMassKg": 3.2,
|
||||||
|
"massComplete": true
|
||||||
|
},
|
||||||
|
"unmetRequirements": [],
|
||||||
|
"unmatchedKeywords": []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"instanceId": "ARM_R:1"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"totals": {
|
||||||
|
"degreesOfFreedom": 4,
|
||||||
|
"massKg": 3,
|
||||||
|
"knownMassKg": 3,
|
||||||
|
"massComplete": true
|
||||||
|
},
|
||||||
|
"unmetRequirements": [],
|
||||||
|
"unmatchedKeywords": [],
|
||||||
|
"missingParts": [],
|
||||||
|
"searchLimited": false,
|
||||||
|
"missingPartGroups": []
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
同款组件可重复出现在 parts 中,新增的 instanceId 在结果内唯一,例如 ARM_R:1、ARM_R:2。单次最多24个实例;数量或搜索达到上限时 searchLimited=true,仍返回已有组合。missingParts 增加 expectedQuantity、actualQuantity 和 missingQuantity,明确数量未达到时返回缺少的数量。默认方案及替代项均按实例累计质量和自由度。
|
||||||
|
|
||||||
|
0 组件承担指定侧时,按该侧需求评价参数和数量,每个实例只归属一个装配角色;部位分组和整机汇总均只计一次。`parts[].category` 和替代组件的 `category` 始终返回真实类别。候选继续按现有评分和编码排序,不额外优先同侧或中性组件。
|
||||||
|
|
||||||
|
### 4.4 连接字段 `connections[]`
|
||||||
|
|
||||||
|
| 字段 | 类型 | 说明 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `parentInstanceId` / `childInstanceId` | string | 连接双方实例标识,格式为 装配角色:序号,序号从1开始 |
|
||||||
|
| `parentCategory` / `childCategory` | string | 双方本次装配角色,可能与组件真实 category 不同 |
|
||||||
|
| `parentComponentCode` / `childComponentCode` | string | 双方组件编码,同款可以在多个实例重复使用 |
|
||||||
|
| `interfaceChild` | string | 父接口原始 frames[].child;子接口 child 可以是同部位的 0 |
|
||||||
|
| `parentFrameIndex` / `childFrameIndex` | integer | 双方各自原始 frames 数组的零起始下标 |
|
||||||
|
| `frameName` | string | 父接口原始 name,仅用于辅助定位 |
|
||||||
|
| `parentLink` / `childRootLink` | string | 原始模型信息,缺失时可为空 |
|
||||||
|
|
||||||
|
本接口只返回连接关系,已移除连接摆放用 xyz/rpy,不计算矩阵。前端以双方实例标识和 frame 下标读取原始 urdfInfo,自行决定模型位置;不能假设双方 child 相等。同一 child 的多个接口以数组下标区分,前端不能按 child 或 componentCode 去重。
|
||||||
|
|
||||||
|
### 4.5 替代候选 `alternatives[]`
|
||||||
|
|
||||||
|
| 字段 | 类型 | 说明 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `category` | string | 当前可替换实例的装配角色,替代组件真实类别可为同部位的 0 |
|
||||||
|
| `instanceId` | string | 当前可替换的单个实例 |
|
||||||
|
| `items` | object[] | 0 至 5 个兼容替代项,空数组表示没有提供替代组件 |
|
||||||
|
| `items[].component` | object | 替代组件的完整公开数据,包括 BOM 和 URDF 信息 |
|
||||||
|
| `items[].connections` | object[] | 替换后的**整套**连接,不只是该部件的局部连接 |
|
||||||
|
| `items[].totals` | object | 替换后的整机汇总 |
|
||||||
|
| `items[].unmetRequirements` | object[] | 替换后的未满足条件 |
|
||||||
|
| `items[].unmatchedKeywords` | string[] | 替换后的未命中关键词 |
|
||||||
|
|
||||||
|
替代组件兼容当前父组件和全部当前子组件,保持当前父子拓扑;仍可能不满足用户的材质、数值或文本要求。替换时重新匹配该实例关联的全部接口,双方 frame 下标或原始模型信息可能改变。
|
||||||
|
|
||||||
|
前端选择一个替代项后,应按 instanceId 替换 `parts` 中的单个实例,并整体采用该项的 `connections`、`totals`、`unmetRequirements` 和 `unmatchedKeywords`。上例替换右臂后,编码变为 `CW-00000000000000000000000000000003`,根 link 变为 `ARM_V2_BASE`,整机质量变为 3.2 kg。
|
||||||
|
|
||||||
|
替代项没有独立 `status`,可根据当前 `missingParts` 和替代项的未满足条件/关键词重新展示状态。这些替代项针对本次默认方案计算;多个角色的替代项不能直接任意组合。重新请求会生成新的默认方案,当前接口没有锁定已选编码或校验多部件替换的入参。
|
||||||
|
|
||||||
|
### 4.6 汇总 `totals`
|
||||||
|
|
||||||
|
| 字段 | 类型 | 说明 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `degreesOfFreedom` | integer | 所选组件标称自由度之和 |
|
||||||
|
| `massKg` | number / null | 全部已选组件质量已知时的总质量;有未知质量时为 null |
|
||||||
|
| `knownMassKg` | number | 仅已知质量部分的合计 |
|
||||||
|
| `massComplete` | boolean | 是否所有已选组件质量均已填写;无组件时为 false |
|
||||||
|
|
||||||
|
`PARTIAL` 的汇总只覆盖已返回的组件。`massComplete=true` 表示这些组件的质量已知,不表示所需角色齐全。不要把组件 `massKg=0` 或汇总 `massKg=null` 展示成真实的零质量。
|
||||||
|
|
||||||
|
### 4.7 未满足条件和缺件
|
||||||
|
|
||||||
|
`unmetRequirements[]` 字段:
|
||||||
|
|
||||||
|
| 字段 | 类型 | 说明 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `scope` | string | `PART` 表示部件条件,`ROBOT` 表示整机条件 |
|
||||||
|
| `category` | string / null | 部件标准角色;整机条件为 null |
|
||||||
|
| `field` | string | 未满足的请求字段,如 `torqueNm`、`massKg`、`material` |
|
||||||
|
| `operator` | string | 数值为 `eq/gte/lte`,材质为 `eq`,功能/形状/大小为 `contains` |
|
||||||
|
| `expected` | number / string | 用户要求的目标值 |
|
||||||
|
| `actual` | number / string / null | 实际值;未知质量或未命中的整机功能可为 null |
|
||||||
|
| `reason` | string | 原因,见下表 |
|
||||||
|
|
||||||
|
| `unmetRequirements.reason` | 展示含义 |
|
||||||
|
| --- | --- |
|
||||||
|
| `VALUE_MISMATCH` | 数值不满足目标 |
|
||||||
|
| `UNKNOWN_MASS` | 质量未填写,无法确认是否满足质量要求 |
|
||||||
|
| `NO_TEXT_MATCH` | 材质、功能、形状或大小未命中 |
|
||||||
|
|
||||||
|
`missingParts[]` 每项包含 `category`(缺失角色)和 `reason`(原因):
|
||||||
|
|
||||||
|
| `missingParts.reason` | 展示含义 |
|
||||||
|
| --- | --- |
|
||||||
|
| `NO_COMPONENT` | 组件库没有该角色的可用组件 |
|
||||||
|
| `INVALID_ASSEMBLY_METADATA` | 历史结果兼容原因;新流程不因位姿或安装基准缺失排除组件,缺少匹配接口使用 NO_COMPATIBLE_CONNECTION |
|
||||||
|
| `NO_TORSO` | 有该角色的可用候选,但没有可用躯干,不能形成整机方案 |
|
||||||
|
| `NO_COMPATIBLE_CONNECTION` | 有候选组件,但未找到与当前组合兼容的连接 |
|
||||||
|
| `SEARCH_LIMIT` | 达到搜索限制,本次未找到可加入的组件 |
|
||||||
|
|
||||||
|
### 4.8 降级示例:`FALLBACK`
|
||||||
|
|
||||||
|
请求要求能跑步、质量不超过 2 kg、右臂扭矩至少 30 N·m:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"requirements": ["跑步"],
|
||||||
|
"requiredParts": ["TORSO_0", "ARM_R"],
|
||||||
|
"robotRequirements": {
|
||||||
|
"massKg": 2,
|
||||||
|
"functionDescription": "跑步",
|
||||||
|
"operators": {"massKg": "lte"}
|
||||||
|
},
|
||||||
|
"partRequirements": [
|
||||||
|
{"category": "ARM_R", "torqueNm": 30, "operators": {"torqueNm": "gte"}}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
例如找到可拼装的完整组合,但合计 3.2 kg、右臂扭矩 25 N·m,且未命中跑步功能。HTTP 200、`code=OK`,下面仅展示 **`data` 的状态字段片段**;实际响应仍包含完整 `parts`、`connections` 和 `alternatives`:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"status": "FALLBACK",
|
||||||
|
"rootCategory": "TORSO_0",
|
||||||
|
"totals": {
|
||||||
|
"degreesOfFreedom": 4,
|
||||||
|
"massKg": 3.2,
|
||||||
|
"knownMassKg": 3.2,
|
||||||
|
"massComplete": true
|
||||||
|
},
|
||||||
|
"unmetRequirements": [
|
||||||
|
{
|
||||||
|
"scope": "PART",
|
||||||
|
"category": "ARM_R",
|
||||||
|
"field": "torqueNm",
|
||||||
|
"operator": "gte",
|
||||||
|
"expected": 30,
|
||||||
|
"actual": 25,
|
||||||
|
"reason": "VALUE_MISMATCH"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"scope": "ROBOT",
|
||||||
|
"category": null,
|
||||||
|
"field": "massKg",
|
||||||
|
"operator": "lte",
|
||||||
|
"expected": 2,
|
||||||
|
"actual": 3.2,
|
||||||
|
"reason": "VALUE_MISMATCH"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"scope": "ROBOT",
|
||||||
|
"category": null,
|
||||||
|
"field": "functionDescription",
|
||||||
|
"operator": "contains",
|
||||||
|
"expected": "跑步",
|
||||||
|
"actual": null,
|
||||||
|
"reason": "NO_TEXT_MATCH"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"unmatchedKeywords": [
|
||||||
|
"跑步"
|
||||||
|
],
|
||||||
|
"missingParts": [],
|
||||||
|
"searchLimited": false,
|
||||||
|
"missingPartGroups": []
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
前端可以展示模型,同时提示“已提供可拼装方案,部分要求未满足”,并列出质量、扭矩和功能差异。
|
||||||
|
|
||||||
|
### 4.9 缺件示例:`PARTIAL`
|
||||||
|
|
||||||
|
请求:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"requiredParts": ["TORSO_0", "HEAD_0", "ARM_R"]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
例如仅返回躯干和右臂的连通组合,组件库没有头部。HTTP 200、`code=OK`,以下为 **`data` 的状态字段片段**,实际响应的 `parts` 包含这两个组件:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"status": "PARTIAL",
|
||||||
|
"rootCategory": "TORSO_0",
|
||||||
|
"totals": {
|
||||||
|
"degreesOfFreedom": 4,
|
||||||
|
"massKg": 3,
|
||||||
|
"knownMassKg": 3,
|
||||||
|
"massComplete": true
|
||||||
|
},
|
||||||
|
"unmetRequirements": [],
|
||||||
|
"unmatchedKeywords": [],
|
||||||
|
"missingParts": [
|
||||||
|
{
|
||||||
|
"category": "HEAD_0",
|
||||||
|
"reason": "NO_COMPONENT",
|
||||||
|
"expectedQuantity": 1,
|
||||||
|
"actualQuantity": 0,
|
||||||
|
"missingQuantity": 1
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"searchLimited": false,
|
||||||
|
"missingPartGroups": []
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
前端展示已返回的组件,并提示缺失头部;不能把这份汇总作为完整整机数据。
|
||||||
|
|
||||||
|
### 4.10 无可用组件示例:`NO_MATCH`
|
||||||
|
|
||||||
|
请求:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"requirements": ["跑步"],
|
||||||
|
"requiredParts": ["TORSO_0", "ARM_R"]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
例如这两个角色都没有可用组件,返回 HTTP 200。**完整响应**:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"code": "OK",
|
||||||
|
"message": "success",
|
||||||
|
"requestId": "frontend-match-004",
|
||||||
|
"data": {
|
||||||
|
"status": "NO_MATCH",
|
||||||
|
"rootCategory": null,
|
||||||
|
"parts": [],
|
||||||
|
"connections": [],
|
||||||
|
"alternatives": [],
|
||||||
|
"totals": {
|
||||||
|
"degreesOfFreedom": 0,
|
||||||
|
"massKg": null,
|
||||||
|
"knownMassKg": 0,
|
||||||
|
"massComplete": false
|
||||||
|
},
|
||||||
|
"unmetRequirements": [],
|
||||||
|
"unmatchedKeywords": [
|
||||||
|
"跑步"
|
||||||
|
],
|
||||||
|
"missingParts": [
|
||||||
|
{
|
||||||
|
"category": "TORSO_0",
|
||||||
|
"reason": "NO_COMPONENT",
|
||||||
|
"expectedQuantity": 1,
|
||||||
|
"actualQuantity": 0,
|
||||||
|
"missingQuantity": 1
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"category": "ARM_R",
|
||||||
|
"reason": "NO_COMPONENT",
|
||||||
|
"expectedQuantity": 1,
|
||||||
|
"actualQuantity": 0,
|
||||||
|
"missingQuantity": 1
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"searchLimited": false,
|
||||||
|
"missingPartGroups": []
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
前端展示“暂无可拼装组件”,结合 `missingParts` 提示原因。数据库故障属于接口错误,会返回 HTTP 503,不会返回此状态。
|
||||||
|
|
||||||
|
## 5. 组件详情
|
||||||
|
|
||||||
|
`GET /api/components/{componentCode}`,无请求体。
|
||||||
|
|
||||||
|
| 路径参数 | 类型 | 必填 | 说明 |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| `componentCode` | string | 是 | 组件编码,非空且最多 64 字符;使用匹配结果中的编码 |
|
||||||
|
|
||||||
|
请求示例:
|
||||||
|
|
||||||
|
```http
|
||||||
|
GET /api/components/CW-00000000000000000000000000000001
|
||||||
|
X-Request-Id: frontend-detail-001
|
||||||
|
```
|
||||||
|
|
||||||
|
HTTP 200,完整响应示例:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"code": "OK",
|
||||||
|
"message": "success",
|
||||||
|
"requestId": "frontend-detail-001",
|
||||||
|
"data": {
|
||||||
|
"componentCode": "CW-00000000000000000000000000000001",
|
||||||
|
"componentName": "铝合金躯干",
|
||||||
|
"category": "TORSO_0",
|
||||||
|
"description": "机器人躯干",
|
||||||
|
"material": "铝合金",
|
||||||
|
"massKg": 2,
|
||||||
|
"degreesOfFreedom": 0,
|
||||||
|
"rotationAxis": null,
|
||||||
|
"functionDescription": "支撑",
|
||||||
|
"shape": "宽躯干",
|
||||||
|
"size": "中型",
|
||||||
|
"torqueNm": 0,
|
||||||
|
"bomList": {
|
||||||
|
"items": [{"code": "BOLT-M4", "quantity": 4}]
|
||||||
|
},
|
||||||
|
"urdfInfo": {
|
||||||
|
"robotName": "torso",
|
||||||
|
"rootLink": "BASE",
|
||||||
|
"frames": [
|
||||||
|
{
|
||||||
|
"name": "J1",
|
||||||
|
"kind": "joint",
|
||||||
|
"type": "fixed",
|
||||||
|
"parent": "BASE",
|
||||||
|
"child": "LINK_arm_r",
|
||||||
|
"interfaceType": "ARM_R",
|
||||||
|
"originExplicit": true,
|
||||||
|
"xyz": [-0.1, 0.01, 0],
|
||||||
|
"rpy": [0, -1.5707963267949, 0],
|
||||||
|
"axis": [0, 0, 0],
|
||||||
|
"limits": {}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"version": 1,
|
||||||
|
"stepUrl": "https://models.example.com/cadworld/components/CW-00000000000000000000000000000001/step/batch/model.STEP",
|
||||||
|
"urdfUrl": "https://models.example.com/cadworld/components/CW-00000000000000000000000000000001/urdf/batch/robot.urdf"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
返回字段见 4.2。禁用组件仍可查询详情;详情可能返回不满足拼装要求的原始 `urdfInfo`,查看详情不表示该组件一定可以参与匹配。
|
||||||
|
|
||||||
|
## 6. 错误响应
|
||||||
|
|
||||||
|
| HTTP 状态 | `code` | 常见原因 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 422 | `INVALID_REQUEST` | 必填项缺失、JSON 类型错误、未知字段、超长文本、负数、自由度小数或数值越界 |
|
||||||
|
| 422 | `INVALID_MATCH_REQUEST` | 不支持的角色、部件条件不属于所需角色、重复角色条件、非法运算符 |
|
||||||
|
| 404 | `COMPONENT_NOT_FOUND` | 详情编码不存在或组件已删除 |
|
||||||
|
| 503 | `DATABASE_UNAVAILABLE` | 数据库暂不可用 |
|
||||||
|
| 500 | `INTERNAL_ERROR` | 服务内部异常 |
|
||||||
|
|
||||||
|
### 6.1 非法角色:HTTP 422
|
||||||
|
|
||||||
|
请求 `POST /api/robot-matches`:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"requiredParts": ["unknown_part"]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
响应:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"code": "INVALID_MATCH_REQUEST",
|
||||||
|
"message": "不支持的组件角色",
|
||||||
|
"data": null,
|
||||||
|
"requestId": "frontend-invalid-001"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6.2 自由度类型错误:HTTP 422
|
||||||
|
|
||||||
|
请求中的自由度使用了字符串:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"requiredParts": ["ARM_R"],
|
||||||
|
"robotRequirements": {"degreesOfFreedom": "20"}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
响应:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"code": "INVALID_REQUEST",
|
||||||
|
"message": "请求体格式不合法,请检查字段类型和JSON结构",
|
||||||
|
"data": null,
|
||||||
|
"requestId": "frontend-invalid-002"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6.3 组件不存在:HTTP 404
|
||||||
|
|
||||||
|
请求 `GET /api/components/CW-NOT-FOUND`,响应:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"code": "COMPONENT_NOT_FOUND",
|
||||||
|
"message": "组件不存在",
|
||||||
|
"data": null,
|
||||||
|
"requestId": "frontend-detail-002"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6.4 数据库不可用:HTTP 503
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"code": "DATABASE_UNAVAILABLE",
|
||||||
|
"message": "数据库暂不可用,请检查数据库连接配置后重试",
|
||||||
|
"data": null,
|
||||||
|
"requestId": "frontend-match-005"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
错误时按 HTTP 状态和 `code` 判断,`message` 用于提示,不作为固定业务分支条件。排查时提供 `requestId`。
|
||||||
|
|
||||||
|
## 7. 前端拼装与模型加载
|
||||||
|
|
||||||
|
1. 提交结构化匹配条件,读取 `data.status`;`FALLBACK`、`PARTIAL` 仍可以展示已有模型,同时展示未满足条件和缺件。
|
||||||
|
2. 使用 `parts[].urdfUrl` 加载 URDF,用 `parts[].instanceId` 区分模型实例,组件编码可重复;需要 STEP 文件时使用 `stepUrl`。空地址不发起文件请求。
|
||||||
|
3. 从 `rootCategory` 对应模型开始,按 `connections` 组装。按双方 instanceId 与 frame 下标读取各自原始接口数据,由前端决定摆放。不要假设连接数组已经按装配顺序排列。
|
||||||
|
4. BOM 展示读取 `bomList`;关节、轴、限位等读取原始 `urdfInfo` 或已加载模型。不要重复累加 BOM 的质量和自由度。
|
||||||
|
5. 选择替代组件后,按 4.5 同时更新组件、连接、汇总及未满足项。
|
||||||
|
|
||||||
|
模型资源由前端直接请求公开 OSS/CDN 地址,无需拼接 `/api/components/{componentCode}/assets/...` 路径,也不需要给模型地址附加管理员凭证。资源域名需允许前端源跨域读取 URDF 及 meshes,联调时由部署人员配置 OSS/CDN 的 GET/HEAD CORS。
|
||||||
|
|
||||||
|
URDF 相对 mesh 路径以主文件目录解析,保留服务器返回的完整目录。若文件使用 `package://`,前端 URDF 加载器需要配置对应 package 路径映射。STEP 格式解析和模型展示由前端加载器负责。
|
||||||
|
|
||||||
|
组件资源替换后应使用最新响应中的 URL。组件已删除时详情返回 404,但已有公开资源地址不保证立即失效;不要仅凭模型地址可访问就判断组件仍可使用。
|
||||||
@@ -0,0 +1,147 @@
|
|||||||
|
# 邮箱与图片验证码登录
|
||||||
|
|
||||||
|
用户端默认端口 `8991`。除 `GET /api/auth/captcha`、`POST /api/auth/login` 和跨域预检外,所有 `/api/**` 业务接口都需要 `Authorization: Bearer <token>`,包括组件详情、匹配、需求会话、私有图片和 SSE。JSON 返回统一为 `{code, message, data, requestId}`。
|
||||||
|
|
||||||
|
此流程沿用参考项目:邮箱与图片验证码登录,首次自动注册;不发送邮件、不验证邮箱归属。`user_type` 不作为客户端可提交字段。用户端仅返回唯一 `userCode`,不暴露数据库主键。
|
||||||
|
|
||||||
|
## 1. 接口
|
||||||
|
|
||||||
|
### 获取验证码
|
||||||
|
|
||||||
|
`GET /api/auth/captcha`,无需登录,响应设置 `Cache-Control: no-store`。
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"code": "OK",
|
||||||
|
"message": "success",
|
||||||
|
"data": {
|
||||||
|
"captchaCode": "一次性验证码编码",
|
||||||
|
"image": "data:image/png;base64,...",
|
||||||
|
"expiresIn": 120
|
||||||
|
},
|
||||||
|
"requestId": "请求编号"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
图片为 180×60 PNG,包含 5 位数字或大写字母。`image` 可直接作为验证码图片的 `src`。有效期默认 120 秒,答案忽略大小写和首尾空格。每次有效参数的登录提交都会消费对应验证码,答错后也必须重新获取。
|
||||||
|
|
||||||
|
### 登录
|
||||||
|
|
||||||
|
`POST /api/auth/login`,`Content-Type: application/json`,无需登录。
|
||||||
|
|
||||||
|
```json
|
||||||
|
{"email":"user@example.com","captchaCode":"验证码编码","captchaAnswer":"ABCDE"}
|
||||||
|
```
|
||||||
|
|
||||||
|
邮箱去除首尾空格、转小写后校验,最长 254 字符;验证码编码和答案必填,最长分别为 64、32 字符。成功示例:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"code": "OK",
|
||||||
|
"message": "success",
|
||||||
|
"data": {
|
||||||
|
"token": "登录凭证",
|
||||||
|
"tokenType": "Bearer",
|
||||||
|
"expiresIn": 86400,
|
||||||
|
"user": {
|
||||||
|
"userCode": "0123456789ABCDEF0123456789ABCDEF",
|
||||||
|
"nickname": "用户_01234567",
|
||||||
|
"email": "user@example.com"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"requestId": "请求编号"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
首次登录创建 `ACTIVE / NORMAL` 用户,昵称为“用户_用户编码前8位”。同邮箱并发首次登录复用同一用户。用户编码创建后不可修改。
|
||||||
|
|
||||||
|
Token 是 32 字节安全随机值的无填充 Base64URL 编码,有效期默认 24 小时;访问不续期。同一用户可持有多个 Token。
|
||||||
|
|
||||||
|
### 当前用户与退出
|
||||||
|
|
||||||
|
- `GET /api/users/me`:返回 `data={userCode,nickname,email}`。
|
||||||
|
- `POST /api/auth/logout`:撤销当前 Token,返回 `data=null`,其他登录态继续有效。再次使用已撤销 Token 返回 401。
|
||||||
|
|
||||||
|
以上接口均须携带 Bearer Token。用户被后台禁用后,登录返回 403,已有 Token 在下一次业务请求时被拒绝。
|
||||||
|
|
||||||
|
| HTTP 状态 | code | 处理方式 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 400 | `CAPTCHA_INVALID` | 验证码错误、过期或已消费,重新获取图片 |
|
||||||
|
| 401 | `UNAUTHORIZED` | 未登录、Token 无效或账号已不可用,重新登录 |
|
||||||
|
| 403 | `ACCOUNT_DISABLED` | 用户已禁用,联系管理员 |
|
||||||
|
| 422 | `INVALID_REQUEST` | 检查邮箱、必填字段、长度或未知字段 |
|
||||||
|
| 503 | `DATABASE_UNAVAILABLE` | 数据库暂不可用,稍后重试 |
|
||||||
|
| 503 | `USER_CODE_EXHAUSTED` | 用户编码分配重试失败,稍后重试 |
|
||||||
|
|
||||||
|
## 2. 前端调用与需求归属
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
const challenge = (await (await fetch('/api/auth/captcha')).json()).data;
|
||||||
|
// 将 challenge.image 展示给用户,answer 为用户输入的图片答案。
|
||||||
|
const response = await fetch('/api/auth/login', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ email, captchaCode: challenge.captchaCode, captchaAnswer: answer })
|
||||||
|
});
|
||||||
|
if (!response.ok) throw await response.json();
|
||||||
|
const { token } = (await response.json()).data;
|
||||||
|
|
||||||
|
const current = await fetch('/api/users/me', {
|
||||||
|
headers: { Authorization: `Bearer ${token}` }
|
||||||
|
});
|
||||||
|
|
||||||
|
// 私有图片需要认证头,通过 Blob URL 展示,Token 不放在 URL 中。
|
||||||
|
const imageResponse = await fetch(previewUrl, {
|
||||||
|
headers: { Authorization: `Bearer ${token}` }
|
||||||
|
});
|
||||||
|
if (!imageResponse.ok) throw await imageResponse.json();
|
||||||
|
const objectUrl = URL.createObjectURL(await imageResponse.blob());
|
||||||
|
imageElement.src = objectUrl;
|
||||||
|
// 图片不再使用时执行 URL.revokeObjectURL(objectUrl)。
|
||||||
|
```
|
||||||
|
|
||||||
|
POST SSE 同样在 fetch 的 headers 中携带 `Authorization`,详见 [需求联调文档](robot-demand-api.md)。不再需要访客 Cookie 或 `credentials: 'include'`。
|
||||||
|
|
||||||
|
会话归属由服务端认证的 `userCode` 决定,存储为 `SHA-256("user:" + userCode)`。同一用户在不同设备登录后可通过原业务编码访问自己的会话;其他用户访问返回 404。客户端不传 `userId`、`userCode` 或归属摘要来指定所有者。
|
||||||
|
|
||||||
|
历史匿名 Cookie 不授予访问权,也不会触发会话认领。历史匿名数据保留至现有过期任务清理。
|
||||||
|
|
||||||
|
## 3. 配置与运行
|
||||||
|
|
||||||
|
| 环境变量 | 默认值 | 说明 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `APP_AUTH_CAPTCHA_TTL` | `PT2M` | 验证码有效期,至少 1 秒 |
|
||||||
|
| `APP_AUTH_TOKEN_TTL` | `PT24H` | 登录态有效期,至少 1 秒 |
|
||||||
|
| `APP_DEMAND_ALLOWED_ORIGINS` | 沿用各环境配置 | `/api/**` 跨域白名单,允许 Authorization 请求头 |
|
||||||
|
|
||||||
|
验证码和登录态分别使用最多 10000 条的 Caffeine 缓存。当前按单实例部署;重启、缓存容量淘汰或有效期结束后凭证失效。用户和会话数据持久化保留;多实例共享登录态需后续切换为共享存储。
|
||||||
|
|
||||||
|
用户端和[管理端](../../cadworld-adminapi/docs/auth-api.md)分别引入自己的安全模块,独立保存 Token 和验证码。后台用户管理使用邮箱,删除入口改为禁用账号;上传与审计使用真实登录管理员。
|
||||||
|
|
||||||
|
## 4. 发布前手动执行的迁移 SQL
|
||||||
|
|
||||||
|
以下 SQL 基于提供的邮箱版 `sys_user`(索引名 `uk_sys_user_phone`,索引列为 `email`),仅执行一次;已有该字段或索引的环境先核对结构。应用不自动迁移,仓库 `.sql` 文件未修改。先执行 SQL,再发布用户端和管理端新代码。
|
||||||
|
|
||||||
|
```sql
|
||||||
|
ALTER TABLE `sys_user`
|
||||||
|
ADD COLUMN `user_code` char(32)
|
||||||
|
CHARACTER SET ascii COLLATE ascii_bin
|
||||||
|
NULL COMMENT '用户唯一编码,对外使用且创建后不可修改'
|
||||||
|
AFTER `id`;
|
||||||
|
|
||||||
|
UPDATE `sys_user`
|
||||||
|
SET `user_code` = UPPER(REPLACE(UUID(), '-', ''))
|
||||||
|
WHERE `user_code` IS NULL;
|
||||||
|
|
||||||
|
ALTER TABLE `sys_user`
|
||||||
|
MODIFY COLUMN `user_code` char(32)
|
||||||
|
CHARACTER SET ascii COLLATE ascii_bin
|
||||||
|
NOT NULL COMMENT '用户唯一编码,对外使用且创建后不可修改',
|
||||||
|
ADD UNIQUE KEY `uk_sys_user_code` (`user_code`),
|
||||||
|
RENAME INDEX `uk_sys_user_phone` TO `uk_sys_user_email`;
|
||||||
|
|
||||||
|
ALTER TABLE `robot_demand_conversation`
|
||||||
|
MODIFY COLUMN `owner_hash` char(64)
|
||||||
|
CHARACTER SET ascii COLLATE ascii_bin
|
||||||
|
NOT NULL COMMENT '登录用户归属摘要,历史匿名归属保留至过期';
|
||||||
|
```
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
# 需求解析后端接入与部署
|
||||||
|
|
||||||
|
已按 `/Users/edy/Downloads/robot-demand-parser-v1` 的 README、backend-handoff、protocol,以及 `index.mjs` / `mechanical-rules.mjs` 移植 Java 程序校验。自动拼装输出版本为 `multimodal-v1.6-component-replacement`,目录版本为 `2026-10-27-hexapod-connectors`。原始来源作为参考保留,当前提示词与 Java 规则已调整为无追问的自动生成流程。来源文件夹保持不变,运行时不依赖 Node、React 或前端解析脚本。
|
||||||
|
|
||||||
|
业务标准化另外落实躯干优先规则:整机必须且只能有一个躯干,解析时可自动补入基础躯干;明确排除躯干时保留排除项并返回无匹配方案,不追问或偷偷补入。匹配先固定最符合需求的躯干,再搜索与其连通的其他组件。
|
||||||
|
|
||||||
|
前端完整调用说明与示例见 [robot-demand-api.md](robot-demand-api.md)。下面说明部署条件和后端边界。
|
||||||
|
|
||||||
|
## 启动条件
|
||||||
|
|
||||||
|
1. 使用已有 `component` 表,部署前按 [管理端旋转轴字段部署说明](../../cadworld-adminapi/docs/admin-api.md#43-旋转轴字段部署) 添加 `rotation_axis`。在用户端服务使用的数据库中执行 [demand-schema.md](demand-schema.md) 的五张表建表语句。代码不自动建表或迁移,不修改或执行仓库 `.sql` 文件。
|
||||||
|
2. 配置 MySQL、公开模型域名与 `ARK_API_KEY`。Key 仅提供给后端,缺失时其他组件接口仍可使用,需求解析返回不可用状态。
|
||||||
|
3. 为需求图片配置私有可写的持久化目录;不能映射为静态资源或挂载到公开模型目录。
|
||||||
|
4. 前端通过同站点 HTTPS 代理 `/api`;开发跨端口时配置具体前端 origin。先完成[邮箱登录及用户编码迁移](auth-api.md),全部业务请求携带 Bearer Token。
|
||||||
|
5. 对接组件实际接口:interfaceType 优先确定现有 category,双方 frames[].child 非空并按单向兼容规则连接(同部位父 L/R 可接同侧或 0,父 0 只接 0);每个 frames 元素是独立接口。无需填写 urdfInfo.assembly,模型摆放由前端处理。
|
||||||
|
|
||||||
|
```bash
|
||||||
|
mvn -pl cadworld-api,cadworld-adminapi -am test
|
||||||
|
mvn -pl cadworld-api,cadworld-adminapi -am -DskipTests package
|
||||||
|
java -jar cadworld-api/target/cadworld-api-0.0.1-SNAPSHOT.jar
|
||||||
|
```
|
||||||
|
|
||||||
|
默认端口 `8991`、profile `test`;生产指定 `SPRING_PROFILES_ACTIVE=prod`。Spring Boot 不自动加载 `.env`,由启动环境注入变量。此服务不需要管理员身份、上传签名密钥或 OSS AccessKey。
|
||||||
|
|
||||||
|
| 环境变量 | 默认 / 说明 |
|
||||||
|
| --- | --- |
|
||||||
|
| `APP_DB_URL` / `APP_DB_USERNAME` / `APP_DB_PASSWORD` | 生产必填,MySQL 连接 |
|
||||||
|
| `APP_STORAGE_PUBLIC_BASE_URL` | 生产必填,公开 OSS/CDN 域名,不能填管理端代理 |
|
||||||
|
| `OSS_ROOT_PREFIX` | 测试默认 `cadworld_dev`,生产默认 `cadworld` |
|
||||||
|
| `ARK_API_KEY` | 无默认,仅后端环境变量或密钥服务提供 |
|
||||||
|
| `ARK_MODEL` | `doubao-seed-2-1-lite-260915`,可替换为账号开通的多模态结构化输出模型 |
|
||||||
|
| `ARK_ENDPOINT` | `https://ark.cn-beijing.volces.com/api/v3/responses` |
|
||||||
|
| `APP_DEMAND_TIMEOUT` | `PT3M`,允许 1 秒至 5 分钟 |
|
||||||
|
| `APP_DEMAND_ATTACHMENT_DIRECTORY` | `data/demand-attachments`,私有附件目录 |
|
||||||
|
| `APP_DEMAND_RETENTION` | `P7D`,允许 1 小时至 30 天 |
|
||||||
|
| `APP_DEMAND_CONCURRENT_ANALYSES` | `4`,允许 1–16;当前进程并发上限,无等待队列 |
|
||||||
|
| `APP_DEMAND_ALLOWED_ORIGINS` | `/api/**` 跨域白名单;`test` 默认 `https://dev-cadworld.robotquan.com`,`prod` 默认 `https://cadworld.robotquan.com`;可用逗号分隔的完整 origin 覆盖,显式留空关闭跨域,禁止通配符 |
|
||||||
|
|
||||||
|
用户端跨域支持凭证,允许 `GET / POST / DELETE / OPTIONS`,请求头允许 `Content-Type / X-Request-Id / Authorization`,向前端暴露 `X-Request-Id`,预检缓存 3600 秒。浏览器统一发送 `Authorization: Bearer <token>`,不再依赖匿名 Cookie。公开 OSS/CDN 资源的跨域需在对应资源服务单独配置。
|
||||||
|
|
||||||
|
模型调用使用严格 JSON Schema、深度思考、`stream:false`、`store:false`,不启用联网工具。SSE 为后端阶段和已校验业务结果,不透传模型推理内容。接收上游响应最多 2MiB,提取的中间 JSON 最多 150000 字符。
|
||||||
|
|
||||||
|
原始提示词、模型中间 Schema、类别目录放在 `cadworld-service/src/main/resources/robot-demand/`,不作为公开静态资源。Schema 拒绝缺少字段、未知字段、非法枚举、超长值和无效证据编号。来源文字必须是所属用户消息的原文子串;历史助手消息不能作为用户数值证据。每张上传图片都需出现在模型图片分析中,图片与观察归属需一致。
|
||||||
|
|
||||||
|
## 持久化与运行方式
|
||||||
|
|
||||||
|
五张表分别保存会话归属和版本、私有附件元信息、服务端历史、完整解析结果、自动生成的匹配快照。对外均使用编码;会话归属使用服务端认证主体的 `SHA-256("user:" + userCode)`,不信任客户端 `userId` 或用户编码。历史匿名会话不认领,保留至过期任务清理。
|
||||||
|
|
||||||
|
新用户消息在事务中锁定会话、递增版本并使旧方案失效;相同消息编号和内容不重复创建版本、调用模型或选件。消息任务在需求规范化后立即执行自动选件和装配校验,需求结果与匹配快照在同一事务内提交,随后才发布 `ready` 和 `analysis.completed`;完成事件及 GET 查询同时返回公开的 `match`,内部 `snapshot` 始终移除。选件在会话锁外执行,提交时再次核对版本和取消状态,防止旧任务覆盖新方案。新流程不写入助手追问。
|
||||||
|
|
||||||
|
对话拼装仅保留 7 个接口:创建会话、上传图片、预览图片、发送消息、查询任务、重试和停止。确认、重新匹配、按匹配编码查询和接受降级接口及相关 DTO/业务实现已删除,旧路径返回 404。结果统一由消息完成事件和任务查询返回;调整需求或刷新组件库结果时,发送新的用户消息,重新调用模型并生成新方案。重发相同消息编号只恢复原任务或原结果。
|
||||||
|
|
||||||
|
当前解析执行器与 SSE 订阅在进程内,建议单实例部署;多实例须共享数据库和私有文件卷,并按会话路由到同一实例。此版本未实现分布式任务租约或跨实例取消通知。进程重启后的 processing 记录会在超时后标为失败,当前版本可重试,不会将未完成结果视为可装配。SSE 意外断开只移除订阅,任务仍继续执行,前端可查询或重新订阅同一消息恢复;显式 DELETE、超时和新版本才停止任务。模型调用受解析超时限制,整个生成任务的截止时间为该超时加 30 秒。
|
||||||
|
|
||||||
|
上传附件只接受本服务生成的编码,不支持客户端任意路径、URL 或预签名外链。默认每小时清理至多 100 个过期会话及其私有图片、消息、解析、匹配;删除失败保留元信息,下轮重试。会话访问过期即返回 404,不等待清理任务。上传到会话而未发送的附件同样随会话过期清理。组件公开 OSS 资源不受此任务影响。
|
||||||
|
|
||||||
|
网关应允许 8MiB 文件上传、POST SSE 和至少 210 秒的请求等待时间(默认解析超时 180 秒加 30 秒)。关闭 SSE 缓冲。所有需求相关运行日志只记录请求编号、业务编码、版本、数量、状态、错误码和耗时,不记录完整输入、图片、BOM/URDF JSON、模型 Key。
|
||||||
|
|
||||||
|
## 需求与匹配判定
|
||||||
|
|
||||||
|
规范化五字段 request 继续兼容原结构化匹配,自动生成使用完整 analysis。详细 `intentItems` 保留 `must/prefer/context`、证据和来源。硬要求优先排序,偏好在硬要求之后评价;不能映射为登记字段或缺少能力证据的硬要求返回 `unverified`。功能文本相关性不证明跑步、巡检、飞行、续航等物理能力。
|
||||||
|
|
||||||
|
数值约束统一到 kg、N·m,支持明确单位换算与中文数字;自由度必须是 int32 非负整数,质量和扭矩遵循 decimal(18,6)。单位缺失、范围无法表示、相互冲突、对象不清楚等保留原要求和未验证说明,不用于硬条件筛选、不阻塞生成,也不自动选一个值或默认单位。`lt/gt/neq` 与非退化双边范围当前不投影为 `eq/gte/lte`。未指定属性不会填 0。未指定可匹配类型或部位时,按 `part-catalog.json` 的 `defaultTemplate=biped` 生成参考方案并说明;可识别的图片或部位推断可用于选件,但不升级为硬数值或已验证能力。图片视觉推断、模糊信息和反例不能投影成硬数值条件。
|
||||||
|
|
||||||
|
组件组合仍为 MySQL + 同义词词典 + Java 有界搜索。候选查询只扫描同时具有非空 `step_object_key` 和 `urdf_main_object_key` 的组件,只有 STEP 的组件不参与默认方案或替代候选;新增时可先仅上传 STEP,再通过管理端修改补齐 URDF 和元数据。先按躯干单件硬要求、数值差距、偏好及功能/关键词相关性固定唯一躯干;评分相同后比较所需接口覆盖及编码。整机自由度和质量在后续组合求和评价。固定躯干后优先覆盖所需角色;在同等覆盖下,硬要求差距优先于偏好。先搜索其他部件硬条件满足的候选,再提供明确说明的降级结果,两轮共用同一个躯干;不以整机总量或覆盖率更换根。
|
||||||
|
|
||||||
|
没有可用躯干时返回无匹配结果,不再尝试其他角色为根。同一组件编码可生成多个独立实例,躯干仍固定一个,中英文类别别名先归一化。除作为基础部件自动补入的躯干外,不补入其他未要求的中间连接件;明确部位数量投影到 partRequirements.quantity(1–24);省略时先覆盖所需类型,再填充其可匹配剩余接口。实例标识、接口占用、替代和参数汇总均以实例为单位,不能按类别或组件编码去重。组件类型仍为16类,新增 hexapod 六足模板,未配置的其他形态继续保留差异。躯干替代项只用于替换当前唯一躯干。
|
||||||
|
|
||||||
|
`complete/partial/no_match` 描述需求匹配,`assembly.ready/blocked` 只描述是否有可展示组合和已生成的逻辑连接关系。缺件通过 `missingParts` 和 `partial` 提示,不进入 `assembly.issues`;缺件、性能不足或未验证能力不要求先接受降级,`degradationAcceptanceRequired` 固定为 false,因此 `partial` 可同时返回 `assembly.ready` 并直接显示已有有效组合。只有没有可用躯干/组件时才没有可展示组合;安装基准、位姿、活动关节和资源清单问题只返回提示,不阻塞已有组合。仅有有效躯干时可以显示躯干,连接数组为空。
|
||||||
|
|
||||||
|
默认组合和替代候选使用相同装配判定。兼容响应中的降级接受标记保留为 false,不提供单独接受流程;缺件、未验证能力和机械/资源问题继续保留。新生成结果不再保存只供接受流程使用的内部 `snapshot`,查询历史数据时仍移除旧快照。升级规则或组件库更新后,发送新消息生成新版本;原消息重放和状态查询不会重算。替代项仍是相对当前服务端方案的一次替换预览,不能直接叠加任意前端候选。消息流程支持基于历史成功快照进行多目标联合替换,任一失败则保留原组合和有效需求并保存新版本;`match.change` 返回 applied/unchanged 及原因,详见接口文档的“对话局部替换”。默认选件和替代排序新增同型号软偏好,优先于普通关键词但不覆盖明确需求。新解析协议为 `multimodal-v1.6-component-replacement`;不改表,旧快照不回填。
|
||||||
|
|
||||||
|
## 接口数据与实例
|
||||||
|
|
||||||
|
组件类型扩展为16类,新增 ARM_0/HAND_0/LEG_0/FOOT_0。默认人形使用臂、手、足、脚四组各至少两个实例的要求,根据实际接口选择 L/R/0。明确六足需求使用 hexapod 模板,只要求躯干及 LEG/FOOT 各至少六个实例,不沿用人形部位要求。接口以合法 interfaceType 确定要查找的 category,缺失或无效时从 child 的 LINK_ 后解析已有类型编码/别名;无法确定类型时不从此接口向外扩展。装配角色必须属于需求;L/R 角色的候选扫描同时纳入同部位的 0 类组件,并按该侧需求评价条件、数量。child 完全相等时继续可连接;新增兼容只允许 ARM/HAND/LEG/FOOT 标准 LINK 编码末尾方向位 L/R(含小写 l/r)连接 0,其余字符保持区分大小写一致。frame 的 name、kind、type、坐标和安装基准不参与连接资格判断。
|
||||||
|
|
||||||
|
四类部位统一按父到子方向处理:L 接 L/0,R 接 R/0,0 只接 0,L/R 不互接;0 组件的其他接口不根据安装侧改写。真实 component.category 保留 0,实例标识、连接类别及替代分组使用装配角色;需求检查按装配角色统计,每个实例只计一次。显式排除同时约束真实类别和装配角色。候选在明确需求之后优先保持同型号,替代项重新验证全部相邻连接,接口不重复占用。interfaceChild 为父接口原始 child,前端须用双方实例和 frame 下标定位,不能再假设双方 child 相等。默认模板的候选类型通过后端生成的 `result.request.templatePartGroups` 扩展,具体类别和分组合计缺口分别返回 `missingParts`、`missingPartGroups`。部署时同步读取 `multimodal-v1.6-component-replacement`;消息请求参数不变,无需数据库迁移,原始 URDF 与历史方案均不回写。
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"rootLink": "ARM_ROOT",
|
||||||
|
"frames": [
|
||||||
|
{
|
||||||
|
"name": "incoming",
|
||||||
|
"child": "LINK_arm_r",
|
||||||
|
"interfaceType": "ARM_R"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
父接口也有 child=LINK_arm_r、目标类型为 ARM_R 时,可以连接这件右臂。多个同 child 的 frames 元素为多个独立接口,原始数组不重排;连接双方以实例标识及 frameIndex 占用接口。先处理固定躯干的接口,再逐层扩展,先覆盖需求类型和明确数量,再在尽量满足硬要求的前提下填充其他兼容接口,避免自动增补破坏本可满足的整机参数。
|
||||||
|
|
||||||
|
结构化结果的实例标识为 category:序号;AI 外层实例标识为 matchId:category:序号,序号从1开始。connection 返回 interfaceChild 和双方 parentFrameIndex/childFrameIndex;不再返回 matrixLayout、装配矩阵或连接摆放用 xyz/rpy。完整 urdfInfo 仍返回原始 JSON,由前端解析各实例模型并定位。资源URL可缓存共享,模型实例必须独立。
|
||||||
|
|
||||||
|
每次最多24个实例;达到实例、候选或搜索上限时返回已有组合、searchLimited=true和提示。资源清单仍检查路径安全,非法相对路径跳过;清单不完整只提示。部署前端时须同步切换到实例连接协议。历史快照不会迁移或重算,旧矩阵格式通过新messageId生成新方案。
|
||||||
|
|
||||||
|
公开组件继续返回 BOM、URDF 信息及 STEP/URDF URL,资源清单保留相对目录和版本。公开资源更新使用新上传批次路径;图片附件继续使用另一套私有资源。原 APP_DEMAND_ROOT_IS_MOUNTING_FRAME 配置已移除,后台不再需要根节点安装基准开关。
|
||||||
|
|
||||||
|
## 验证范围
|
||||||
|
|
||||||
|
自动测试使用 Java H2 表、模拟模型客户端、本地模拟 Responses HTTP 服务与测试资源域名,不调用真实付费模型、不访问业务 MySQL 或 OSS。
|
||||||
|
|
||||||
|
保留规则包原始 Node 样例,验证四组样例的机械条件投影及证据不变。覆盖新流程无追问、证据和图片归属、单位补充、数值与冲突边界、模型拒绝/超时/异常、SSE、取消和重试、版本和幂等、硬要求/偏好、7 个接口路由及旧路由 404、历史内部快照不暴露、资源版本变化后通过新消息刷新、私有附件过期清理,以及消息自动返回装配、默认模板、图文冲突和缺单位生成、断流查询恢复、选件失败不发布结果、匹配快照保存失败时回滚解析结果、新消息使正在选件的旧任务失效、child单向兼容矩阵、真实类别与装配角色分离、显式排除、中性替代候选、接口独立占用、类型优先与兜底、多个同child接口、四/六个同款实例、数量不足和上限、逐层覆盖需求、单实例替代及按实例汇总。验证缺件时默认组件与替代候选可直接预览、仅有躯干可显示,同时保留缺件和整机总量未验证提示;位姿或资源清单问题只提示,不阻塞已有组合。既有管理端上传、版本控制、逻辑删除与审计测试也参加回归。
|
||||||
|
|
||||||
|
真实图片 OCR 和多模态识别质量仍需配置实际模型后使用机械样本验收。修改提示词、Schema 或类别目录时,应同步来源版本、规则校验与一致性样例,不能只替换提示词后直接发布。
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
# 需求解析流程建表 SQL
|
||||||
|
|
||||||
|
在 `cadworld-api` 使用的 MySQL 数据库中执行以下建表语句。新增五张独立业务表,现有 `component` 表不变。应用启动不建表、不执行迁移;仓库 `.sql` 文件未修改。
|
||||||
|
|
||||||
|
自动生成流程复用以下五张表,无需修改表结构或执行新的迁移。新消息完成需求理解、选件和装配校验后,将解析结果与匹配快照一起保存;`ready` 表示方案已生成。`needs_clarification` 仅保留兼容旧记录,新流程不生成该状态。下方已有 DDL 的确认相关注释保留作为旧结构说明。
|
||||||
|
|
||||||
|
会话、消息、附件、解析和匹配均使用唯一编码对外访问,数据库主键只在内部使用。`owner_hash` 保存服务端认证主体的 `SHA-256("user:" + userCode)`;历史匿名归属保留至过期,已有表的注释调整见[登录迁移 SQL](auth-api.md#4-发布前手动执行的迁移-sql)。完整解析结果只由所属用户访问;模型配置、内部匹配快照和图片磁盘路径不返回前端。
|
||||||
|
|
||||||
|
```sql
|
||||||
|
CREATE TABLE `robot_demand_conversation` (
|
||||||
|
`id` bigint NOT NULL AUTO_INCREMENT COMMENT '会话主键ID,仅内部使用',
|
||||||
|
`conversation_code` varchar(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL COMMENT '需求会话唯一编码',
|
||||||
|
`owner_hash` char(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL COMMENT '登录用户归属摘要,历史匿名归属保留至过期',
|
||||||
|
`revision` int unsigned NOT NULL DEFAULT '0' COMMENT '当前需求版本号,每次新用户消息递增',
|
||||||
|
`created_at` datetime(3) NOT NULL COMMENT '创建时间',
|
||||||
|
`updated_at` datetime(3) NOT NULL COMMENT '最近更新时间',
|
||||||
|
`expires_at` datetime(3) NOT NULL COMMENT '会话过期时间,默认最近新消息后七天',
|
||||||
|
PRIMARY KEY (`id`),
|
||||||
|
UNIQUE KEY `uk_demand_conversation_code` (`conversation_code`) COMMENT '会话编码唯一索引',
|
||||||
|
KEY `idx_demand_conversation_owner` (`owner_hash`,`updated_at`) COMMENT '用户会话查询索引',
|
||||||
|
KEY `idx_demand_conversation_expiry` (`expires_at`,`id`) COMMENT '过期会话清理索引'
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='机器人需求会话表';
|
||||||
|
|
||||||
|
CREATE TABLE `robot_demand_attachment` (
|
||||||
|
`id` bigint NOT NULL AUTO_INCREMENT COMMENT '附件主键ID,仅内部使用',
|
||||||
|
`attachment_code` varchar(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL COMMENT '需求图片唯一编码',
|
||||||
|
`conversation_code` varchar(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL COMMENT '所属需求会话编码',
|
||||||
|
`message_code` varchar(80) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT '' COMMENT '绑定的用户消息编码,未发送时为空',
|
||||||
|
`mime_type` varchar(32) CHARACTER SET ascii COLLATE ascii_bin NOT NULL COMMENT '图片格式,仅PNG、JPEG、WebP',
|
||||||
|
`size_bytes` bigint unsigned NOT NULL COMMENT '图片字节数,每张不超过8MiB',
|
||||||
|
`sha256` char(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL COMMENT '图片SHA-256,用于内容完整性校验',
|
||||||
|
`created_at` datetime(3) NOT NULL COMMENT '上传时间',
|
||||||
|
PRIMARY KEY (`id`),
|
||||||
|
UNIQUE KEY `uk_demand_attachment_code` (`attachment_code`) COMMENT '图片编码唯一索引',
|
||||||
|
KEY `idx_demand_attachment_conversation` (`conversation_code`,`id`) COMMENT '会话图片查询及清理索引'
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='机器人需求图片附件表';
|
||||||
|
|
||||||
|
CREATE TABLE `robot_demand_message` (
|
||||||
|
`id` bigint NOT NULL AUTO_INCREMENT COMMENT '消息主键ID,仅内部排序使用',
|
||||||
|
`message_code` varchar(80) CHARACTER SET ascii COLLATE ascii_bin NOT NULL COMMENT '消息编码,用户消息由客户端生成并保持稳定',
|
||||||
|
`conversation_code` varchar(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL COMMENT '所属需求会话编码',
|
||||||
|
`message_role` varchar(16) CHARACTER SET ascii COLLATE ascii_bin NOT NULL COMMENT '消息角色:user或assistant,只由服务端设置',
|
||||||
|
`message_text` mediumtext NOT NULL COMMENT '用户原文或服务端生成的追问,每条最多20000字符',
|
||||||
|
`attachment_codes` json NOT NULL COMMENT '该消息的图片编码数组,文字消息写空数组',
|
||||||
|
`created_at` datetime(3) NOT NULL COMMENT '消息创建时间',
|
||||||
|
PRIMARY KEY (`id`),
|
||||||
|
UNIQUE KEY `uk_demand_message_code` (`conversation_code`,`message_code`) COMMENT '会话内消息幂等索引',
|
||||||
|
KEY `idx_demand_message_history` (`conversation_code`,`id`) COMMENT '按实际写入顺序加载历史'
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='机器人需求对话消息表';
|
||||||
|
|
||||||
|
CREATE TABLE `robot_demand_analysis` (
|
||||||
|
`id` bigint NOT NULL AUTO_INCREMENT COMMENT '解析记录主键ID,仅内部使用',
|
||||||
|
`analysis_code` varchar(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL COMMENT '需求解析唯一编码',
|
||||||
|
`conversation_code` varchar(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL COMMENT '所属需求会话编码',
|
||||||
|
`source_message_code` varchar(80) CHARACTER SET ascii COLLATE ascii_bin NOT NULL COMMENT '触发本次解析的用户消息编码',
|
||||||
|
`revision` int unsigned NOT NULL COMMENT '解析对应的需求版本号',
|
||||||
|
`status` varchar(32) CHARACTER SET ascii COLLATE ascii_bin NOT NULL COMMENT '解析状态:processing、ready、needs_clarification、failed、cancelled、superseded',
|
||||||
|
`result_json` json NOT NULL COMMENT '完整标准化request和analysis,未完成时写空对象',
|
||||||
|
`model_version` varchar(128) CHARACTER SET ascii COLLATE ascii_bin NOT NULL COMMENT '本次使用的模型版本,仅服务端记录',
|
||||||
|
`failure_code` varchar(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT '' COMMENT '通用失败编码,不保存上游响应正文或凭证',
|
||||||
|
`created_at` datetime(3) NOT NULL COMMENT '解析开始时间',
|
||||||
|
`updated_at` datetime(3) NOT NULL COMMENT '解析最近更新时间',
|
||||||
|
PRIMARY KEY (`id`),
|
||||||
|
UNIQUE KEY `uk_demand_analysis_code` (`analysis_code`) COMMENT '解析编码唯一索引',
|
||||||
|
UNIQUE KEY `uk_demand_analysis_revision` (`conversation_code`,`revision`) COMMENT '每个会话版本只有一份解析结果',
|
||||||
|
KEY `idx_demand_analysis_message` (`conversation_code`,`source_message_code`,`revision`) COMMENT '重复消息查询对应解析结果'
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='机器人需求解析记录表';
|
||||||
|
|
||||||
|
CREATE TABLE `robot_demand_match` (
|
||||||
|
`id` bigint NOT NULL AUTO_INCREMENT COMMENT '匹配记录主键ID,仅内部使用',
|
||||||
|
`match_code` varchar(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL COMMENT '已确认需求的匹配方案唯一编码',
|
||||||
|
`analysis_code` varchar(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL COMMENT '对应的已确认解析编码',
|
||||||
|
`revision` int unsigned NOT NULL COMMENT '确认时的需求版本号',
|
||||||
|
`result_json` json NOT NULL COMMENT '匹配响应及内部组件版本快照,快照不对外返回',
|
||||||
|
`degradation_accepted` tinyint unsigned NOT NULL DEFAULT '0' COMMENT '是否接受明确降级:0-未接受,1-已接受,不代表要求已满足',
|
||||||
|
`created_at` datetime(3) NOT NULL COMMENT '首次确认匹配时间',
|
||||||
|
`updated_at` datetime(3) NOT NULL COMMENT '方案刷新或降级确认时间',
|
||||||
|
PRIMARY KEY (`id`),
|
||||||
|
UNIQUE KEY `uk_demand_match_code` (`match_code`) COMMENT '匹配编码唯一索引',
|
||||||
|
UNIQUE KEY `uk_demand_match_analysis` (`analysis_code`) COMMENT '解析版本确认幂等索引'
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='机器人需求确认匹配表';
|
||||||
|
```
|
||||||
|
|
||||||
|
图片文件存放于 `APP_DEMAND_ATTACHMENT_DIRECTORY` 指定的私有目录,不写入这些表,不发布为静态文件。生产部署需要持久化卷;多实例部署需要挂载同一个私有文件系统目录。
|
||||||
@@ -0,0 +1,147 @@
|
|||||||
|
# 个人项目、广场与封面接口
|
||||||
|
|
||||||
|
先执行[项目建表 SQL](project-schema.md),再部署服务。接口继续使用 `{code,message,data,requestId}`;`projectCode`、`ownerUserCode` 等均为业务编码,不返回数据库主键。
|
||||||
|
|
||||||
|
## 1. 前端调用顺序与权限
|
||||||
|
|
||||||
|
1. 完成[需求生成](robot-demand-api.md),获取状态为 `ready` 的 `analysisId`。
|
||||||
|
2. 调用 `POST /api/projects`,将该值作为 `analysisCode`,保存为当前用户的私有项目。
|
||||||
|
3. 需要封面时,用户选择图片或前端对装配预览截图,通过专用封面接口上传。
|
||||||
|
4. 发布前必须存在有效封面;有缺件但可预览的方案也可发布,前端保留缺件和校验提示。
|
||||||
|
5. 广场列表和详情无需登录;登录后可以 fork 到自己的工作空间,副本默认私有。
|
||||||
|
|
||||||
|
除两个广场 GET 接口外,所有项目接口都需要 `Authorization: Bearer <token>`。用户归属从认证主体获取,不传用户编码。无 Token 可匿名浏览广场;主动携带无效 Token 时沿用现有鉴权规则返回 401。
|
||||||
|
|
||||||
|
`GET /api/projects` 即“我的工作空间”。项目装配内容保存后固定,只能修改名称、简介、封面和发布状态;重新拼装后另存一个项目。不提供任意模型文件上传、替换或文件编辑接口。
|
||||||
|
|
||||||
|
组件禁用只影响新拼装方案和替代候选,不影响已保存项目的独立装配快照及展示。
|
||||||
|
|
||||||
|
| 方法 | 路径 | 请求 | 用途 |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| POST | `/api/projects` | 创建 JSON | 保存生成结果 |
|
||||||
|
| GET | `/api/projects` | `page`、`size` | 当前用户项目列表 |
|
||||||
|
| GET | `/api/projects/{projectCode}` | 无 | 当前用户项目详情 |
|
||||||
|
| PATCH | `/api/projects/{projectCode}` | 修改 JSON | 修改名称、简介 |
|
||||||
|
| DELETE | `/api/projects/{projectCode}` | 无 | 软删除,返回 `{success:true}` |
|
||||||
|
| POST | `/api/projects/{projectCode}/cover` | multipart `file` | 上传或替换封面 |
|
||||||
|
| POST | `/api/projects/{projectCode}/publish` | 无 | 发布到广场 |
|
||||||
|
| POST | `/api/projects/{projectCode}/unpublish` | 无 | 取消发布 |
|
||||||
|
| GET | `/api/plaza/projects` | `page`、`size` | 匿名浏览广场 |
|
||||||
|
| GET | `/api/plaza/projects/{projectCode}` | 无 | 匿名查看公开详情 |
|
||||||
|
| POST | `/api/plaza/projects/{projectCode}/fork` | 无 | fork 为自己的私有项目 |
|
||||||
|
|
||||||
|
所有者详情及写操作只能操作自己的项目,即使目标项目公开也不能直接修改。其他用户查看公开项目应使用广场详情接口。无权访问、不存在或已删除的项目返回 404;取消发布后的广场详情及 fork 也返回 404。项目响应设置 `Cache-Control: no-store`。
|
||||||
|
|
||||||
|
## 2. 保存、修改与响应
|
||||||
|
|
||||||
|
创建请求示例:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"analysisCode": "DN-22222222222222222222222222222222",
|
||||||
|
"projectName": "我的机器人",
|
||||||
|
"description": "躯干与右臂装配方案"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`analysisCode`、`projectName` 必填,分别最多 64、128 字符;名称不能全为空白。简介可省略或为 null,保存为空字符串,最多 2000 字符。重复保存同一方案会创建独立的新项目。
|
||||||
|
|
||||||
|
来源必须是当前用户未过期会话的当前已完成版本,且有可预览组件;处理中、失败、被新消息替代、无匹配或 `assembly.status=blocked` 的结果不能保存。服务端读取自己的生成快照,不接受客户端上传自定义装配 JSON。
|
||||||
|
|
||||||
|
PATCH 请求只接受 `projectName` 和 `description`。字段省略或为 null 时保持原值;简介传 `""` 表示清空,名称不能清空。客户端提交 `snapshot`、`visibility`、`coverRelativePath`、`ownerUserCode` 等额外字段返回 422。
|
||||||
|
|
||||||
|
创建、详情、修改、上传、发布、取消发布和 fork 返回同一项目结构:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"code": "OK",
|
||||||
|
"message": "success",
|
||||||
|
"data": {
|
||||||
|
"projectCode": "RP-11111111111111111111111111111111",
|
||||||
|
"ownerUserCode": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
|
||||||
|
"projectName": "我的机器人",
|
||||||
|
"description": "躯干与右臂装配方案",
|
||||||
|
"coverRelativePath": null,
|
||||||
|
"coverUrl": null,
|
||||||
|
"schemaVersion": "project-v1",
|
||||||
|
"matchStatus": "partial",
|
||||||
|
"assemblyStatus": "ready",
|
||||||
|
"sourceProjectCode": null,
|
||||||
|
"visibility": "PRIVATE",
|
||||||
|
"publishedAt": null,
|
||||||
|
"createdAt": "2026-10-20T02:00:00Z",
|
||||||
|
"updatedAt": "2026-10-20T02:00:00Z",
|
||||||
|
"snapshot": {
|
||||||
|
"status": "partial",
|
||||||
|
"rootCategory": "TORSO_0",
|
||||||
|
"searchLimited": false,
|
||||||
|
"totals": {},
|
||||||
|
"unmetRequirements": [],
|
||||||
|
"missingParts": [],
|
||||||
|
"missingPartGroups": [],
|
||||||
|
"requirementChecks": [],
|
||||||
|
"assembly": {},
|
||||||
|
"components": []
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"requestId": "project-save-001"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
示例中的 `snapshot` 子数组和对象作结构占位,真实成功项目一定包含非空组件和可预览装配。其 `components`、`assembly`、汇总、缺件及校验字段沿用生成响应 `match` 中的展示结构,可复用现有预览器。快照去除原始对话、需求图片、来源解析/会话信息、内部字段和替代方案列表,不返回 `sourceAnalysisCode`。
|
||||||
|
|
||||||
|
列表返回 `{items,page,size,total}`;`items` 与项目结构相同,但省略 `snapshot`。`page` 默认 1,`size` 默认 20、范围 1–100。个人列表按 `updatedAt` 倒序,广场按 `publishedAt` 倒序,时间相同按项目编码倒序。
|
||||||
|
|
||||||
|
## 3. OSS 封面
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
async function uploadProjectCover(token, projectCode, fileOrScreenshotBlob) {
|
||||||
|
const form = new FormData();
|
||||||
|
form.append("file", fileOrScreenshotBlob, "cover.png");
|
||||||
|
const response = await fetch(`/api/projects/${projectCode}/cover`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { Authorization: `Bearer ${token}` },
|
||||||
|
body: form
|
||||||
|
});
|
||||||
|
const result = await response.json();
|
||||||
|
if (!response.ok) throw result;
|
||||||
|
return result.data;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
不要手动设置 multipart 的 Content-Type。支持 PNG、JPEG、WebP,每张不超过 8MiB,文件内容须与 MIME 一致;文件名由服务端生成,忽略客户端文件名,不接受对象路径或 URL。
|
||||||
|
|
||||||
|
```text
|
||||||
|
数据库 cover_relative_path:
|
||||||
|
projects/RP-xxx/covers/uuid.png
|
||||||
|
|
||||||
|
OSS 对象键(示例测试环境):
|
||||||
|
cadworld_dev/projects/RP-xxx/covers/uuid.png
|
||||||
|
|
||||||
|
响应 coverUrl:
|
||||||
|
https://你的OSS或CDN域名/cadworld_dev/projects/RP-xxx/covers/uuid.png
|
||||||
|
```
|
||||||
|
|
||||||
|
配置 `OSS_ACCESS_KEY_ID`、`OSS_ACCESS_KEY_SECRET`、`OSS_REGION`、`OSS_BUCKET`、`OSS_ROOT_PREFIX` 和 `APP_STORAGE_PUBLIC_BASE_URL`。公开访问基址只填写 OSS/CDN 域名或统一基址,不重复附加环境根目录,不能使用管理端下载代理地址。浏览器通过返回的 URL 直接加载图片。
|
||||||
|
|
||||||
|
后端接收图片并上传 OSS,成功后才更新项目路径;失败保留原封面。数据库关联失败会尝试清理本次新对象,失败日志带项目编码及 requestId,供排查补偿。每次替换都产生新路径,不覆盖旧图片。
|
||||||
|
|
||||||
|
## 4. 发布、fork 与错误
|
||||||
|
|
||||||
|
发布成功后 `visibility=PUBLIC`、`publishedAt` 有值;重复发布保留原时间。取消发布后改为 `PRIVATE` 且清空发布时间,再次发布生成新时间。发布时校验快照可预览以及封面对象确实存在。
|
||||||
|
|
||||||
|
fork 不需要请求体,沿用来源名称和简介,复制独立装配快照,记录 `sourceProjectCode`,新项目归当前用户并默认为私有。封面共享同一不可覆盖的 OSS 对象,替换或删除原项目不影响副本;来源重新发布、修改简介或更换封面也不会自动同步到副本。
|
||||||
|
|
||||||
|
| HTTP | 业务码 | 含义 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 401 | `UNAUTHORIZED` | 写操作未登录或 Token 失效 |
|
||||||
|
| 404 | `PROJECT_NOT_FOUND` | 项目不存在、已删除、无权访问或来源不再公开 |
|
||||||
|
| 404 | `DEMAND_NOT_FOUND` | 来源解析不存在、不属于当前用户或会话过期 |
|
||||||
|
| 409 | `PROJECT_RESULT_UNAVAILABLE` | 来源未完成、版本已更新或装配结果不可预览 |
|
||||||
|
| 409 | `PROJECT_COVER_REQUIRED` | 发布前缺少封面或 OSS 对象已不存在 |
|
||||||
|
| 413 | `UPLOAD_TOO_LARGE` / `INVALID_REQUEST` | 封面超过限制;后者由 multipart 请求限制返回 |
|
||||||
|
| 422 | `INVALID_PROJECT_COVER` | 空图片、不支持的格式或 MIME 与文件头不一致 |
|
||||||
|
| 422 | `INVALID_REQUEST` | JSON 字段、长度或分页参数非法 |
|
||||||
|
| 502 | `OSS_*_FAILED` | OSS 上传或对象校验失败 |
|
||||||
|
|
||||||
|
部署顺序:执行建表 SQL → 配置 OSS 和访问域名 → 部署服务 → 验证保存、封面上传、匿名广场及跨账号 fork。替换封面和软删除项目不立即删除旧 OSS 对象,一期不提供自动垃圾回收。
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
# 机器人项目建表 SQL
|
||||||
|
|
||||||
|
部署项目功能前,在用户端使用的 MySQL 数据库中手动执行以下 SQL。只新增一张 `robot_project` 表,不自动迁移,不修改仓库 `.sql` 文件。每个用户的工作空间直接通过 `owner_user_code` 查询。
|
||||||
|
|
||||||
|
```sql
|
||||||
|
CREATE TABLE `robot_project` (
|
||||||
|
`id` bigint NOT NULL AUTO_INCREMENT COMMENT '项目主键ID,仅内部使用',
|
||||||
|
`project_code` varchar(64) COLLATE utf8mb4_bin NOT NULL COMMENT '项目唯一编码',
|
||||||
|
`owner_user_code` char(32) COLLATE utf8mb4_bin NOT NULL COMMENT '所属用户唯一编码',
|
||||||
|
`project_name` varchar(128) NOT NULL COMMENT '项目名称',
|
||||||
|
`description` varchar(2000) NOT NULL DEFAULT '' COMMENT '项目简介',
|
||||||
|
`cover_relative_path` varchar(512) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '封面相对路径,不含域名和环境根目录',
|
||||||
|
`snapshot_json` json NOT NULL COMMENT '独立保存的装配展示快照,不含原始对话和需求图片',
|
||||||
|
`schema_version` varchar(32) COLLATE utf8mb4_bin NOT NULL COMMENT '项目快照格式版本,首版为project-v1',
|
||||||
|
`match_status` varchar(16) COLLATE utf8mb4_bin NOT NULL COMMENT '方案完整度:complete或partial',
|
||||||
|
`assembly_status` varchar(16) COLLATE utf8mb4_bin NOT NULL COMMENT '装配状态:ready或partial',
|
||||||
|
`source_analysis_code` varchar(64) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '原始需求解析编码,仅用于溯源',
|
||||||
|
`source_project_code` varchar(64) COLLATE utf8mb4_bin DEFAULT NULL COMMENT 'fork来源项目编码,原创项目为空',
|
||||||
|
`visibility` varchar(16) COLLATE utf8mb4_bin NOT NULL DEFAULT 'PRIVATE' COMMENT '可见性:PRIVATE私有,PUBLIC公开',
|
||||||
|
`published_at` datetime(3) DEFAULT NULL COMMENT '最近一次从私有转为公开的时间,私有时为空',
|
||||||
|
`deleted` tinyint unsigned NOT NULL DEFAULT '0' COMMENT '删除标记:0未删除,1已删除',
|
||||||
|
`created_at` datetime(3) NOT NULL COMMENT '创建时间',
|
||||||
|
`updated_at` datetime(3) NOT NULL COMMENT '最近更新时间',
|
||||||
|
PRIMARY KEY (`id`),
|
||||||
|
UNIQUE KEY `uk_robot_project_code` (`project_code`) COMMENT '项目编码唯一索引',
|
||||||
|
KEY `idx_robot_project_owner`
|
||||||
|
(`owner_user_code`, `deleted`, `updated_at`, `project_code`) COMMENT '个人项目列表索引',
|
||||||
|
KEY `idx_robot_project_plaza`
|
||||||
|
(`visibility`, `deleted`, `published_at`, `project_code`) COMMENT '广场项目列表索引'
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
|
||||||
|
COLLATE=utf8mb4_general_ci COMMENT='机器人装配项目表';
|
||||||
|
```
|
||||||
|
|
||||||
|
所有字符字段统一使用表级 `utf8mb4` 字符集。编码、路径、版本和状态字段指定 `utf8mb4_bin`,保留区分大小写的比较规则;名称和简介使用表级 `utf8mb4_general_ci`。
|
||||||
|
|
||||||
|
如果已经执行了此前的建表 SQL,手动执行以下语句,将原先单独使用 ASCII 的字段转换为 `utf8mb4`,保留原有类型、默认值及中文注释。新建表无需执行这段转换 SQL。
|
||||||
|
|
||||||
|
```sql
|
||||||
|
ALTER TABLE `robot_project`
|
||||||
|
MODIFY COLUMN `project_code` varchar(64) COLLATE utf8mb4_bin NOT NULL COMMENT '项目唯一编码',
|
||||||
|
MODIFY COLUMN `owner_user_code` char(32) COLLATE utf8mb4_bin NOT NULL COMMENT '所属用户唯一编码',
|
||||||
|
MODIFY COLUMN `cover_relative_path` varchar(512) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '封面相对路径,不含域名和环境根目录',
|
||||||
|
MODIFY COLUMN `schema_version` varchar(32) COLLATE utf8mb4_bin NOT NULL COMMENT '项目快照格式版本,首版为project-v1',
|
||||||
|
MODIFY COLUMN `match_status` varchar(16) COLLATE utf8mb4_bin NOT NULL COMMENT '方案完整度:complete或partial',
|
||||||
|
MODIFY COLUMN `assembly_status` varchar(16) COLLATE utf8mb4_bin NOT NULL COMMENT '装配状态:ready或partial',
|
||||||
|
MODIFY COLUMN `source_analysis_code` varchar(64) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '原始需求解析编码,仅用于溯源',
|
||||||
|
MODIFY COLUMN `source_project_code` varchar(64) COLLATE utf8mb4_bin DEFAULT NULL COMMENT 'fork来源项目编码,原创项目为空',
|
||||||
|
MODIFY COLUMN `visibility` varchar(16) COLLATE utf8mb4_bin NOT NULL DEFAULT 'PRIVATE' COMMENT '可见性:PRIVATE私有,PUBLIC公开';
|
||||||
|
```
|
||||||
|
|
||||||
|
来源编码不设置级联删除约束。保存项目后,原需求会话过期清理不影响项目;fork 后,来源项目取消发布或删除也不影响副本。
|
||||||
|
|
||||||
|
封面数据库路径示例为 `projects/RP-xxx/covers/xxx.png`。实际 OSS 对象键由当前 `OSS_ROOT_PREFIX` 加上此路径生成,域名由 `APP_STORAGE_PUBLIC_BASE_URL` 配置。切换环境只改变路径解析配置;若跨环境迁移数据,仍需将实际图片同步到目标桶的对应环境目录。
|
||||||
|
|
||||||
|
项目删除采用软删除。封面替换、项目软删除暂不物理清理 OSS 对象,因为已有 fork 可能共享这些对象;后续清理必须先确认没有项目引用。
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,54 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.linkerbot</groupId>
|
||||||
|
<artifactId>cadworld</artifactId>
|
||||||
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
<relativePath>../pom.xml</relativePath>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<artifactId>cadworld-api</artifactId>
|
||||||
|
<packaging>jar</packaging>
|
||||||
|
<name>cadworld-api</name>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.linkerbot</groupId>
|
||||||
|
<artifactId>cadworld-security-api</artifactId>
|
||||||
|
<version>${project.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.linkerbot</groupId>
|
||||||
|
<artifactId>cadworld-service</artifactId>
|
||||||
|
<version>${project.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.mysql</groupId>
|
||||||
|
<artifactId>mysql-connector-j</artifactId>
|
||||||
|
<scope>runtime</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.h2database</groupId>
|
||||||
|
<artifactId>h2</artifactId>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.security</groupId>
|
||||||
|
<artifactId>spring-security-test</artifactId>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
</project>
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
package com.linkerbot.cadworld.api;
|
||||||
|
|
||||||
|
import com.linkerbot.cadworld.config.MatchingProperties;
|
||||||
|
import com.linkerbot.cadworld.config.DemandProperties;
|
||||||
|
import com.linkerbot.cadworld.config.MybatisPlusConfig;
|
||||||
|
import com.linkerbot.cadworld.config.StorageProperties;
|
||||||
|
import com.linkerbot.cadworld.mapper.ComponentMapper;
|
||||||
|
import com.linkerbot.cadworld.service.impl.ObjectStorageUrlResolver;
|
||||||
|
import org.mybatis.spring.annotation.MapperScan;
|
||||||
|
import org.springframework.boot.SpringApplication;
|
||||||
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
import org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration;
|
||||||
|
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||||
|
import org.springframework.context.annotation.Import;
|
||||||
|
|
||||||
|
@SpringBootApplication(exclude = UserDetailsServiceAutoConfiguration.class, scanBasePackages = {
|
||||||
|
"com.linkerbot.cadworld.api", "com.linkerbot.cadworld.common",
|
||||||
|
"com.linkerbot.cadworld.service.matching", "com.linkerbot.cadworld.service.auth",
|
||||||
|
"com.linkerbot.cadworld.security.api"
|
||||||
|
})
|
||||||
|
@EnableConfigurationProperties({StorageProperties.class, MatchingProperties.class, DemandProperties.class})
|
||||||
|
@Import({MybatisPlusConfig.class, ObjectStorageUrlResolver.class})
|
||||||
|
@MapperScan(basePackageClasses = ComponentMapper.class)
|
||||||
|
public class ApiApplication {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
SpringApplication.run(ApiApplication.class, args);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
package com.linkerbot.cadworld.api.config;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import com.linkerbot.cadworld.config.DemandProperties;
|
||||||
|
import com.linkerbot.cadworld.mapper.ComponentMapper;
|
||||||
|
import com.linkerbot.cadworld.service.demand.ArkDemandModelClient;
|
||||||
|
import com.linkerbot.cadworld.service.demand.DemandAnalysisService;
|
||||||
|
import com.linkerbot.cadworld.service.demand.DemandAssemblyValidator;
|
||||||
|
import com.linkerbot.cadworld.service.demand.DemandAttachmentStore;
|
||||||
|
import com.linkerbot.cadworld.service.demand.DemandMatchService;
|
||||||
|
import com.linkerbot.cadworld.service.demand.DemandModelClient;
|
||||||
|
import com.linkerbot.cadworld.service.demand.DemandNormalizer;
|
||||||
|
import com.linkerbot.cadworld.service.demand.DemandRepository;
|
||||||
|
import com.linkerbot.cadworld.service.demand.DemandRequirementChecker;
|
||||||
|
import com.linkerbot.cadworld.service.demand.DemandRetentionService;
|
||||||
|
import com.linkerbot.cadworld.service.demand.DemandRules;
|
||||||
|
import com.linkerbot.cadworld.service.impl.ObjectStorageUrlResolver;
|
||||||
|
import com.linkerbot.cadworld.service.matching.MatchTextService;
|
||||||
|
import com.linkerbot.cadworld.service.matching.RobotMatchingService;
|
||||||
|
import com.linkerbot.cadworld.service.support.StorageObjectKeys;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.List;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.jdbc.core.JdbcTemplate;
|
||||||
|
import org.springframework.transaction.PlatformTransactionManager;
|
||||||
|
import org.springframework.web.servlet.config.annotation.CorsRegistry;
|
||||||
|
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||||
|
|
||||||
|
/** 仅用户端启动时注册需求解析服务,管理端不会绑定模型或初始化会话业务。 */
|
||||||
|
@Slf4j
|
||||||
|
@Configuration(proxyBeanMethods = false)
|
||||||
|
public class DemandConfiguration {
|
||||||
|
@Bean DemandRules demandRules(ObjectMapper json) throws IOException { return new DemandRules(json); }
|
||||||
|
@Bean DemandNormalizer demandNormalizer(DemandRules rules, ObjectMapper json) { return new DemandNormalizer(rules, json); }
|
||||||
|
@Bean DemandModelClient demandModelClient(ObjectMapper json, DemandRules rules, DemandProperties properties) { return new ArkDemandModelClient(json, rules, properties); }
|
||||||
|
@Bean DemandRepository demandRepository(JdbcTemplate jdbc, ObjectMapper json, DemandProperties properties, PlatformTransactionManager manager) {
|
||||||
|
return new DemandRepository(jdbc, json, properties, manager);
|
||||||
|
}
|
||||||
|
@Bean DemandAttachmentStore demandAttachmentStore(DemandRepository repository, DemandProperties properties) { return new DemandAttachmentStore(repository, properties); }
|
||||||
|
@Bean DemandRetentionService demandRetentionService(DemandRepository repository, DemandAttachmentStore attachments) { return new DemandRetentionService(repository, attachments); }
|
||||||
|
@Bean DemandAnalysisService demandAnalysisService(DemandRepository repository, DemandAttachmentStore attachments, DemandModelClient model,
|
||||||
|
DemandNormalizer normalizer, DemandMatchService matches, DemandProperties properties) {
|
||||||
|
return new DemandAnalysisService(repository, attachments, model, normalizer, matches, properties);
|
||||||
|
}
|
||||||
|
@Bean DemandAssemblyValidator demandAssemblyValidator() { return new DemandAssemblyValidator(); }
|
||||||
|
@Bean DemandRequirementChecker demandRequirementChecker(ObjectMapper json, MatchTextService text) { return new DemandRequirementChecker(json, text); }
|
||||||
|
@Bean DemandMatchService demandMatchService(ObjectMapper json, RobotMatchingService matching, ComponentMapper mapper,
|
||||||
|
ObjectStorageUrlResolver urls, StorageObjectKeys keys,
|
||||||
|
DemandAssemblyValidator assembly, DemandRequirementChecker requirements) {
|
||||||
|
return new DemandMatchService(json, matching, mapper, urls, keys, assembly, requirements);
|
||||||
|
}
|
||||||
|
@Bean WebMvcConfigurer demandCors(DemandProperties properties) {
|
||||||
|
return new WebMvcConfigurer() {
|
||||||
|
@Override public void addCorsMappings(CorsRegistry registry) {
|
||||||
|
List<String> origins = properties.allowedOrigins();
|
||||||
|
if (origins == null || origins.isEmpty()) return;
|
||||||
|
String[] allowed = origins.stream().filter((String origin) -> !origin.isBlank()).toArray(String[]::new);
|
||||||
|
if (allowed.length == 0) return;
|
||||||
|
for (String origin : allowed) if (origin.contains("*")) throw new IllegalArgumentException("需求接口凭证跨域必须配置具体前端域名");
|
||||||
|
registry.addMapping("/api/**").allowedOrigins(allowed).allowedMethods("GET", "POST", "PATCH", "DELETE", "OPTIONS")
|
||||||
|
.allowedHeaders("Content-Type", "X-Request-Id", "Authorization").exposedHeaders("X-Request-Id").allowCredentials(true).maxAge(3600);
|
||||||
|
log.info("用户接口跨域配置已启用 path=/api/** allowedOrigins={}", List.of(allowed));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
+46
@@ -0,0 +1,46 @@
|
|||||||
|
package com.linkerbot.cadworld.api.config;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import com.linkerbot.cadworld.config.OssClientConfiguration;
|
||||||
|
import com.linkerbot.cadworld.config.OssProperties;
|
||||||
|
import com.linkerbot.cadworld.service.client.ObjectStorageClient;
|
||||||
|
import com.linkerbot.cadworld.service.client.OssObjectStorageClient;
|
||||||
|
import com.linkerbot.cadworld.service.demand.DemandRepository;
|
||||||
|
import com.linkerbot.cadworld.service.impl.ObjectStorageUrlResolver;
|
||||||
|
import com.linkerbot.cadworld.service.project.ProjectCoverStore;
|
||||||
|
import com.linkerbot.cadworld.service.project.ProjectRepository;
|
||||||
|
import com.linkerbot.cadworld.service.project.ProjectService;
|
||||||
|
import com.linkerbot.cadworld.service.project.ProjectSnapshots;
|
||||||
|
import com.linkerbot.cadworld.service.support.StorageObjectKeys;
|
||||||
|
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.context.annotation.Import;
|
||||||
|
import org.springframework.jdbc.core.JdbcTemplate;
|
||||||
|
import org.springframework.transaction.PlatformTransactionManager;
|
||||||
|
|
||||||
|
@Configuration(proxyBeanMethods = false)
|
||||||
|
@EnableConfigurationProperties(OssProperties.class)
|
||||||
|
@Import({OssClientConfiguration.class, OssObjectStorageClient.class, StorageObjectKeys.class})
|
||||||
|
public class ProjectConfiguration {
|
||||||
|
@Bean
|
||||||
|
ProjectRepository projectRepository(JdbcTemplate jdbc, ObjectMapper json) {
|
||||||
|
return new ProjectRepository(jdbc, json);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
ProjectSnapshots projectSnapshots(ObjectMapper json) {
|
||||||
|
return new ProjectSnapshots(json);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
ProjectCoverStore projectCoverStore(ObjectStorageClient storage, StorageObjectKeys keys, ObjectStorageUrlResolver urls) {
|
||||||
|
return new ProjectCoverStore(storage, keys, urls);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
ProjectService projectService(ProjectRepository projects, DemandRepository demands, ProjectSnapshots snapshots,
|
||||||
|
ProjectCoverStore covers, PlatformTransactionManager manager) {
|
||||||
|
return new ProjectService(projects, demands, snapshots, covers, manager);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
package com.linkerbot.cadworld.api.controller;
|
||||||
|
|
||||||
|
import com.linkerbot.cadworld.common.api.ApiResponse;
|
||||||
|
import com.linkerbot.cadworld.common.api.RequestIdHolder;
|
||||||
|
import com.linkerbot.cadworld.dto.auth.CaptchaResponse;
|
||||||
|
import com.linkerbot.cadworld.dto.auth.LoginRequest;
|
||||||
|
import com.linkerbot.cadworld.dto.auth.LoginResponse;
|
||||||
|
import com.linkerbot.cadworld.dto.auth.LoginUserResponse;
|
||||||
|
import com.linkerbot.cadworld.entity.SysUser;
|
||||||
|
import com.linkerbot.cadworld.security.api.CurrentUser;
|
||||||
|
import com.linkerbot.cadworld.security.common.AuthProperties;
|
||||||
|
import com.linkerbot.cadworld.security.common.CaptchaService;
|
||||||
|
import com.linkerbot.cadworld.security.common.TokenService;
|
||||||
|
import com.linkerbot.cadworld.service.auth.LoginUserService;
|
||||||
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
|
import jakarta.validation.Valid;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.http.HttpHeaders;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestBody;
|
||||||
|
import org.springframework.web.bind.annotation.RequestHeader;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
@RestController
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class AuthController {
|
||||||
|
private final CaptchaService captcha;
|
||||||
|
private final TokenService tokens;
|
||||||
|
private final LoginUserService users;
|
||||||
|
private final AuthProperties properties;
|
||||||
|
|
||||||
|
@GetMapping("/api/auth/captcha")
|
||||||
|
public ApiResponse<CaptchaResponse> captcha(HttpServletResponse response) {
|
||||||
|
response.setHeader(HttpHeaders.CACHE_CONTROL, "no-store");
|
||||||
|
return ApiResponse.success(captcha.issue());
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/api/auth/login")
|
||||||
|
public ApiResponse<LoginResponse> login(@Valid @RequestBody LoginRequest input, HttpServletResponse response) {
|
||||||
|
response.setHeader(HttpHeaders.CACHE_CONTROL, "no-store");
|
||||||
|
captcha.verify(input.captchaCode(), input.captchaAnswer());
|
||||||
|
SysUser user = users.login(input.email());
|
||||||
|
return ApiResponse.success(new LoginResponse(tokens.issue(user.getUserCode()), "Bearer",
|
||||||
|
properties.tokenTtl().toSeconds(), users.view(user)));
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/api/auth/logout")
|
||||||
|
public ApiResponse<Void> logout(@RequestHeader(HttpHeaders.AUTHORIZATION) String authorization) {
|
||||||
|
String userCode = CurrentUser.required();
|
||||||
|
tokens.revoke(authorization.substring(7));
|
||||||
|
log.info("用户退出登录 userCode={} requestId={}", userCode, RequestIdHolder.get());
|
||||||
|
return ApiResponse.success(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/api/users/me")
|
||||||
|
public ApiResponse<LoginUserResponse> me() {
|
||||||
|
return ApiResponse.success(users.view(users.requireActive(CurrentUser.required())));
|
||||||
|
}
|
||||||
|
}
|
||||||
+38
@@ -0,0 +1,38 @@
|
|||||||
|
package com.linkerbot.cadworld.api.controller;
|
||||||
|
|
||||||
|
import com.linkerbot.cadworld.common.api.ApiResponse;
|
||||||
|
import com.linkerbot.cadworld.dto.matching.PublicComponentResponse;
|
||||||
|
import com.linkerbot.cadworld.dto.matching.RobotMatchRequest;
|
||||||
|
import com.linkerbot.cadworld.dto.matching.RobotMatchResponse;
|
||||||
|
import com.linkerbot.cadworld.service.matching.PublicComponentQueryService;
|
||||||
|
import com.linkerbot.cadworld.service.matching.RobotMatchingService;
|
||||||
|
import jakarta.validation.Valid;
|
||||||
|
import jakarta.validation.constraints.NotBlank;
|
||||||
|
import jakarta.validation.constraints.Size;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.validation.annotation.Validated;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.PathVariable;
|
||||||
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestBody;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api")
|
||||||
|
@Validated
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class ComponentMatchingController {
|
||||||
|
private final RobotMatchingService matching;
|
||||||
|
private final PublicComponentQueryService components;
|
||||||
|
|
||||||
|
@PostMapping("/robot-matches")
|
||||||
|
public ApiResponse<RobotMatchResponse> match(@Valid @RequestBody RobotMatchRequest request) {
|
||||||
|
return ApiResponse.success(matching.match(request));
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/components/{componentCode}")
|
||||||
|
public ApiResponse<PublicComponentResponse> detail(@PathVariable @NotBlank @Size(max = 64) String componentCode) {
|
||||||
|
return ApiResponse.success(components.get(componentCode));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
package com.linkerbot.cadworld.api.controller;
|
||||||
|
|
||||||
|
import com.linkerbot.cadworld.security.api.CurrentUser;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.security.MessageDigest;
|
||||||
|
import java.security.NoSuchAlgorithmException;
|
||||||
|
import java.util.HexFormat;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
/** 仅使用服务端认证主体确定归属;历史匿名 Cookie 不参与账号会话访问。 */
|
||||||
|
@Component
|
||||||
|
public class DemandOwner {
|
||||||
|
public String resolve() {
|
||||||
|
try {
|
||||||
|
byte[] owner = ("user:" + CurrentUser.required()).getBytes(StandardCharsets.US_ASCII);
|
||||||
|
return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(owner));
|
||||||
|
} catch (NoSuchAlgorithmException exception) {
|
||||||
|
throw new IllegalStateException("SHA-256 unavailable", exception);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+90
@@ -0,0 +1,90 @@
|
|||||||
|
package com.linkerbot.cadworld.api.controller;
|
||||||
|
|
||||||
|
import com.linkerbot.cadworld.common.api.ApiResponse;
|
||||||
|
import com.linkerbot.cadworld.common.api.RequestIdHolder;
|
||||||
|
import com.linkerbot.cadworld.common.exception.BizException;
|
||||||
|
import com.linkerbot.cadworld.dto.demand.DemandMessageRequest;
|
||||||
|
import com.linkerbot.cadworld.service.demand.DemandAnalysisService;
|
||||||
|
import com.linkerbot.cadworld.service.demand.DemandAttachmentStore;
|
||||||
|
import com.linkerbot.cadworld.service.demand.DemandRepository;
|
||||||
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
|
import jakarta.validation.Valid;
|
||||||
|
import jakarta.validation.constraints.NotBlank;
|
||||||
|
import java.io.IOException;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.http.CacheControl;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.validation.annotation.Validated;
|
||||||
|
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.PathVariable;
|
||||||
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestBody;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestPart;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
||||||
|
|
||||||
|
/** 消息接口自动完成需求理解、选件和装配校验;完成事件直接包含机器人方案。 */
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api")
|
||||||
|
@Validated
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
@Slf4j
|
||||||
|
public class RobotDemandController {
|
||||||
|
private final DemandOwner owners;
|
||||||
|
private final DemandRepository repository;
|
||||||
|
private final DemandAttachmentStore attachments;
|
||||||
|
private final DemandAnalysisService analyses;
|
||||||
|
|
||||||
|
@PostMapping("/robot-conversations")
|
||||||
|
public ApiResponse<DemandRepository.Conversation> create() {
|
||||||
|
DemandRepository.Conversation conversation = repository.create(owners.resolve());
|
||||||
|
log.info("需求会话创建 requestId={} conversationId={}", RequestIdHolder.get(), conversation.conversationId());
|
||||||
|
return ApiResponse.success(conversation);
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping(value = "/robot-conversations/{conversationId}/attachments", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
|
||||||
|
public ApiResponse<AttachmentView> upload(@PathVariable @NotBlank String conversationId, @RequestPart("file") MultipartFile file) throws IOException {
|
||||||
|
if (file.getSize() > 8 * 1024 * 1024) throw new BizException(422, "INVALID_REQUEST", "每张图片不能超过8MiB");
|
||||||
|
DemandRepository.Attachment saved = attachments.upload(conversationId, owners.resolve(), file.getBytes(), file.getContentType());
|
||||||
|
log.info("需求图片保存 requestId={} conversationId={} attachmentId={} sizeBytes={}", RequestIdHolder.get(), conversationId, saved.attachmentId(), saved.sizeBytes());
|
||||||
|
return ApiResponse.success(new AttachmentView(saved.attachmentId(), saved.mimeType(), saved.sizeBytes(), "/api/robot-conversations/" + conversationId + "/attachments/" + saved.attachmentId()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/robot-conversations/{conversationId}/attachments/{attachmentId}")
|
||||||
|
public ResponseEntity<byte[]> image(@PathVariable @NotBlank String conversationId, @PathVariable @NotBlank String attachmentId) {
|
||||||
|
DemandRepository.Attachment file = repository.attachment(conversationId, owners.resolve(), attachmentId);
|
||||||
|
return ResponseEntity.ok().cacheControl(CacheControl.noStore()).contentType(MediaType.parseMediaType(file.mimeType()))
|
||||||
|
.header("X-Content-Type-Options", "nosniff").body(attachments.read(file));
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping(value = "/robot-conversations/{conversationId}/messages", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
|
||||||
|
public SseEmitter message(@PathVariable @NotBlank String conversationId, @Valid @RequestBody DemandMessageRequest input,
|
||||||
|
HttpServletResponse response) {
|
||||||
|
response.setHeader("Cache-Control", "no-cache"); response.setHeader("X-Accel-Buffering", "no");
|
||||||
|
return analyses.submit(conversationId, owners.resolve(), input);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/robot-analyses/{analysisId}")
|
||||||
|
public ApiResponse<DemandAnalysisService.AnalysisView> analysis(@PathVariable @NotBlank String analysisId, HttpServletResponse response) {
|
||||||
|
response.setHeader("Cache-Control", "no-store");
|
||||||
|
return ApiResponse.success(analyses.get(analysisId, owners.resolve()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping(value = "/robot-analyses/{analysisId}/retry", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
|
||||||
|
public SseEmitter retry(@PathVariable @NotBlank String analysisId, HttpServletResponse response) {
|
||||||
|
response.setHeader("Cache-Control", "no-cache"); response.setHeader("X-Accel-Buffering", "no");
|
||||||
|
return analyses.retry(analysisId, owners.resolve());
|
||||||
|
}
|
||||||
|
|
||||||
|
@DeleteMapping("/robot-analyses/{analysisId}")
|
||||||
|
public ApiResponse<DemandAnalysisService.AnalysisView> cancel(@PathVariable @NotBlank String analysisId) {
|
||||||
|
return ApiResponse.success(analyses.cancel(analysisId, owners.resolve()));
|
||||||
|
}
|
||||||
|
|
||||||
|
public record AttachmentView(String attachmentId, String mimeType, long sizeBytes, String previewUrl) { }
|
||||||
|
}
|
||||||
+110
@@ -0,0 +1,110 @@
|
|||||||
|
package com.linkerbot.cadworld.api.controller;
|
||||||
|
|
||||||
|
import com.linkerbot.cadworld.common.api.ApiResponse;
|
||||||
|
import com.linkerbot.cadworld.common.api.PageResponse;
|
||||||
|
import com.linkerbot.cadworld.common.exception.BizException;
|
||||||
|
import com.linkerbot.cadworld.dto.common.SuccessResponse;
|
||||||
|
import com.linkerbot.cadworld.dto.project.CreateProjectRequest;
|
||||||
|
import com.linkerbot.cadworld.dto.project.ProjectResponse;
|
||||||
|
import com.linkerbot.cadworld.dto.project.UpdateProjectRequest;
|
||||||
|
import com.linkerbot.cadworld.security.api.CurrentUser;
|
||||||
|
import com.linkerbot.cadworld.service.project.ProjectCoverStore;
|
||||||
|
import com.linkerbot.cadworld.service.project.ProjectService;
|
||||||
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
|
import jakarta.validation.Valid;
|
||||||
|
import jakarta.validation.constraints.NotBlank;
|
||||||
|
import jakarta.validation.constraints.Size;
|
||||||
|
import java.io.IOException;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.http.HttpHeaders;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.validation.annotation.Validated;
|
||||||
|
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||||
|
import org.springframework.web.bind.annotation.PatchMapping;
|
||||||
|
import org.springframework.web.bind.annotation.PathVariable;
|
||||||
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestBody;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestParam;
|
||||||
|
import org.springframework.web.bind.annotation.RequestPart;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api")
|
||||||
|
@Validated
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class RobotProjectController {
|
||||||
|
private final ProjectService projects;
|
||||||
|
private final DemandOwner demandOwners;
|
||||||
|
|
||||||
|
@ModelAttribute
|
||||||
|
public void disableCaching(HttpServletResponse response) {
|
||||||
|
response.setHeader(HttpHeaders.CACHE_CONTROL, "no-store");
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/projects")
|
||||||
|
public ApiResponse<ProjectResponse> create(@Valid @RequestBody CreateProjectRequest request) {
|
||||||
|
return ApiResponse.success(projects.create(CurrentUser.required(), demandOwners.resolve(), request));
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/projects")
|
||||||
|
public ApiResponse<PageResponse<ProjectResponse>> mine(@RequestParam(defaultValue = "1") long page,
|
||||||
|
@RequestParam(defaultValue = "20") long size) {
|
||||||
|
return ApiResponse.success(projects.list(CurrentUser.required(), page, size));
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/projects/{projectCode}")
|
||||||
|
public ApiResponse<ProjectResponse> detail(@PathVariable @NotBlank @Size(max = 64) String projectCode) {
|
||||||
|
return ApiResponse.success(projects.owned(projectCode, CurrentUser.required()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@PatchMapping("/projects/{projectCode}")
|
||||||
|
public ApiResponse<ProjectResponse> update(@PathVariable @NotBlank @Size(max = 64) String projectCode,
|
||||||
|
@Valid @RequestBody UpdateProjectRequest request) {
|
||||||
|
return ApiResponse.success(projects.update(projectCode, CurrentUser.required(), request));
|
||||||
|
}
|
||||||
|
|
||||||
|
@DeleteMapping("/projects/{projectCode}")
|
||||||
|
public ApiResponse<SuccessResponse> delete(@PathVariable @NotBlank @Size(max = 64) String projectCode) {
|
||||||
|
projects.delete(projectCode, CurrentUser.required());
|
||||||
|
return ApiResponse.success(SuccessResponse.ok());
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping(value = "/projects/{projectCode}/cover", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
|
||||||
|
public ApiResponse<ProjectResponse> cover(@PathVariable @NotBlank @Size(max = 64) String projectCode,
|
||||||
|
@RequestPart("file") MultipartFile file) throws IOException {
|
||||||
|
if (file.getSize() > ProjectCoverStore.MAX_BYTES) {
|
||||||
|
throw new BizException(413, "UPLOAD_TOO_LARGE", "封面图片不能超过8MiB");
|
||||||
|
}
|
||||||
|
return ApiResponse.success(projects.uploadCover(projectCode, CurrentUser.required(), file.getBytes(), file.getContentType()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/projects/{projectCode}/publish")
|
||||||
|
public ApiResponse<ProjectResponse> publish(@PathVariable @NotBlank @Size(max = 64) String projectCode) {
|
||||||
|
return ApiResponse.success(projects.visibility(projectCode, CurrentUser.required(), true));
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/projects/{projectCode}/unpublish")
|
||||||
|
public ApiResponse<ProjectResponse> unpublish(@PathVariable @NotBlank @Size(max = 64) String projectCode) {
|
||||||
|
return ApiResponse.success(projects.visibility(projectCode, CurrentUser.required(), false));
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/plaza/projects")
|
||||||
|
public ApiResponse<PageResponse<ProjectResponse>> plaza(@RequestParam(defaultValue = "1") long page,
|
||||||
|
@RequestParam(defaultValue = "20") long size) {
|
||||||
|
return ApiResponse.success(projects.list(null, page, size));
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/plaza/projects/{projectCode}")
|
||||||
|
public ApiResponse<ProjectResponse> published(@PathVariable @NotBlank @Size(max = 64) String projectCode) {
|
||||||
|
return ApiResponse.success(projects.published(projectCode));
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/plaza/projects/{projectCode}/fork")
|
||||||
|
public ApiResponse<ProjectResponse> fork(@PathVariable @NotBlank @Size(max = 64) String projectCode) {
|
||||||
|
return ApiResponse.success(projects.fork(projectCode, CurrentUser.required()));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
spring:
|
||||||
|
datasource:
|
||||||
|
url: ${APP_DB_URL}
|
||||||
|
username: ${APP_DB_USERNAME}
|
||||||
|
password: ${APP_DB_PASSWORD}
|
||||||
|
driver-class-name: com.mysql.cj.jdbc.Driver
|
||||||
|
hikari:
|
||||||
|
pool-name: CadworldApiHikariCP
|
||||||
|
minimum-idle: 1
|
||||||
|
maximum-pool-size: 20
|
||||||
|
connection-timeout: 5000
|
||||||
|
|
||||||
|
app:
|
||||||
|
demand:
|
||||||
|
secure-cookie: true
|
||||||
|
allowed-origins: ${APP_DEMAND_ALLOWED_ORIGINS:https://cadworld.robotquan.com}
|
||||||
|
storage:
|
||||||
|
root-prefix: ${OSS_ROOT_PREFIX:cadworld}
|
||||||
|
# 生产环境必须配置公开 OSS/CDN 域名,供前端直接加载模型。
|
||||||
|
public-base-url: ${APP_STORAGE_PUBLIC_BASE_URL}
|
||||||
|
|
||||||
|
logging:
|
||||||
|
level:
|
||||||
|
com.linkerbot.cadworld: INFO
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
spring:
|
||||||
|
datasource:
|
||||||
|
# 优先使用与管理端一致的 APP_DB_*,兼容原有 DB_* 环境变量。
|
||||||
|
url: ${APP_DB_URL:${DB_URL:jdbc:mysql://39.105.93.138:3306/cadworld?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai}}
|
||||||
|
username: ${APP_DB_USERNAME:${DB_USERNAME:}}
|
||||||
|
password: ${APP_DB_PASSWORD:${DB_PASSWORD:}}
|
||||||
|
driver-class-name: com.mysql.cj.jdbc.Driver
|
||||||
|
hikari:
|
||||||
|
pool-name: CadworldApiHikariCP
|
||||||
|
minimum-idle: 1
|
||||||
|
maximum-pool-size: 10
|
||||||
|
connection-timeout: 5000
|
||||||
|
|
||||||
|
app:
|
||||||
|
demand:
|
||||||
|
# Origin 必须包含协议;可用逗号分隔的完整来源覆盖。
|
||||||
|
allowed-origins: ${APP_DEMAND_ALLOWED_ORIGINS:https://dev-cadworld.robotquan.com}
|
||||||
|
storage:
|
||||||
|
root-prefix: ${OSS_ROOT_PREFIX:cadworld_dev}
|
||||||
|
|
||||||
|
logging:
|
||||||
|
level:
|
||||||
|
com.linkerbot.cadworld: DEBUG
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
spring:
|
||||||
|
application:
|
||||||
|
name: cadworld-api
|
||||||
|
profiles:
|
||||||
|
default: test
|
||||||
|
sql:
|
||||||
|
init:
|
||||||
|
mode: never
|
||||||
|
jackson:
|
||||||
|
deserialization:
|
||||||
|
fail-on-unknown-properties: true
|
||||||
|
servlet:
|
||||||
|
multipart:
|
||||||
|
max-file-size: 8MB
|
||||||
|
max-request-size: 9MB
|
||||||
|
server:
|
||||||
|
port: ${SERVER_PORT:8991}
|
||||||
|
logging:
|
||||||
|
level:
|
||||||
|
root: INFO
|
||||||
|
# 测试环境开启项目 DEBUG 时,仍不输出 SQL 参数或完整请求内容。
|
||||||
|
com.linkerbot.cadworld.mapper: INFO
|
||||||
|
org.springframework.web: INFO
|
||||||
|
mybatis-plus:
|
||||||
|
configuration:
|
||||||
|
map-underscore-to-camel-case: true
|
||||||
|
app:
|
||||||
|
auth:
|
||||||
|
captcha-ttl: ${APP_AUTH_CAPTCHA_TTL:PT2M}
|
||||||
|
token-ttl: ${APP_AUTH_TOKEN_TTL:PT24H}
|
||||||
|
demand:
|
||||||
|
api-key: ${ARK_API_KEY:}
|
||||||
|
model: ${ARK_MODEL:doubao-seed-2-1-lite-260915}
|
||||||
|
endpoint: ${ARK_ENDPOINT:https://ark.cn-beijing.volces.com/api/v3/responses}
|
||||||
|
timeout: ${APP_DEMAND_TIMEOUT:PT3M}
|
||||||
|
attachment-directory: ${APP_DEMAND_ATTACHMENT_DIRECTORY:/data/cadworld/demand-attachments}
|
||||||
|
retention: ${APP_DEMAND_RETENTION:P7D}
|
||||||
|
concurrent-analyses: ${APP_DEMAND_CONCURRENT_ANALYSES:4}
|
||||||
|
allowed-origins: ${APP_DEMAND_ALLOWED_ORIGINS:}
|
||||||
|
storage:
|
||||||
|
# 配置公开 OSS/CDN 域名,不能填管理端下载代理地址;组件访问 URL 在响应时补全环境根目录。
|
||||||
|
public-base-url: ${APP_STORAGE_PUBLIC_BASE_URL:}
|
||||||
|
oss:
|
||||||
|
access-key-id: ${OSS_ACCESS_KEY_ID:}
|
||||||
|
access-key-secret: ${OSS_ACCESS_KEY_SECRET:}
|
||||||
|
region: ${OSS_REGION:oss-cn-beijing}
|
||||||
|
bucket: ${OSS_BUCKET:linkerbot}
|
||||||
|
matching:
|
||||||
|
candidates-per-role: 50
|
||||||
|
preferred-candidates-per-role: 30
|
||||||
|
beam-width: 128
|
||||||
|
max-state-expansions: 50000
|
||||||
|
# 可追加或覆盖同义词组,例如:
|
||||||
|
# synonyms:
|
||||||
|
# "[跑步]": [奔跑, 跑动, running]
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
package com.linkerbot.cadworld.api;
|
||||||
|
|
||||||
|
import com.linkerbot.cadworld.security.common.TokenService;
|
||||||
|
import com.linkerbot.cadworld.service.auth.LoginUserService;
|
||||||
|
import java.util.UUID;
|
||||||
|
import org.springframework.jdbc.core.JdbcTemplate;
|
||||||
|
|
||||||
|
final class ApiAuthTestSupport {
|
||||||
|
private ApiAuthTestSupport() {
|
||||||
|
}
|
||||||
|
|
||||||
|
static void createSchema(JdbcTemplate jdbc) {
|
||||||
|
jdbc.execute("""
|
||||||
|
CREATE TABLE IF NOT EXISTS sys_user (
|
||||||
|
id BIGINT AUTO_INCREMENT PRIMARY KEY,
|
||||||
|
user_code CHAR(32) NOT NULL UNIQUE,
|
||||||
|
email VARCHAR(254) NOT NULL UNIQUE,
|
||||||
|
nickname VARCHAR(64) NOT NULL DEFAULT '',
|
||||||
|
status VARCHAR(32) NOT NULL DEFAULT 'ACTIVE',
|
||||||
|
user_type VARCHAR(32) NOT NULL DEFAULT 'NORMAL',
|
||||||
|
created_at TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
updated_at TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP)
|
||||||
|
""");
|
||||||
|
jdbc.update("DELETE FROM sys_user");
|
||||||
|
}
|
||||||
|
|
||||||
|
static String token(LoginUserService users, TokenService tokens) {
|
||||||
|
return tokens.issue(users.login(UUID.randomUUID() + "@example.test").getUserCode());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,247 @@
|
|||||||
|
package com.linkerbot.cadworld.api;
|
||||||
|
|
||||||
|
import ch.qos.logback.classic.Logger;
|
||||||
|
import ch.qos.logback.classic.spi.ILoggingEvent;
|
||||||
|
import ch.qos.logback.core.read.ListAppender;
|
||||||
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import com.linkerbot.cadworld.security.common.AuthProperties;
|
||||||
|
import com.linkerbot.cadworld.security.common.CaptchaService;
|
||||||
|
import com.linkerbot.cadworld.service.auth.LoginUserService;
|
||||||
|
import jakarta.servlet.http.Cookie;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.concurrent.CountDownLatch;
|
||||||
|
import java.util.concurrent.ExecutorService;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.concurrent.Future;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.boot.test.context.TestConfiguration;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Import;
|
||||||
|
import org.springframework.context.annotation.Primary;
|
||||||
|
import org.springframework.dao.DataAccessResourceFailureException;
|
||||||
|
import org.springframework.http.HttpHeaders;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.jdbc.core.JdbcTemplate;
|
||||||
|
import org.springframework.test.context.bean.override.mockito.MockitoSpyBean;
|
||||||
|
import org.springframework.test.web.servlet.MockMvc;
|
||||||
|
import org.springframework.test.web.servlet.MvcResult;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.mockito.Mockito.doThrow;
|
||||||
|
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
|
||||||
|
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||||
|
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.options;
|
||||||
|
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||||
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
|
||||||
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||||
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||||
|
|
||||||
|
@SpringBootTest(classes = ApiApplication.class, properties = {
|
||||||
|
"spring.datasource.url=jdbc:h2:mem:auth;MODE=MySQL;DB_CLOSE_DELAY=-1",
|
||||||
|
"spring.datasource.driver-class-name=org.h2.Driver", "spring.datasource.username=sa", "spring.datasource.password=",
|
||||||
|
"app.storage.public-base-url=https://models.example.test", "logging.file.path=target/test-logs",
|
||||||
|
"logging.level.com.linkerbot.cadworld=DEBUG", "app.demand.allowed-origins=http://localhost:5173"
|
||||||
|
})
|
||||||
|
@AutoConfigureMockMvc(print = org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrint.NONE)
|
||||||
|
@Import(AuthApiTest.CaptchaConfiguration.class)
|
||||||
|
class AuthApiTest {
|
||||||
|
private static final String ORIGIN = "http://localhost:5173";
|
||||||
|
@Autowired private MockMvc mvc;
|
||||||
|
@Autowired private JdbcTemplate jdbc;
|
||||||
|
@Autowired private ObjectMapper json;
|
||||||
|
@MockitoSpyBean private LoginUserService users;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void prepare() {
|
||||||
|
assertThat(jdbc.execute((org.springframework.jdbc.core.ConnectionCallback<String>) connection ->
|
||||||
|
connection.getMetaData().getDatabaseProductName())).isEqualTo("H2");
|
||||||
|
ApiAuthTestSupport.createSchema(jdbc);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void firstLoginNormalizesEmailAndMeDoesNotExposeDatabaseId() throws Exception {
|
||||||
|
JsonNode first = login(" USER@EXAMPLE.TEST ");
|
||||||
|
JsonNode second = login("user@example.test");
|
||||||
|
assertThat(first.path("tokenType").asText()).isEqualTo("Bearer");
|
||||||
|
assertThat(first.path("expiresIn").asLong()).isEqualTo(86400);
|
||||||
|
assertThat(first.path("user").path("userCode").asText()).matches("[A-F0-9]{32}");
|
||||||
|
assertThat(first.path("user").path("email").asText()).isEqualTo("user@example.test");
|
||||||
|
assertThat(first.path("user").size()).isEqualTo(3);
|
||||||
|
assertThat(first.path("user")).isEqualTo(second.path("user"));
|
||||||
|
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM sys_user", Long.class)).isEqualTo(1);
|
||||||
|
mvc.perform(get("/api/users/me").header(HttpHeaders.AUTHORIZATION, bearer(first)))
|
||||||
|
.andExpect(status().isOk()).andExpect(jsonPath("$.data.id").doesNotExist())
|
||||||
|
.andExpect(jsonPath("$.data.email").value("user@example.test"))
|
||||||
|
.andExpect(jsonPath("$.data.userCode").value(first.path("user").path("userCode").asText()))
|
||||||
|
.andExpect(header().doesNotExist(HttpHeaders.SET_COOKIE));
|
||||||
|
mvc.perform(get("/api/users/me")).andExpect(status().isUnauthorized());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void wrongCaptchaIsConsumedAndInvalidInputCannotCreateUsers() throws Exception {
|
||||||
|
String code = captcha();
|
||||||
|
mvc.perform(post("/api/auth/login").contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.content(body("user@example.test", code, "WRONG")))
|
||||||
|
.andExpect(status().isBadRequest()).andExpect(jsonPath("$.code").value("CAPTCHA_INVALID"));
|
||||||
|
mvc.perform(post("/api/auth/login").contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.content(body("user@example.test", code, "ABCDE")))
|
||||||
|
.andExpect(status().isBadRequest());
|
||||||
|
for (String email : List.of("", "not-an-email", "a".repeat(255) + "@example.test")) {
|
||||||
|
mvc.perform(post("/api/auth/login").contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.content(body(email, captcha(), "ABCDE")))
|
||||||
|
.andExpect(status().isUnprocessableEntity()).andExpect(jsonPath("$.code").value("INVALID_REQUEST"));
|
||||||
|
}
|
||||||
|
mvc.perform(post("/api/auth/login").contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.content("{\"email\":\"user@example.test\",\"captchaCode\":\"x\",\"captchaAnswer\":\"ABCDE\",\"userType\":\"ADMIN\"}"))
|
||||||
|
.andExpect(status().isUnprocessableEntity());
|
||||||
|
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM sys_user", Long.class)).isZero();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void logoutRevokesOnlyCurrentSession() throws Exception {
|
||||||
|
JsonNode first = login("user@example.test");
|
||||||
|
JsonNode second = login("user@example.test");
|
||||||
|
mvc.perform(post("/api/auth/logout").header(HttpHeaders.AUTHORIZATION, bearer(first))).andExpect(status().isOk());
|
||||||
|
mvc.perform(get("/api/users/me").header(HttpHeaders.AUTHORIZATION, bearer(first)))
|
||||||
|
.andExpect(status().isUnauthorized()).andExpect(jsonPath("$.code").value("UNAUTHORIZED"));
|
||||||
|
mvc.perform(get("/api/users/me").header(HttpHeaders.AUTHORIZATION, bearer(second))).andExpect(status().isOk());
|
||||||
|
mvc.perform(post("/api/auth/logout").header(HttpHeaders.AUTHORIZATION, bearer(first))).andExpect(status().isUnauthorized());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void disablingUserRejectsLoginAndExistingTokensImmediately() throws Exception {
|
||||||
|
JsonNode user = login("user@example.test");
|
||||||
|
jdbc.update("UPDATE sys_user SET status='DISABLED'");
|
||||||
|
mvc.perform(get("/api/users/me").header(HttpHeaders.AUTHORIZATION, bearer(user)))
|
||||||
|
.andExpect(status().isUnauthorized()).andExpect(jsonPath("$.code").value("UNAUTHORIZED"));
|
||||||
|
mvc.perform(post("/api/auth/login").header(HttpHeaders.ORIGIN, ORIGIN).contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.content(body("user@example.test", captcha(), "ABCDE")))
|
||||||
|
.andExpect(status().isForbidden()).andExpect(jsonPath("$.code").value("ACCOUNT_DISABLED"))
|
||||||
|
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, ORIGIN));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void allBusinessRoutesRequireAuthenticationAndAnonymousCookieHasNoAuthority() throws Exception {
|
||||||
|
for (String path : List.of("/api/users/me", "/api/components/CW-A", "/api/robot-analyses/test",
|
||||||
|
"/api/robot-conversations/test/attachments/test")) {
|
||||||
|
mvc.perform(get(path).cookie(new Cookie("cadworld_demand_visitor", "A".repeat(43))))
|
||||||
|
.andExpect(status().isUnauthorized()).andExpect(jsonPath("$.code").value("UNAUTHORIZED"));
|
||||||
|
}
|
||||||
|
for (String path : List.of("/api/robot-matches", "/api/robot-conversations", "/api/auth/logout",
|
||||||
|
"/api/robot-conversations/test/attachments", "/api/robot-conversations/test/messages", "/api/robot-analyses/test/retry")) {
|
||||||
|
mvc.perform(post(path)).andExpect(status().isUnauthorized());
|
||||||
|
}
|
||||||
|
mvc.perform(delete("/api/robot-analyses/test")).andExpect(status().isUnauthorized());
|
||||||
|
for (String value : List.of("Bearer invalid", "Basic invalid", "Bearer ")) {
|
||||||
|
mvc.perform(get("/api/users/me").header(HttpHeaders.AUTHORIZATION, value).header("X-Request-Id", "auth-invalid"))
|
||||||
|
.andExpect(status().isUnauthorized()).andExpect(jsonPath("$.requestId").value("auth-invalid"));
|
||||||
|
}
|
||||||
|
mvc.perform(get("/api/auth/captcha").header(HttpHeaders.AUTHORIZATION, "Bearer stale"))
|
||||||
|
.andExpect(status().isOk()).andExpect(header().string(HttpHeaders.CACHE_CONTROL, "no-store"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void corsPreflightAndAuthenticationErrorsKeepCorsHeaders() throws Exception {
|
||||||
|
mvc.perform(options("/api/robot-matches").header(HttpHeaders.ORIGIN, ORIGIN)
|
||||||
|
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST")
|
||||||
|
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "authorization,content-type,x-request-id"))
|
||||||
|
.andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, ORIGIN));
|
||||||
|
mvc.perform(get("/api/users/me").header(HttpHeaders.ORIGIN, ORIGIN))
|
||||||
|
.andExpect(status().isUnauthorized()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, ORIGIN));
|
||||||
|
mvc.perform(get("/api/users/me").header(HttpHeaders.ORIGIN, ORIGIN).header(HttpHeaders.AUTHORIZATION, "Bearer invalid"))
|
||||||
|
.andExpect(status().isUnauthorized()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, ORIGIN));
|
||||||
|
mvc.perform(options("/api/robot-matches").header(HttpHeaders.ORIGIN, "https://untrusted.example")
|
||||||
|
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST"))
|
||||||
|
.andExpect(status().isForbidden()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void authenticationDatabaseFailureUsesExistingErrorEnvelope() throws Exception {
|
||||||
|
JsonNode login = login("user@example.test");
|
||||||
|
doThrow(new DataAccessResourceFailureException("test unavailable")).when(users)
|
||||||
|
.requireActive(login.path("user").path("userCode").asText());
|
||||||
|
mvc.perform(get("/api/users/me").header(HttpHeaders.AUTHORIZATION, bearer(login)).header("X-Request-Id", "auth-database"))
|
||||||
|
.andExpect(status().isServiceUnavailable()).andExpect(jsonPath("$.code").value("DATABASE_UNAVAILABLE"))
|
||||||
|
.andExpect(jsonPath("$.requestId").value("auth-database"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void concurrentFirstLoginsCreateExactlyOneUser() throws Exception {
|
||||||
|
CountDownLatch start = new CountDownLatch(1);
|
||||||
|
List<Future<String>> results = new ArrayList<>();
|
||||||
|
Set<String> codes = new HashSet<>();
|
||||||
|
try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
|
||||||
|
for (int index = 0; index < 10; index++) results.add(executor.submit(() -> {
|
||||||
|
start.await();
|
||||||
|
return users.login(" RACE@EXAMPLE.TEST ").getUserCode();
|
||||||
|
}));
|
||||||
|
start.countDown();
|
||||||
|
for (Future<String> result : results) codes.add(result.get(10, TimeUnit.SECONDS));
|
||||||
|
}
|
||||||
|
assertThat(codes).hasSize(1);
|
||||||
|
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM sys_user", Long.class)).isEqualTo(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void authenticationLogsDoNotContainCredentialsOrEmail() throws Exception {
|
||||||
|
Logger logger = (Logger) LoggerFactory.getLogger("com.linkerbot.cadworld");
|
||||||
|
ListAppender<ILoggingEvent> capture = new ListAppender<>();
|
||||||
|
capture.start();
|
||||||
|
logger.addAppender(capture);
|
||||||
|
try {
|
||||||
|
String code = captcha();
|
||||||
|
JsonNode login = data(mvc.perform(post("/api/auth/login").contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.content(body("private.email@example.test", code, "ABCDE"))).andExpect(status().isOk()).andReturn());
|
||||||
|
mvc.perform(post("/api/auth/logout").header(HttpHeaders.AUTHORIZATION, bearer(login))).andExpect(status().isOk());
|
||||||
|
mvc.perform(get("/api/users/me").header(HttpHeaders.AUTHORIZATION, "Bearer PRIVATE_TOKEN")).andExpect(status().isUnauthorized());
|
||||||
|
mvc.perform(post("/api/auth/login").contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.content(body("private.email@example.test", captcha(), "PRIVATE_ANSWER"))).andExpect(status().isBadRequest());
|
||||||
|
String logs = String.join("\n", capture.list.stream().map(ILoggingEvent::getFormattedMessage).toList());
|
||||||
|
assertThat(logs).contains("用户登录成功", "用户退出登录", "CAPTCHA_INVALID", "UNAUTHORIZED");
|
||||||
|
assertThat(logs).doesNotContain("private.email@example.test", "PRIVATE_TOKEN", "PRIVATE_ANSWER", "ABCDE",
|
||||||
|
code, login.path("token").asText(), "data:image/png;base64,");
|
||||||
|
} finally {
|
||||||
|
logger.detachAppender(capture);
|
||||||
|
capture.stop();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private String captcha() throws Exception {
|
||||||
|
return data(mvc.perform(get("/api/auth/captcha")).andExpect(status().isOk()).andReturn()).path("captchaCode").asText();
|
||||||
|
}
|
||||||
|
|
||||||
|
private JsonNode login(String email) throws Exception {
|
||||||
|
return data(mvc.perform(post("/api/auth/login").contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.content(body(email, captcha(), "abcde"))).andExpect(status().isOk())
|
||||||
|
.andExpect(header().string(HttpHeaders.CACHE_CONTROL, "no-store")).andReturn());
|
||||||
|
}
|
||||||
|
|
||||||
|
private String body(String email, String code, String answer) throws Exception {
|
||||||
|
return json.writeValueAsString(Map.of("email", email, "captchaCode", code, "captchaAnswer", answer));
|
||||||
|
}
|
||||||
|
|
||||||
|
private String bearer(JsonNode login) { return "Bearer " + login.path("token").asText(); }
|
||||||
|
private JsonNode data(MvcResult result) throws Exception { return json.readTree(result.getResponse().getContentAsByteArray()).path("data"); }
|
||||||
|
|
||||||
|
@TestConfiguration(proxyBeanMethods = false)
|
||||||
|
static class CaptchaConfiguration {
|
||||||
|
@Bean
|
||||||
|
@Primary
|
||||||
|
CaptchaService fixedAnswerCaptcha(AuthProperties properties) {
|
||||||
|
return new CaptchaService(properties) {
|
||||||
|
@Override protected String generateAnswer() { return "ABCDE"; }
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
package com.linkerbot.cadworld.api;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import org.springframework.jdbc.core.JdbcTemplate;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
final class ComponentFixtureSupport {
|
||||||
|
private ComponentFixtureSupport() { }
|
||||||
|
|
||||||
|
static void loadHexapodLibrary(JdbcTemplate jdbc, ObjectMapper json) throws Exception {
|
||||||
|
loadLibrary(jdbc, json, "hexapod-library-components.json");
|
||||||
|
}
|
||||||
|
|
||||||
|
static void loadLibrary(JdbcTemplate jdbc, ObjectMapper json, String name) throws Exception {
|
||||||
|
try (InputStream stream = ComponentFixtureSupport.class.getResourceAsStream("/fixtures/" + name)) {
|
||||||
|
assertThat(stream).isNotNull();
|
||||||
|
for (JsonNode row : json.readTree(stream)) {
|
||||||
|
jdbc.update("""
|
||||||
|
INSERT INTO component (component_code,component_name,category,description,material,mass_kg,
|
||||||
|
degrees_of_freedom,function_description,shape,size,torque_nm,bom_list,urdf_info,
|
||||||
|
step_object_key,urdf_prefix,urdf_main_object_key,urdf_files,version)
|
||||||
|
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
|
||||||
|
""", row.path("component_code").asText(), row.path("component_name").asText(), row.path("category").asText(),
|
||||||
|
row.path("description").asText(), row.path("material").asText(), row.path("mass_kg").decimalValue(),
|
||||||
|
row.path("degrees_of_freedom").asInt(), row.path("function_description").asText(), row.path("shape").asText(),
|
||||||
|
row.path("size").asText(), row.path("torque_nm").decimalValue(), row.path("bom_list").toString(), row.path("urdf_info").toString(),
|
||||||
|
row.path("step_object_key").asText(), row.path("urdf_prefix").asText(), row.path("urdf_main_object_key").asText(),
|
||||||
|
row.path("urdf_files").toString(), row.path("version").asLong());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,30 @@
|
|||||||
|
package com.linkerbot.cadworld.api;
|
||||||
|
|
||||||
|
import com.linkerbot.cadworld.api.controller.ComponentMatchingController;
|
||||||
|
import com.linkerbot.cadworld.common.exception.GlobalExceptionHandler;
|
||||||
|
import com.linkerbot.cadworld.service.matching.PublicComponentQueryService;
|
||||||
|
import com.linkerbot.cadworld.service.matching.RobotMatchingService;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.dao.DataAccessResourceFailureException;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.test.web.servlet.MockMvc;
|
||||||
|
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||||
|
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.Mockito.mock;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||||
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||||
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||||
|
|
||||||
|
class MatchingFailureTest {
|
||||||
|
@Test
|
||||||
|
void databaseFailureRemainsAnErrorInsteadOfBecomingNoMatch() throws Exception {
|
||||||
|
RobotMatchingService matching = mock(RobotMatchingService.class);
|
||||||
|
when(matching.match(any())).thenThrow(new DataAccessResourceFailureException("test database unavailable"));
|
||||||
|
MockMvc mvc = MockMvcBuilders.standaloneSetup(new ComponentMatchingController(matching, mock(PublicComponentQueryService.class)))
|
||||||
|
.setControllerAdvice(new GlobalExceptionHandler()).build();
|
||||||
|
mvc.perform(post("/api/robot-matches").contentType(MediaType.APPLICATION_JSON).content("{\"requiredParts\":[\"TORSO_0\"]}"))
|
||||||
|
.andExpect(status().isServiceUnavailable()).andExpect(jsonPath("$.code").value("DATABASE_UNAVAILABLE"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,469 @@
|
|||||||
|
package com.linkerbot.cadworld.api;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||||
|
import com.linkerbot.cadworld.common.exception.BizException;
|
||||||
|
import com.linkerbot.cadworld.dto.project.ProjectResponse;
|
||||||
|
import com.linkerbot.cadworld.entity.SysUser;
|
||||||
|
import com.linkerbot.cadworld.security.common.TokenService;
|
||||||
|
import com.linkerbot.cadworld.service.auth.LoginUserService;
|
||||||
|
import com.linkerbot.cadworld.service.client.ObjectStorageClient;
|
||||||
|
import com.linkerbot.cadworld.service.demand.DemandModelClient;
|
||||||
|
import com.linkerbot.cadworld.service.demand.DemandRepository;
|
||||||
|
import com.linkerbot.cadworld.service.project.ProjectCoverStore;
|
||||||
|
import com.linkerbot.cadworld.service.project.ProjectRepository;
|
||||||
|
import com.linkerbot.cadworld.service.project.ProjectService;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.security.MessageDigest;
|
||||||
|
import java.sql.Timestamp;
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.Base64;
|
||||||
|
import java.util.HexFormat;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.UUID;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
import java.util.concurrent.CountDownLatch;
|
||||||
|
import java.util.concurrent.ExecutorService;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.concurrent.Future;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
import java.util.concurrent.TimeoutException;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.dao.DataAccessResourceFailureException;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.jdbc.core.JdbcTemplate;
|
||||||
|
import org.springframework.mock.web.MockMultipartFile;
|
||||||
|
import org.springframework.test.context.bean.override.mockito.MockitoBean;
|
||||||
|
import org.springframework.test.context.bean.override.mockito.MockitoSpyBean;
|
||||||
|
import org.springframework.test.web.servlet.MockMvc;
|
||||||
|
import org.springframework.test.web.servlet.MvcResult;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.ArgumentMatchers.anyLong;
|
||||||
|
import static org.mockito.ArgumentMatchers.anyString;
|
||||||
|
import static org.mockito.ArgumentMatchers.eq;
|
||||||
|
import static org.mockito.Mockito.doAnswer;
|
||||||
|
import static org.mockito.Mockito.doThrow;
|
||||||
|
import static org.mockito.Mockito.never;
|
||||||
|
import static org.mockito.Mockito.verify;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
|
||||||
|
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||||
|
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart;
|
||||||
|
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch;
|
||||||
|
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||||
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
|
||||||
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||||
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||||
|
|
||||||
|
@SpringBootTest(classes = ApiApplication.class, properties = {
|
||||||
|
"spring.datasource.url=jdbc:h2:mem:projects;MODE=MySQL;DB_CLOSE_DELAY=-1;LOCK_TIMEOUT=5000",
|
||||||
|
"spring.datasource.driver-class-name=org.h2.Driver", "spring.datasource.username=sa", "spring.datasource.password=",
|
||||||
|
"app.storage.root-prefix=cadworld_dev", "app.storage.public-base-url=https://assets.example.test",
|
||||||
|
"logging.file.path=target/test-logs"
|
||||||
|
})
|
||||||
|
@AutoConfigureMockMvc(print = org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrint.NONE)
|
||||||
|
class ProjectApiTest {
|
||||||
|
private static final byte[] PNG = Base64.getDecoder().decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+j2ioAAAAASUVORK5CYII=");
|
||||||
|
@Autowired private MockMvc mvc;
|
||||||
|
@Autowired private JdbcTemplate jdbc;
|
||||||
|
@Autowired private ObjectMapper json;
|
||||||
|
@Autowired private LoginUserService users;
|
||||||
|
@Autowired private TokenService tokens;
|
||||||
|
@Autowired private DemandRepository demands;
|
||||||
|
@Autowired private ProjectService service;
|
||||||
|
@MockitoBean private DemandModelClient model;
|
||||||
|
@MockitoBean private ObjectStorageClient storage;
|
||||||
|
@MockitoSpyBean private ProjectRepository projects;
|
||||||
|
private final Map<String, byte[]> objects = new ConcurrentHashMap<>();
|
||||||
|
private String owner;
|
||||||
|
private String token;
|
||||||
|
private String other;
|
||||||
|
private String otherToken;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void prepare() throws Exception {
|
||||||
|
assertThat(jdbc.execute((org.springframework.jdbc.core.ConnectionCallback<String>) connection -> connection.getMetaData().getDatabaseProductName())).isEqualTo("H2");
|
||||||
|
ApiAuthTestSupport.createSchema(jdbc);
|
||||||
|
jdbc.execute("""
|
||||||
|
CREATE TABLE IF NOT EXISTS robot_project (
|
||||||
|
id BIGINT AUTO_INCREMENT PRIMARY KEY,project_code VARCHAR(64) NOT NULL UNIQUE,
|
||||||
|
owner_user_code CHAR(32) NOT NULL,project_name VARCHAR(128) NOT NULL,description VARCHAR(2000) NOT NULL,
|
||||||
|
cover_relative_path VARCHAR(512),snapshot_json CLOB NOT NULL,schema_version VARCHAR(32) NOT NULL,
|
||||||
|
match_status VARCHAR(16) NOT NULL,assembly_status VARCHAR(16) NOT NULL,source_analysis_code VARCHAR(64),
|
||||||
|
source_project_code VARCHAR(64),visibility VARCHAR(16) NOT NULL,published_at TIMESTAMP(3),
|
||||||
|
deleted INT NOT NULL DEFAULT 0,created_at TIMESTAMP(3) NOT NULL,updated_at TIMESTAMP(3) NOT NULL)
|
||||||
|
""");
|
||||||
|
jdbc.execute("CREATE TABLE IF NOT EXISTS robot_demand_conversation (id BIGINT AUTO_INCREMENT PRIMARY KEY,conversation_code VARCHAR(64) NOT NULL UNIQUE,owner_hash VARCHAR(64) NOT NULL,revision INT NOT NULL,created_at TIMESTAMP NOT NULL,updated_at TIMESTAMP NOT NULL,expires_at TIMESTAMP NOT NULL)");
|
||||||
|
jdbc.execute("CREATE TABLE IF NOT EXISTS robot_demand_analysis (id BIGINT AUTO_INCREMENT PRIMARY KEY,analysis_code VARCHAR(64) NOT NULL UNIQUE,conversation_code VARCHAR(64) NOT NULL,source_message_code VARCHAR(80) NOT NULL,revision INT NOT NULL,status VARCHAR(32) NOT NULL,result_json CLOB NOT NULL,model_version VARCHAR(128) NOT NULL,failure_code VARCHAR(64) NOT NULL,created_at TIMESTAMP NOT NULL,updated_at TIMESTAMP NOT NULL)");
|
||||||
|
jdbc.execute("CREATE TABLE IF NOT EXISTS robot_demand_match (id BIGINT AUTO_INCREMENT PRIMARY KEY,match_code VARCHAR(64) NOT NULL UNIQUE,analysis_code VARCHAR(64) NOT NULL UNIQUE,revision INT NOT NULL,result_json CLOB NOT NULL,degradation_accepted INT NOT NULL,created_at TIMESTAMP NOT NULL,updated_at TIMESTAMP NOT NULL)");
|
||||||
|
jdbc.execute("CREATE TABLE IF NOT EXISTS robot_demand_attachment (attachment_code VARCHAR(64),conversation_code VARCHAR(64))");
|
||||||
|
jdbc.execute("CREATE TABLE IF NOT EXISTS robot_demand_message (conversation_code VARCHAR(64))");
|
||||||
|
for (String table : List.of("robot_project", "robot_demand_match", "robot_demand_analysis", "robot_demand_attachment", "robot_demand_message", "robot_demand_conversation")) {
|
||||||
|
jdbc.update("DELETE FROM " + table);
|
||||||
|
}
|
||||||
|
SysUser first = users.login("project-owner@example.test");
|
||||||
|
SysUser second = users.login("project-other@example.test");
|
||||||
|
owner = first.getUserCode();
|
||||||
|
other = second.getUserCode();
|
||||||
|
token = tokens.issue(owner);
|
||||||
|
otherToken = tokens.issue(other);
|
||||||
|
objects.clear();
|
||||||
|
mockUploads();
|
||||||
|
when(storage.objectExists(anyString())).thenAnswer(invocation -> objects.containsKey(invocation.getArgument(0, String.class)));
|
||||||
|
doAnswer(invocation -> { objects.remove(invocation.getArgument(0, String.class)); return null; }).when(storage).deleteObject(anyString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void savesIndependentSanitizedSnapshotAndDoesNotLoadSnapshotsForLists() throws Exception {
|
||||||
|
String analysis = source(false);
|
||||||
|
JsonNode created = create(analysis);
|
||||||
|
String code = created.path("projectCode").asText();
|
||||||
|
assertThat(created.path("visibility").asText()).isEqualTo("PRIVATE");
|
||||||
|
assertThat(created.path("schemaVersion").asText()).isEqualTo("project-v1");
|
||||||
|
assertThat(created.path("ownerUserCode").asText()).isEqualTo(owner);
|
||||||
|
assertThat(created.path("snapshot").path("components").get(0).path("component").path("version").asInt()).isEqualTo(3);
|
||||||
|
assertThat(created.path("snapshot").path("assembly").path("connections").isArray()).isTrue();
|
||||||
|
assertThat(created.findValues("id")).isEmpty();
|
||||||
|
assertThat(created.toString()).doesNotContain("PRIVATE_PROMPT", "PRIVATE_KEY", "analysisId", "conversationId", "alternatives", "sourceAnalysisCode");
|
||||||
|
assertThat(jdbc.queryForObject("SELECT source_analysis_code FROM robot_project WHERE project_code=?", String.class, code)).isEqualTo(analysis);
|
||||||
|
JsonNode listed = data(mvc.perform(get("/api/projects").header("Authorization", bearer(token)))
|
||||||
|
.andExpect(status().isOk()).andExpect(header().string("Cache-Control", "no-store"))
|
||||||
|
.andExpect(jsonPath("$.data.total").value(1)).andExpect(jsonPath("$.data.size").value(20))
|
||||||
|
.andExpect(jsonPath("$.data.items[0].snapshot").doesNotExist()).andReturn());
|
||||||
|
assertThat(listed.path("items").get(0).has("id")).isFalse();
|
||||||
|
jdbc.update("UPDATE robot_demand_conversation SET expires_at=?", Timestamp.from(Instant.now().minusSeconds(10)));
|
||||||
|
assertThat(demands.purgeExpired(attachment -> { })).isEqualTo(1);
|
||||||
|
JsonNode detail = data(mvc.perform(get("/api/projects/" + code).header("Authorization", bearer(token))).andExpect(status().isOk()).andReturn());
|
||||||
|
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();
|
||||||
|
mvc.perform(get("/api/projects")).andExpect(status().isUnauthorized());
|
||||||
|
mvc.perform(post("/api/projects").contentType(MediaType.APPLICATION_JSON).content("{}" )).andExpect(status().isUnauthorized());
|
||||||
|
mvc.perform(get("/api/projects/" + code)).andExpect(status().isUnauthorized());
|
||||||
|
mvc.perform(patch("/api/projects/" + code).contentType(MediaType.APPLICATION_JSON).content("{}" )).andExpect(status().isUnauthorized());
|
||||||
|
mvc.perform(delete("/api/projects/" + code)).andExpect(status().isUnauthorized());
|
||||||
|
mvc.perform(multipart("/api/projects/" + code + "/cover").file(image(PNG, "image/png"))).andExpect(status().isUnauthorized());
|
||||||
|
for (String action : List.of("publish", "unpublish")) {
|
||||||
|
mvc.perform(post("/api/projects/" + code + "/" + action)).andExpect(status().isUnauthorized());
|
||||||
|
mvc.perform(post("/api/projects/" + code + "/" + action).header("Authorization", bearer(otherToken))).andExpect(status().isNotFound());
|
||||||
|
}
|
||||||
|
mvc.perform(post("/api/plaza/projects/" + code + "/fork")).andExpect(status().isUnauthorized());
|
||||||
|
mvc.perform(get("/api/projects/" + code).header("Authorization", bearer(otherToken))).andExpect(status().isNotFound());
|
||||||
|
mvc.perform(patch("/api/projects/" + code).header("Authorization", bearer(otherToken)).contentType(MediaType.APPLICATION_JSON).content("{\"description\":\"改\"}" )).andExpect(status().isNotFound());
|
||||||
|
mvc.perform(delete("/api/projects/" + code).header("Authorization", bearer(otherToken))).andExpect(status().isNotFound());
|
||||||
|
mvc.perform(multipart("/api/projects/" + code + "/cover").file(image(PNG, "image/png")).header("Authorization", bearer(otherToken))).andExpect(status().isNotFound());
|
||||||
|
mvc.perform(get("/api/plaza/projects/" + code)).andExpect(status().isNotFound());
|
||||||
|
mvc.perform(post("/api/plaza/projects/" + code + "/fork").header("Authorization", bearer(otherToken))).andExpect(status().isNotFound());
|
||||||
|
mvc.perform(get("/api/projects").header("Authorization", bearer(otherToken))).andExpect(jsonPath("$.data.total").value(0));
|
||||||
|
mvc.perform(get("/api/plaza/projects")).andExpect(status().isOk()).andExpect(jsonPath("$.data.total").value(0));
|
||||||
|
verify(storage, never()).putObject(anyString(), anyString(), any(), anyLong());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void publishesPartialProjectsAndForkKeepsSnapshotAndOriginalCover() throws Exception {
|
||||||
|
String code = create(source(true)).path("projectCode").asText();
|
||||||
|
mvc.perform(post("/api/projects/" + code + "/publish").header("Authorization", bearer(token)))
|
||||||
|
.andExpect(status().isConflict()).andExpect(jsonPath("$.code").value("PROJECT_COVER_REQUIRED"));
|
||||||
|
JsonNode cover = upload(code, PNG, "image/png");
|
||||||
|
String relative = cover.path("coverRelativePath").asText();
|
||||||
|
assertThat(relative).matches("projects/RP-[a-f0-9]{32}/covers/[a-f0-9]{32}\\.png");
|
||||||
|
assertThat(relative).doesNotContain("cadworld_dev", "https:");
|
||||||
|
assertThat(cover.path("coverUrl").asText()).isEqualTo("https://assets.example.test/cadworld_dev/" + relative);
|
||||||
|
assertThat(objects).containsKey("cadworld_dev/" + relative);
|
||||||
|
JsonNode published = publish(code);
|
||||||
|
assertThat(published.path("matchStatus").asText()).isEqualTo("partial");
|
||||||
|
assertThat(published.path("snapshot").path("missingParts").size()).isEqualTo(1);
|
||||||
|
assertThat(publish(code).path("publishedAt")).isEqualTo(published.path("publishedAt"));
|
||||||
|
mvc.perform(get("/api/plaza/projects")).andExpect(status().isOk()).andExpect(header().string("Cache-Control", "no-store"))
|
||||||
|
.andExpect(jsonPath("$.data.items[0].projectCode").value(code)).andExpect(jsonPath("$.data.items[0].snapshot").doesNotExist());
|
||||||
|
mvc.perform(get("/api/plaza/projects/" + code)).andExpect(status().isOk()).andExpect(header().string("Cache-Control", "no-store"));
|
||||||
|
JsonNode fork = data(mvc.perform(post("/api/plaza/projects/" + code + "/fork").header("Authorization", bearer(otherToken)))
|
||||||
|
.andExpect(status().isOk()).andReturn());
|
||||||
|
String forkCode = fork.path("projectCode").asText();
|
||||||
|
assertThat(forkCode).isNotEqualTo(code);
|
||||||
|
assertThat(fork.path("ownerUserCode").asText()).isEqualTo(other);
|
||||||
|
assertThat(fork.path("sourceProjectCode").asText()).isEqualTo(code);
|
||||||
|
assertThat(fork.path("snapshot")).isEqualTo(published.path("snapshot"));
|
||||||
|
assertThat(fork.path("coverRelativePath").asText()).isEqualTo(relative);
|
||||||
|
assertThat(fork.path("visibility").asText()).isEqualTo("PRIVATE");
|
||||||
|
assertThat(upload(code, PNG, "image/png").path("coverRelativePath").asText()).isNotEqualTo(relative);
|
||||||
|
mvc.perform(post("/api/projects/" + code + "/unpublish").header("Authorization", bearer(token))).andExpect(status().isOk()).andExpect(jsonPath("$.data.publishedAt").isEmpty());
|
||||||
|
mvc.perform(get("/api/plaza/projects/" + code)).andExpect(status().isNotFound());
|
||||||
|
mvc.perform(post("/api/plaza/projects/" + code + "/fork").header("Authorization", bearer(otherToken))).andExpect(status().isNotFound());
|
||||||
|
mvc.perform(delete("/api/projects/" + code).header("Authorization", bearer(token))).andExpect(status().isOk());
|
||||||
|
mvc.perform(get("/api/projects/" + code).header("Authorization", bearer(token))).andExpect(status().isNotFound());
|
||||||
|
mvc.perform(post("/api/projects/" + forkCode + "/publish").header("Authorization", bearer(otherToken))).andExpect(status().isOk());
|
||||||
|
JsonNode independent = data(mvc.perform(get("/api/projects/" + forkCode).header("Authorization", bearer(otherToken))).andExpect(status().isOk()).andReturn());
|
||||||
|
assertThat(independent.path("snapshot")).isEqualTo(fork.path("snapshot"));
|
||||||
|
assertThat(independent.path("coverRelativePath").asText()).isEqualTo(relative);
|
||||||
|
assertThat(objects).hasSize(2);
|
||||||
|
verify(storage, never()).deleteObject(anyString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void validatesMetadataRejectsSnapshotEditingAndSortsPagesStably() throws Exception {
|
||||||
|
String analysis = source(false);
|
||||||
|
for (int index = 0; index < 3; index++) create(analysis);
|
||||||
|
List<String> codes = jdbc.queryForList("SELECT project_code FROM robot_project ORDER BY project_code DESC", String.class);
|
||||||
|
jdbc.update("UPDATE robot_project SET updated_at=?", Timestamp.from(Instant.parse("2026-01-01T00:00:00Z")));
|
||||||
|
mvc.perform(get("/api/projects").param("page", "2").param("size", "1").header("Authorization", bearer(token)))
|
||||||
|
.andExpect(status().isOk()).andExpect(jsonPath("$.data.total").value(3)).andExpect(jsonPath("$.data.items[0].projectCode").value(codes.get(1)));
|
||||||
|
String code = codes.get(0);
|
||||||
|
mvc.perform(patch("/api/projects/" + code).header("Authorization", bearer(token)).contentType(MediaType.APPLICATION_JSON).content("{\"description\":\"新简介\"}"))
|
||||||
|
.andExpect(status().isOk()).andExpect(jsonPath("$.data.projectName").value("我的机器人")).andExpect(jsonPath("$.data.description").value("新简介"));
|
||||||
|
mvc.perform(patch("/api/projects/" + code).header("Authorization", bearer(token)).contentType(MediaType.APPLICATION_JSON).content("{\"projectName\":\"新名称\",\"description\":\"\"}"))
|
||||||
|
.andExpect(status().isOk()).andExpect(jsonPath("$.data.projectName").value("新名称")).andExpect(jsonPath("$.data.description").value(""));
|
||||||
|
for (String content : List.of("{\"projectName\":\" \"}", "{\"snapshot\":{}}", "{\"coverRelativePath\":\"projects/other.png\"}", "{\"visibility\":\"PUBLIC\"}", "{\"ownerUserCode\":\"other\"}", "{\"description\":\"" + "a".repeat(2001) + "\"}")) {
|
||||||
|
mvc.perform(patch("/api/projects/" + code).header("Authorization", bearer(token)).contentType(MediaType.APPLICATION_JSON).content(content)).andExpect(status().isUnprocessableEntity());
|
||||||
|
}
|
||||||
|
mvc.perform(post("/api/projects").header("Authorization", bearer(token)).contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.content(json.writeValueAsString(Map.of("analysisCode", analysis, "projectName", "a".repeat(129))))).andExpect(status().isUnprocessableEntity());
|
||||||
|
for (String page : List.of("0", "-1", String.valueOf(Long.MAX_VALUE))) {
|
||||||
|
mvc.perform(get("/api/plaza/projects").param("page", page)).andExpect(status().isUnprocessableEntity());
|
||||||
|
}
|
||||||
|
for (String size : List.of("0", "101", "-1")) {
|
||||||
|
mvc.perform(get("/api/plaza/projects").param("size", size)).andExpect(status().isUnprocessableEntity());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void rejectsUnfinishedExpiredForeignSupersededAndUnpreviewableSources() throws Exception {
|
||||||
|
String analysis = source(false);
|
||||||
|
mvc.perform(createRequest(analysis, otherToken)).andExpect(status().isNotFound());
|
||||||
|
mvc.perform(createRequest("DN-missing", token)).andExpect(status().isNotFound());
|
||||||
|
for (String state : List.of("processing", "failed", "cancelled", "superseded", "needs_clarification")) {
|
||||||
|
jdbc.update("UPDATE robot_demand_analysis SET status=? WHERE analysis_code=?", state, analysis);
|
||||||
|
mvc.perform(createRequest(analysis, token)).andExpect(status().isConflict());
|
||||||
|
}
|
||||||
|
jdbc.update("UPDATE robot_demand_analysis SET status='ready' WHERE analysis_code=?", analysis);
|
||||||
|
jdbc.update("UPDATE robot_demand_conversation SET revision=2");
|
||||||
|
mvc.perform(createRequest(analysis, token)).andExpect(status().isConflict());
|
||||||
|
jdbc.update("UPDATE robot_demand_conversation SET revision=1");
|
||||||
|
for (String invalid : List.of("no_match", "blocked", "empty")) {
|
||||||
|
ObjectNode snapshot = match(false);
|
||||||
|
if ("no_match".equals(invalid)) snapshot.put("status", "no_match");
|
||||||
|
if ("blocked".equals(invalid)) ((ObjectNode) snapshot.path("assembly")).put("status", "blocked");
|
||||||
|
if ("empty".equals(invalid)) snapshot.putArray("components");
|
||||||
|
jdbc.update("UPDATE robot_demand_match SET result_json=? WHERE analysis_code=?", json.writeValueAsString(snapshot), analysis);
|
||||||
|
mvc.perform(createRequest(analysis, token)).andExpect(status().isConflict());
|
||||||
|
}
|
||||||
|
jdbc.update("DELETE FROM robot_demand_match");
|
||||||
|
mvc.perform(createRequest(analysis, token)).andExpect(status().isConflict());
|
||||||
|
jdbc.update("UPDATE robot_demand_conversation SET expires_at=?", Timestamp.from(Instant.now().minusSeconds(10)));
|
||||||
|
mvc.perform(createRequest(analysis, token)).andExpect(status().isNotFound());
|
||||||
|
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM robot_project", Integer.class)).isZero();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void coverAcceptsOnlyBoundedImagesAndUsesServerGeneratedPaths() throws Exception {
|
||||||
|
String code = create(source(false)).path("projectCode").asText();
|
||||||
|
upload(code, PNG, "image/png");
|
||||||
|
assertThat(upload(code, new byte[] {(byte) 255, (byte) 216, (byte) 255, 0}, "image/jpeg").path("coverRelativePath").asText()).endsWith(".jpg");
|
||||||
|
String previous = upload(code, "RIFF0000WEBP".getBytes(StandardCharsets.US_ASCII), "image/webp").path("coverRelativePath").asText();
|
||||||
|
for (MockMultipartFile file : List.of(image(new byte[0], "image/png"), image("invalid".getBytes(StandardCharsets.US_ASCII), "image/png"), image(PNG, "image/jpeg"), image(PNG, "image/svg+xml"))) {
|
||||||
|
mvc.perform(multipart("/api/projects/" + code + "/cover").file(file).header("Authorization", bearer(token))).andExpect(status().isUnprocessableEntity());
|
||||||
|
}
|
||||||
|
mvc.perform(multipart("/api/projects/" + code + "/cover").file(image(new byte[(int) ProjectCoverStore.MAX_BYTES + 1], "image/png"))
|
||||||
|
.header("Authorization", bearer(token))).andExpect(status().isPayloadTooLarge());
|
||||||
|
assertThat(coverPath(code)).isEqualTo(previous);
|
||||||
|
assertThat(objects).hasSize(3);
|
||||||
|
for (String key : objects.keySet()) assertThat(key).startsWith("cadworld_dev/projects/" + code + "/covers/").doesNotContain("client-name");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void failedOssUploadPreservesOldCoverAndDatabaseFailureRollsBackAndCompensates() throws Exception {
|
||||||
|
String code = create(source(false)).path("projectCode").asText();
|
||||||
|
String previous = upload(code, PNG, "image/png").path("coverRelativePath").asText();
|
||||||
|
doThrow(new BizException(502, "OSS_UPLOAD_FAILED", "上传失败")).when(storage).putObject(anyString(), anyString(), any(), anyLong());
|
||||||
|
mvc.perform(multipart("/api/projects/" + code + "/cover").file(image(PNG, "image/png")).header("Authorization", bearer(token))).andExpect(status().isBadGateway());
|
||||||
|
assertThat(coverPath(code)).isEqualTo(previous);
|
||||||
|
mockUploads();
|
||||||
|
doAnswer(invocation -> {
|
||||||
|
invocation.callRealMethod();
|
||||||
|
throw new DataAccessResourceFailureException("simulated failure after update");
|
||||||
|
}).when(projects).updateCover(eq(code), eq(owner), anyString(), any(Instant.class));
|
||||||
|
mvc.perform(multipart("/api/projects/" + code + "/cover").file(image(PNG, "image/png")).header("Authorization", bearer(token))).andExpect(status().isServiceUnavailable());
|
||||||
|
assertThat(coverPath(code)).isEqualTo(previous);
|
||||||
|
assertThat(objects.keySet()).containsExactly("cadworld_dev/" + previous);
|
||||||
|
verify(storage).deleteObject(anyString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void deletionDuringUploadCompensatesOnlyTheNewObject() throws Exception {
|
||||||
|
String code = create(source(false)).path("projectCode").asText();
|
||||||
|
String previous = upload(code, PNG, "image/png").path("coverRelativePath").asText();
|
||||||
|
doAnswer(invocation -> {
|
||||||
|
objects.put(invocation.getArgument(0, String.class), PNG);
|
||||||
|
jdbc.update("UPDATE robot_project SET deleted=1 WHERE project_code=?", code);
|
||||||
|
return null;
|
||||||
|
}).when(storage).putObject(anyString(), anyString(), any(), anyLong());
|
||||||
|
mvc.perform(multipart("/api/projects/" + code + "/cover").file(image(PNG, "image/png")).header("Authorization", bearer(token))).andExpect(status().isNotFound());
|
||||||
|
assertThat(objects.keySet()).containsExactly("cadworld_dev/" + previous);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void compensationFailurePreservesOriginalDatabaseErrorAndPreviousCover() throws Exception {
|
||||||
|
String code = create(source(false)).path("projectCode").asText();
|
||||||
|
String previous = upload(code, PNG, "image/png").path("coverRelativePath").asText();
|
||||||
|
doThrow(new DataAccessResourceFailureException("simulated update failure"))
|
||||||
|
.when(projects).updateCover(eq(code), eq(owner), anyString(), any(Instant.class));
|
||||||
|
doThrow(new BizException(502, "OSS_DELETE_FAILED", "清理失败")).when(storage).deleteObject(anyString());
|
||||||
|
mvc.perform(multipart("/api/projects/" + code + "/cover").file(image(PNG, "image/png")).header("Authorization", bearer(token)))
|
||||||
|
.andExpect(status().isServiceUnavailable()).andExpect(jsonPath("$.code").value("DATABASE_UNAVAILABLE"));
|
||||||
|
assertThat(coverPath(code)).isEqualTo(previous);
|
||||||
|
assertThat(objects).hasSize(2);
|
||||||
|
verify(storage).deleteObject(anyString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void publishingRequiresExistingCoverAndRepublishingAssignsNewTime() throws Exception {
|
||||||
|
String code = create(source(false)).path("projectCode").asText();
|
||||||
|
String path = upload(code, PNG, "image/png").path("coverRelativePath").asText();
|
||||||
|
objects.clear();
|
||||||
|
mvc.perform(post("/api/projects/" + code + "/publish").header("Authorization", bearer(token))).andExpect(status().isConflict());
|
||||||
|
objects.put("cadworld_dev/" + path, PNG);
|
||||||
|
publish(code);
|
||||||
|
jdbc.update("UPDATE robot_project SET published_at=? WHERE project_code=?", Timestamp.from(Instant.parse("2020-01-01T00:00:00Z")), code);
|
||||||
|
assertThat(publish(code).path("publishedAt").asText()).startsWith("2020-01-01");
|
||||||
|
mvc.perform(post("/api/projects/" + code + "/unpublish").header("Authorization", bearer(token))).andExpect(status().isOk());
|
||||||
|
assertThat(publish(code).path("publishedAt").asText()).doesNotStartWith("2020-01-01");
|
||||||
|
jdbc.update("UPDATE robot_project SET snapshot_json=? WHERE project_code=?", "{}", code);
|
||||||
|
mvc.perform(post("/api/projects/" + code + "/publish").header("Authorization", bearer(token))).andExpect(status().isConflict());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void forkAndUnpublishSerializeOnSourceProjectLock() throws Exception {
|
||||||
|
String code = create(source(false)).path("projectCode").asText();
|
||||||
|
upload(code, PNG, "image/png");
|
||||||
|
publish(code);
|
||||||
|
CountDownLatch sourceLocked = new CountDownLatch(1);
|
||||||
|
CountDownLatch releaseFork = new CountDownLatch(1);
|
||||||
|
CountDownLatch unpublishAttempted = new CountDownLatch(1);
|
||||||
|
doAnswer(invocation -> {
|
||||||
|
ProjectRepository.Project project = (ProjectRepository.Project) invocation.callRealMethod();
|
||||||
|
sourceLocked.countDown();
|
||||||
|
if (!releaseFork.await(5, TimeUnit.SECONDS)) throw new IllegalStateException("fork barrier timeout");
|
||||||
|
return project;
|
||||||
|
}).when(projects).published(code, true);
|
||||||
|
doAnswer(invocation -> {
|
||||||
|
unpublishAttempted.countDown();
|
||||||
|
return invocation.callRealMethod();
|
||||||
|
}).when(projects).owned(code, owner, true);
|
||||||
|
try (ExecutorService executor = Executors.newFixedThreadPool(2)) {
|
||||||
|
Future<ProjectResponse> fork = executor.submit(() -> service.fork(code, other));
|
||||||
|
try {
|
||||||
|
assertThat(sourceLocked.await(5, TimeUnit.SECONDS)).isTrue();
|
||||||
|
Future<ProjectResponse> unpublish = executor.submit(() -> service.visibility(code, owner, false));
|
||||||
|
assertThat(unpublishAttempted.await(5, TimeUnit.SECONDS)).isTrue();
|
||||||
|
assertThatThrownBy(() -> unpublish.get(150, TimeUnit.MILLISECONDS)).isInstanceOf(TimeoutException.class);
|
||||||
|
releaseFork.countDown();
|
||||||
|
assertThat(fork.get(5, TimeUnit.SECONDS).visibility()).isEqualTo("PRIVATE");
|
||||||
|
assertThat(unpublish.get(5, TimeUnit.SECONDS).visibility()).isEqualTo("PRIVATE");
|
||||||
|
} finally {
|
||||||
|
releaseFork.countDown();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
mvc.perform(post("/api/plaza/projects/" + code + "/fork").header("Authorization", bearer(otherToken))).andExpect(status().isNotFound());
|
||||||
|
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM robot_project WHERE owner_user_code=?", Integer.class, other)).isEqualTo(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void mockUploads() {
|
||||||
|
doAnswer(invocation -> {
|
||||||
|
java.io.InputStream input = invocation.getArgument(2, java.io.InputStream.class);
|
||||||
|
objects.put(invocation.getArgument(0, String.class), input.readAllBytes());
|
||||||
|
return null;
|
||||||
|
}).when(storage).putObject(anyString(), anyString(), any(), anyLong());
|
||||||
|
}
|
||||||
|
|
||||||
|
private String source(boolean partial) throws Exception {
|
||||||
|
String conversation = "DC-" + UUID.randomUUID().toString().replace("-", "");
|
||||||
|
String analysis = "DN-" + UUID.randomUUID().toString().replace("-", "");
|
||||||
|
Timestamp now = Timestamp.from(Instant.now());
|
||||||
|
String hash = HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(("user:" + owner).getBytes(StandardCharsets.US_ASCII)));
|
||||||
|
jdbc.update("INSERT INTO robot_demand_conversation(conversation_code,owner_hash,revision,created_at,updated_at,expires_at) VALUES (?,?,1,?,?,?)", conversation, hash, now, now, Timestamp.from(Instant.now().plusSeconds(3600)));
|
||||||
|
jdbc.update("INSERT INTO robot_demand_analysis(analysis_code,conversation_code,source_message_code,revision,status,result_json,model_version,failure_code,created_at,updated_at) VALUES (?,?,'m1',1,'ready',?,'test','',?,?)", analysis, conversation, "{\"request\":{\"userInput\":\"PRIVATE_PROMPT\"}}", now, now);
|
||||||
|
jdbc.update("INSERT INTO robot_demand_match(match_code,analysis_code,revision,result_json,degradation_accepted,created_at,updated_at) VALUES (?,?,1,?,0,?,?)", "DM-" + UUID.randomUUID(), analysis, json.writeValueAsString(match(partial)), now, now);
|
||||||
|
return analysis;
|
||||||
|
}
|
||||||
|
|
||||||
|
private ObjectNode match(boolean partial) throws Exception {
|
||||||
|
ObjectNode result = (ObjectNode) json.readTree("""
|
||||||
|
{"analysisId":"DN-private","conversationId":"DC-private","snapshot":{"id":9000,"secret":"PRIVATE_KEY"},
|
||||||
|
"request":{"userInput":"PRIVATE_PROMPT"},"alternatives":[{"secret":"PRIVATE_KEY"}],
|
||||||
|
"status":"complete","rootCategory":"TORSO_0","searchLimited":false,"totals":{"massKg":1},
|
||||||
|
"components":[{"instanceId":"DM-test:TORSO_0","id":12,"snapshot":{"secret":"PRIVATE_KEY"},
|
||||||
|
"component":{"componentCode":"C-TORSO","componentName":"躯干","version":3,"id":9001,
|
||||||
|
"internalObjectKey":"PRIVATE_KEY","urdfInfo":{"rootLink":"BASE","frames":[],"id":9002}},
|
||||||
|
"urdfMainPath":"robot.urdf","resourceIssues":[],
|
||||||
|
"resources":[{"relativePath":"robot.urdf","url":"https://assets.example.test/cadworld_dev/components/robot.urdf","version":3,"expiresAt":null,"id":9003}]}],
|
||||||
|
"assembly":{"status":"ready","rootInstanceId":"DM-test:TORSO_0","connections":[],"issues":[]},
|
||||||
|
"unmetRequirements":[],"missingParts":[],"missingPartGroups":[],"requirementChecks":[]}
|
||||||
|
""");
|
||||||
|
if (partial) {
|
||||||
|
result.put("status", "partial");
|
||||||
|
result.withArray("missingParts").addObject().put("category", "ARM_R").put("missingQuantity", 1).put("reason", "NO_CANDIDATE");
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder createRequest(String analysis, String accessToken) throws Exception {
|
||||||
|
return post("/api/projects").header("Authorization", bearer(accessToken)).contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.content(json.writeValueAsString(Map.of("analysisCode", analysis, "projectName", "我的机器人", "description", "项目简介")));
|
||||||
|
}
|
||||||
|
|
||||||
|
private JsonNode create(String analysis) throws Exception {
|
||||||
|
return data(mvc.perform(createRequest(analysis, token)).andExpect(status().isOk()).andReturn());
|
||||||
|
}
|
||||||
|
|
||||||
|
private JsonNode upload(String code, byte[] bytes, String mime) throws Exception {
|
||||||
|
return data(mvc.perform(multipart("/api/projects/" + code + "/cover").file(image(bytes, mime)).header("Authorization", bearer(token)))
|
||||||
|
.andExpect(status().isOk()).andReturn());
|
||||||
|
}
|
||||||
|
|
||||||
|
private JsonNode publish(String code) throws Exception {
|
||||||
|
return data(mvc.perform(post("/api/projects/" + code + "/publish").header("Authorization", bearer(token)))
|
||||||
|
.andExpect(status().isOk()).andReturn());
|
||||||
|
}
|
||||||
|
|
||||||
|
private JsonNode data(MvcResult result) throws Exception {
|
||||||
|
return json.readTree(result.getResponse().getContentAsString()).path("data");
|
||||||
|
}
|
||||||
|
|
||||||
|
private MockMultipartFile image(byte[] bytes, String mime) {
|
||||||
|
return new MockMultipartFile("file", "../client-name.svg", mime, bytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
private String coverPath(String code) {
|
||||||
|
return jdbc.queryForObject("SELECT cover_relative_path FROM robot_project WHERE project_code=?", String.class, code);
|
||||||
|
}
|
||||||
|
|
||||||
|
private String bearer(String value) {
|
||||||
|
return "Bearer " + value;
|
||||||
|
}
|
||||||
|
}
|
||||||
+102
@@ -0,0 +1,102 @@
|
|||||||
|
package com.linkerbot.cadworld.api.config;
|
||||||
|
|
||||||
|
import com.linkerbot.cadworld.common.web.RequestIdFilter;
|
||||||
|
import com.linkerbot.cadworld.config.DemandProperties;
|
||||||
|
import java.util.List;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.params.ParameterizedTest;
|
||||||
|
import org.junit.jupiter.params.provider.CsvSource;
|
||||||
|
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||||
|
import org.springframework.boot.test.context.ConfigDataApplicationContextInitializer;
|
||||||
|
import org.springframework.boot.test.context.TestConfiguration;
|
||||||
|
import org.springframework.boot.test.context.runner.WebApplicationContextRunner;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.core.env.StandardEnvironment;
|
||||||
|
import org.springframework.http.HttpHeaders;
|
||||||
|
import org.springframework.test.web.servlet.MockMvc;
|
||||||
|
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMethod;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
|
||||||
|
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||||
|
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.options;
|
||||||
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
||||||
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
|
||||||
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||||
|
|
||||||
|
class ApiCorsConfigurationTest {
|
||||||
|
private final WebApplicationContextRunner runner = new WebApplicationContextRunner()
|
||||||
|
.withInitializer(context -> context.getEnvironment().getPropertySources()
|
||||||
|
.remove(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME))
|
||||||
|
.withInitializer(new ConfigDataApplicationContextInitializer())
|
||||||
|
.withUserConfiguration(CorsTestConfiguration.class);
|
||||||
|
|
||||||
|
@ParameterizedTest
|
||||||
|
@CsvSource({
|
||||||
|
"test, https://dev-cadworld.robotquan.com, https://cadworld.robotquan.com",
|
||||||
|
"prod, https://cadworld.robotquan.com, https://dev-cadworld.robotquan.com"
|
||||||
|
})
|
||||||
|
void profileAllowsItsFrontendAndRejectsOtherOrigins(String profile, String allowedOrigin, String otherOrigin) {
|
||||||
|
runner.withPropertyValues("spring.profiles.active=" + profile).run(context -> {
|
||||||
|
assertThat(context).hasNotFailed();
|
||||||
|
MockMvc mvc = MockMvcBuilders.webAppContextSetup(context).addFilters(new RequestIdFilter()).build();
|
||||||
|
for (String method : List.of("GET", "POST", "PATCH", "DELETE")) {
|
||||||
|
mvc.perform(options("/api/cors-probe").header(HttpHeaders.ORIGIN, allowedOrigin)
|
||||||
|
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, method)
|
||||||
|
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "content-type,x-request-id,authorization"))
|
||||||
|
.andExpect(status().isOk())
|
||||||
|
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, allowedOrigin))
|
||||||
|
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"))
|
||||||
|
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "3600"));
|
||||||
|
}
|
||||||
|
mvc.perform(get("/api/cors-probe").header(HttpHeaders.ORIGIN, allowedOrigin)
|
||||||
|
.header("X-Request-Id", "cors-test"))
|
||||||
|
.andExpect(status().isOk()).andExpect(content().string("ok"))
|
||||||
|
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, allowedOrigin))
|
||||||
|
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, "X-Request-Id"))
|
||||||
|
.andExpect(header().string("X-Request-Id", "cors-test"));
|
||||||
|
for (String origin : List.of(otherOrigin, allowedOrigin.replace("https://", "http://"), "https://untrusted.example")) {
|
||||||
|
mvc.perform(options("/api/cors-probe").header(HttpHeaders.ORIGIN, origin)
|
||||||
|
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST"))
|
||||||
|
.andExpect(status().isForbidden())
|
||||||
|
.andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
|
||||||
|
mvc.perform(get("/api/cors-probe").header(HttpHeaders.ORIGIN, origin))
|
||||||
|
.andExpect(status().isForbidden());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void environmentVariableCanOverrideWhitelistWithMultipleOrigins() {
|
||||||
|
runner.withPropertyValues("spring.profiles.active=test",
|
||||||
|
"APP_DEMAND_ALLOWED_ORIGINS=http://localhost:5173,https://custom.example").run(context -> {
|
||||||
|
assertThat(context).hasNotFailed();
|
||||||
|
MockMvc mvc = MockMvcBuilders.webAppContextSetup(context).build();
|
||||||
|
for (String origin : List.of("http://localhost:5173", "https://custom.example")) {
|
||||||
|
mvc.perform(get("/api/cors-probe").header(HttpHeaders.ORIGIN, origin))
|
||||||
|
.andExpect(status().isOk())
|
||||||
|
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, origin));
|
||||||
|
}
|
||||||
|
mvc.perform(get("/api/cors-probe").header(HttpHeaders.ORIGIN, "https://dev-cadworld.robotquan.com"))
|
||||||
|
.andExpect(status().isForbidden());
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@TestConfiguration(proxyBeanMethods = false)
|
||||||
|
@EnableWebMvc
|
||||||
|
@EnableConfigurationProperties(DemandProperties.class)
|
||||||
|
static class CorsTestConfiguration {
|
||||||
|
@Bean WebMvcConfigurer cors(DemandProperties properties) { return new DemandConfiguration().demandCors(properties); }
|
||||||
|
@Bean ProbeController probeController() { return new ProbeController(); }
|
||||||
|
}
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
static class ProbeController {
|
||||||
|
@RequestMapping(value = "/api/cors-probe", method = {RequestMethod.GET, RequestMethod.POST, RequestMethod.PATCH, RequestMethod.DELETE})
|
||||||
|
public String probe() { return "ok"; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,180 @@
|
|||||||
|
{
|
||||||
|
"summary": "当前为双足人形机器人方案,按当轮要求配置左手部件。",
|
||||||
|
"intentItems": [
|
||||||
|
{
|
||||||
|
"id": "intent-1",
|
||||||
|
"dimension": "form",
|
||||||
|
"subject": "整机",
|
||||||
|
"requirement": "为人形构型机器人",
|
||||||
|
"priority": "must",
|
||||||
|
"source": "explicit",
|
||||||
|
"evidenceIds": [
|
||||||
|
"obs-1"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "intent-2",
|
||||||
|
"dimension": "quantity",
|
||||||
|
"subject": "整机",
|
||||||
|
"requirement": "整机数量为1台",
|
||||||
|
"priority": "must",
|
||||||
|
"source": "explicit",
|
||||||
|
"evidenceIds": [
|
||||||
|
"obs-1"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "intent-3",
|
||||||
|
"dimension": "form",
|
||||||
|
"subject": "左手",
|
||||||
|
"requirement": "需配置左手部件",
|
||||||
|
"priority": "must",
|
||||||
|
"source": "explicit",
|
||||||
|
"evidenceIds": [
|
||||||
|
"obs-4"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"images": [],
|
||||||
|
"observations": [
|
||||||
|
{
|
||||||
|
"id": "obs-1",
|
||||||
|
"messageId": "m1",
|
||||||
|
"imageId": "",
|
||||||
|
"kind": "user_text",
|
||||||
|
"content": "给我一个人形机器人",
|
||||||
|
"clarity": "clear",
|
||||||
|
"region": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "obs-2",
|
||||||
|
"messageId": "m2",
|
||||||
|
"imageId": "",
|
||||||
|
"kind": "user_text",
|
||||||
|
"content": "换个头",
|
||||||
|
"clarity": "clear",
|
||||||
|
"region": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "obs-3",
|
||||||
|
"messageId": "m3",
|
||||||
|
"imageId": "",
|
||||||
|
"kind": "user_text",
|
||||||
|
"content": "换个左臂",
|
||||||
|
"clarity": "clear",
|
||||||
|
"region": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "obs-4",
|
||||||
|
"messageId": "m4",
|
||||||
|
"imageId": "",
|
||||||
|
"kind": "user_text",
|
||||||
|
"content": "加上左手",
|
||||||
|
"clarity": "clear",
|
||||||
|
"region": []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"keywords": [
|
||||||
|
{
|
||||||
|
"term": "人形机器人",
|
||||||
|
"source": "explicit",
|
||||||
|
"reason": "",
|
||||||
|
"negated": false,
|
||||||
|
"evidenceIds": [
|
||||||
|
"obs-1"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"term": "双足",
|
||||||
|
"source": "inferred",
|
||||||
|
"reason": "人形构型对应双足人形模板",
|
||||||
|
"negated": false,
|
||||||
|
"evidenceIds": [
|
||||||
|
"obs-1"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"term": "左手",
|
||||||
|
"source": "explicit",
|
||||||
|
"reason": "",
|
||||||
|
"negated": false,
|
||||||
|
"evidenceIds": [
|
||||||
|
"obs-4"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"robotTypes": [
|
||||||
|
{
|
||||||
|
"type": "biped",
|
||||||
|
"source": "inferred",
|
||||||
|
"reason": "用户要求人形机器人,采用双足人形模板",
|
||||||
|
"evidenceIds": [
|
||||||
|
"obs-1"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"partCategories": [
|
||||||
|
{
|
||||||
|
"category": "TORSO_0",
|
||||||
|
"source": "inferred",
|
||||||
|
"reason": "人形机器人需要躯干",
|
||||||
|
"evidenceIds": [
|
||||||
|
"obs-1"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"category": "HEAD_0",
|
||||||
|
"source": "inferred",
|
||||||
|
"reason": "人形机器人通常包含头部",
|
||||||
|
"evidenceIds": [
|
||||||
|
"obs-1"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"category": "WAIST_0",
|
||||||
|
"source": "inferred",
|
||||||
|
"reason": "人形机器人通常包含腰部",
|
||||||
|
"evidenceIds": [
|
||||||
|
"obs-1"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"category": "HAND_L",
|
||||||
|
"source": "explicit",
|
||||||
|
"reason": "用户明确要求加上左手",
|
||||||
|
"evidenceIds": [
|
||||||
|
"obs-4"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"excludedCategories": [],
|
||||||
|
"constraints": [
|
||||||
|
{
|
||||||
|
"scope": "robot",
|
||||||
|
"categories": [],
|
||||||
|
"field": "quantity",
|
||||||
|
"value": "1",
|
||||||
|
"upperValue": "",
|
||||||
|
"operator": "eq",
|
||||||
|
"evidenceIds": [
|
||||||
|
"obs-1"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"unmodeled": [],
|
||||||
|
"questions": [],
|
||||||
|
"operation": {
|
||||||
|
"type": "replace",
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"family": "HAND",
|
||||||
|
"side": "L",
|
||||||
|
"instanceId": "",
|
||||||
|
"ordinal": "",
|
||||||
|
"evidenceIds": [
|
||||||
|
"obs-4"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,240 @@
|
|||||||
|
{
|
||||||
|
"oldArmInfo": {
|
||||||
|
"frames": [
|
||||||
|
{
|
||||||
|
"rpy": [
|
||||||
|
1.5707963267949,
|
||||||
|
-1.5707963267949,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"xyz": [
|
||||||
|
0,
|
||||||
|
0.0145,
|
||||||
|
0.0195
|
||||||
|
],
|
||||||
|
"axis": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
-1
|
||||||
|
],
|
||||||
|
"kind": "joint",
|
||||||
|
"name": "Link1",
|
||||||
|
"type": "continuous",
|
||||||
|
"child": "Link1",
|
||||||
|
"limits": {},
|
||||||
|
"parent": "LINK_ARM_L",
|
||||||
|
"interfaceName": null,
|
||||||
|
"interfaceType": null,
|
||||||
|
"originExplicit": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"rpy": [
|
||||||
|
1.57079632679492,
|
||||||
|
1.5707963267949,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"xyz": [
|
||||||
|
0.0515000000000048,
|
||||||
|
0,
|
||||||
|
0.0144999999999986
|
||||||
|
],
|
||||||
|
"axis": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
-1
|
||||||
|
],
|
||||||
|
"kind": "joint",
|
||||||
|
"name": "LINK2",
|
||||||
|
"type": "continuous",
|
||||||
|
"child": "LINK2",
|
||||||
|
"limits": {},
|
||||||
|
"parent": "Link1",
|
||||||
|
"interfaceName": null,
|
||||||
|
"interfaceType": null,
|
||||||
|
"originExplicit": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"rpy": [
|
||||||
|
1.5707963267949,
|
||||||
|
0,
|
||||||
|
-3.14159265358979
|
||||||
|
],
|
||||||
|
"xyz": [
|
||||||
|
0,
|
||||||
|
0.019000000000001,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"axis": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
1
|
||||||
|
],
|
||||||
|
"kind": "joint",
|
||||||
|
"name": "LINK_HAND_L",
|
||||||
|
"type": "fixed",
|
||||||
|
"child": "LINK_HAND_L",
|
||||||
|
"limits": {},
|
||||||
|
"parent": "LINK2",
|
||||||
|
"interfaceName": "LINK_HAND_L",
|
||||||
|
"interfaceType": "HAND_L",
|
||||||
|
"originExplicit": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"rpy": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"xyz": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"kind": "interface",
|
||||||
|
"name": "__root_interface__",
|
||||||
|
"child": "LINK_ARM_L",
|
||||||
|
"isRoot": true,
|
||||||
|
"limits": {},
|
||||||
|
"parent": null,
|
||||||
|
"synthetic": true,
|
||||||
|
"interfaceName": "LINK_ARM_L",
|
||||||
|
"interfaceType": "ARM_L",
|
||||||
|
"originExplicit": false
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"rootLink": "LINK_ARM_L",
|
||||||
|
"robotName": "臂_L_开源八棱柱"
|
||||||
|
},
|
||||||
|
"newArmInfo": {
|
||||||
|
"frames": [
|
||||||
|
{
|
||||||
|
"rpy": [
|
||||||
|
1.5707963267949,
|
||||||
|
0,
|
||||||
|
-3.14159265358979
|
||||||
|
],
|
||||||
|
"xyz": [
|
||||||
|
0,
|
||||||
|
0.0185,
|
||||||
|
0.0224963969286362
|
||||||
|
],
|
||||||
|
"axis": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
1
|
||||||
|
],
|
||||||
|
"kind": "joint",
|
||||||
|
"name": "1_Link",
|
||||||
|
"type": "continuous",
|
||||||
|
"child": "1_Link",
|
||||||
|
"limits": {},
|
||||||
|
"parent": "LINK_ARM_L",
|
||||||
|
"interfaceName": null,
|
||||||
|
"interfaceType": null,
|
||||||
|
"originExplicit": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"rpy": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"xyz": [
|
||||||
|
-0.0575533458090581,
|
||||||
|
0.00718419196277781,
|
||||||
|
-0.00400000000000003
|
||||||
|
],
|
||||||
|
"axis": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
-1
|
||||||
|
],
|
||||||
|
"kind": "joint",
|
||||||
|
"name": "2_Link",
|
||||||
|
"type": "continuous",
|
||||||
|
"child": "2_Link",
|
||||||
|
"limits": {},
|
||||||
|
"parent": "1_Link",
|
||||||
|
"interfaceName": null,
|
||||||
|
"interfaceType": null,
|
||||||
|
"originExplicit": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"rpy": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"xyz": [
|
||||||
|
-0.0319155558910018,
|
||||||
|
-0.00232315371736215,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"axis": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
-1
|
||||||
|
],
|
||||||
|
"kind": "joint",
|
||||||
|
"name": "LINK_3",
|
||||||
|
"type": "continuous",
|
||||||
|
"child": "LINK_3",
|
||||||
|
"limits": {},
|
||||||
|
"parent": "2_Link",
|
||||||
|
"interfaceName": null,
|
||||||
|
"interfaceType": null,
|
||||||
|
"originExplicit": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"rpy": [
|
||||||
|
3.10675810549612,
|
||||||
|
1.5707963267949,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"xyz": [
|
||||||
|
-0.032480285464846,
|
||||||
|
-0.00113189392935303,
|
||||||
|
-0.01475
|
||||||
|
],
|
||||||
|
"axis": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"kind": "joint",
|
||||||
|
"name": "LINK_HAND_L",
|
||||||
|
"type": "fixed",
|
||||||
|
"child": "LINK_HAND_L",
|
||||||
|
"limits": {},
|
||||||
|
"parent": "LINK_3",
|
||||||
|
"interfaceName": "LINK_HAND_L",
|
||||||
|
"interfaceType": "HAND_L",
|
||||||
|
"originExplicit": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"rpy": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"xyz": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"kind": "interface",
|
||||||
|
"name": "__root_interface__",
|
||||||
|
"child": "LINK_ARM_L",
|
||||||
|
"isRoot": true,
|
||||||
|
"limits": {},
|
||||||
|
"parent": null,
|
||||||
|
"synthetic": true,
|
||||||
|
"interfaceName": "LINK_ARM_L",
|
||||||
|
"interfaceType": "ARM_L",
|
||||||
|
"originExplicit": false
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"rootLink": "LINK_ARM_L",
|
||||||
|
"robotName": "臂_L_臂3自由度左"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,145 @@
|
|||||||
|
{
|
||||||
|
"summary" : "基于现有双足人形机器人有效方案,替换头部部件,并单独更换左臂部件,保持其余原有构型不变",
|
||||||
|
"intentItems" : [ {
|
||||||
|
"id" : "i1",
|
||||||
|
"dimension" : "form",
|
||||||
|
"subject" : "整机",
|
||||||
|
"requirement" : "具备人形双足类人构型",
|
||||||
|
"priority" : "must",
|
||||||
|
"source" : "explicit",
|
||||||
|
"evidenceIds" : [ "o1" ]
|
||||||
|
} ],
|
||||||
|
"images" : [ ],
|
||||||
|
"observations" : [ {
|
||||||
|
"id" : "o1",
|
||||||
|
"messageId" : "r1",
|
||||||
|
"imageId" : "",
|
||||||
|
"kind" : "user_text",
|
||||||
|
"content" : "给我一个人形机器人",
|
||||||
|
"clarity" : "clear",
|
||||||
|
"region" : [ ]
|
||||||
|
}, {
|
||||||
|
"id" : "o2",
|
||||||
|
"messageId" : "r2",
|
||||||
|
"imageId" : "",
|
||||||
|
"kind" : "user_text",
|
||||||
|
"content" : "换个头",
|
||||||
|
"clarity" : "clear",
|
||||||
|
"region" : [ ]
|
||||||
|
}, {
|
||||||
|
"id" : "o3",
|
||||||
|
"messageId" : "r3",
|
||||||
|
"imageId" : "",
|
||||||
|
"kind" : "user_text",
|
||||||
|
"content" : "单独换个左臂",
|
||||||
|
"clarity" : "clear",
|
||||||
|
"region" : [ ]
|
||||||
|
} ],
|
||||||
|
"keywords" : [ {
|
||||||
|
"term" : "人形机器人",
|
||||||
|
"source" : "explicit",
|
||||||
|
"reason" : "用户明确提出的核心机器人主体需求",
|
||||||
|
"negated" : false,
|
||||||
|
"evidenceIds" : [ "o1" ]
|
||||||
|
}, {
|
||||||
|
"term" : "双足",
|
||||||
|
"source" : "inferred",
|
||||||
|
"reason" : "人形机器人为双足构型,匹配biped模板特征",
|
||||||
|
"negated" : false,
|
||||||
|
"evidenceIds" : [ "o1" ]
|
||||||
|
}, {
|
||||||
|
"term" : "头部",
|
||||||
|
"source" : "explicit",
|
||||||
|
"reason" : "用户要求执行替换操作的目标部件",
|
||||||
|
"negated" : false,
|
||||||
|
"evidenceIds" : [ "o2" ]
|
||||||
|
}, {
|
||||||
|
"term" : "左臂",
|
||||||
|
"source" : "explicit",
|
||||||
|
"reason" : "用户要求单独执行替换操作的目标部件",
|
||||||
|
"negated" : false,
|
||||||
|
"evidenceIds" : [ "o3" ]
|
||||||
|
} ],
|
||||||
|
"robotTypes" : [ {
|
||||||
|
"type" : "biped",
|
||||||
|
"source" : "explicit",
|
||||||
|
"reason" : "用户要求的人形机器人匹配biped双足机器人模板",
|
||||||
|
"evidenceIds" : [ "o1" ]
|
||||||
|
} ],
|
||||||
|
"partCategories" : [ {
|
||||||
|
"category" : "TORSO_0",
|
||||||
|
"source" : "explicit",
|
||||||
|
"reason" : "biped模板必需的躯干部件,构成机器人主体",
|
||||||
|
"evidenceIds" : [ "o1" ]
|
||||||
|
}, {
|
||||||
|
"category" : "HEAD_0",
|
||||||
|
"source" : "explicit",
|
||||||
|
"reason" : "biped模板包含的头部部件,为用户要求的替换目标",
|
||||||
|
"evidenceIds" : [ "o1", "o2" ]
|
||||||
|
}, {
|
||||||
|
"category" : "WAIST_0",
|
||||||
|
"source" : "explicit",
|
||||||
|
"reason" : "biped模板必需的腰部部件,连接躯干与下肢",
|
||||||
|
"evidenceIds" : [ "o1" ]
|
||||||
|
}, {
|
||||||
|
"category" : "ARM_L",
|
||||||
|
"source" : "explicit",
|
||||||
|
"reason" : "biped模板包含的左臂部件,为用户要求的单独替换目标",
|
||||||
|
"evidenceIds" : [ "o1", "o3" ]
|
||||||
|
}, {
|
||||||
|
"category" : "ARM_R",
|
||||||
|
"source" : "explicit",
|
||||||
|
"reason" : "biped模板包含的右臂部件,构成人形双臂结构",
|
||||||
|
"evidenceIds" : [ "o1" ]
|
||||||
|
}, {
|
||||||
|
"category" : "HAND_L",
|
||||||
|
"source" : "explicit",
|
||||||
|
"reason" : "biped模板包含的左手部件,匹配左臂末端",
|
||||||
|
"evidenceIds" : [ "o1" ]
|
||||||
|
}, {
|
||||||
|
"category" : "HAND_R",
|
||||||
|
"source" : "explicit",
|
||||||
|
"reason" : "biped模板包含的右手部件,匹配右臂末端",
|
||||||
|
"evidenceIds" : [ "o1" ]
|
||||||
|
}, {
|
||||||
|
"category" : "LEG_L",
|
||||||
|
"source" : "explicit",
|
||||||
|
"reason" : "biped模板包含的左足部件,构成人形双足行走结构",
|
||||||
|
"evidenceIds" : [ "o1" ]
|
||||||
|
}, {
|
||||||
|
"category" : "LEG_R",
|
||||||
|
"source" : "explicit",
|
||||||
|
"reason" : "biped模板包含的右足部件,构成人形双足行走结构",
|
||||||
|
"evidenceIds" : [ "o1" ]
|
||||||
|
}, {
|
||||||
|
"category" : "FOOT_L",
|
||||||
|
"source" : "explicit",
|
||||||
|
"reason" : "biped模板包含的左脚部件,匹配左足末端",
|
||||||
|
"evidenceIds" : [ "o1" ]
|
||||||
|
}, {
|
||||||
|
"category" : "FOOT_R",
|
||||||
|
"source" : "explicit",
|
||||||
|
"reason" : "biped模板包含的右脚部件,匹配右足末端",
|
||||||
|
"evidenceIds" : [ "o1" ]
|
||||||
|
} ],
|
||||||
|
"excludedCategories" : [ ],
|
||||||
|
"constraints" : [ ],
|
||||||
|
"unmodeled" : [ ],
|
||||||
|
"questions" : [ ],
|
||||||
|
"operation" : {
|
||||||
|
"type" : "replace",
|
||||||
|
"targets" : [ {
|
||||||
|
"family" : "HEAD",
|
||||||
|
"side" : "all",
|
||||||
|
"instanceId" : "",
|
||||||
|
"ordinal" : "",
|
||||||
|
"evidenceIds" : [ "o2" ]
|
||||||
|
}, {
|
||||||
|
"family" : "ARM",
|
||||||
|
"side" : "L",
|
||||||
|
"instanceId" : "",
|
||||||
|
"ordinal" : "",
|
||||||
|
"evidenceIds" : [ "o3" ]
|
||||||
|
} ]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,182 @@
|
|||||||
|
{
|
||||||
|
"summary": "用户需求为生成具有类人形态的双足人形机器人,在现有方案基础上更换头部部件,未明确其余具体性能、材料、尺寸等参数。",
|
||||||
|
"intentItems": [
|
||||||
|
{
|
||||||
|
"id": "item-001",
|
||||||
|
"dimension": "form",
|
||||||
|
"subject": "整机",
|
||||||
|
"requirement": "具有类人人形形态",
|
||||||
|
"priority": "must",
|
||||||
|
"source": "explicit",
|
||||||
|
"evidenceIds": [
|
||||||
|
"obs-001"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"images": [],
|
||||||
|
"observations": [
|
||||||
|
{
|
||||||
|
"id": "obs-001",
|
||||||
|
"messageId": "m1",
|
||||||
|
"imageId": "",
|
||||||
|
"kind": "user_text",
|
||||||
|
"content": "给我一个人形机器人",
|
||||||
|
"clarity": "clear",
|
||||||
|
"region": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "obs-002",
|
||||||
|
"messageId": "m2",
|
||||||
|
"imageId": "",
|
||||||
|
"kind": "user_text",
|
||||||
|
"content": "换个头",
|
||||||
|
"clarity": "clear",
|
||||||
|
"region": []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"keywords": [
|
||||||
|
{
|
||||||
|
"term": "人形机器人",
|
||||||
|
"source": "explicit",
|
||||||
|
"reason": "用户明确请求生成具有类人形态的机器人",
|
||||||
|
"negated": false,
|
||||||
|
"evidenceIds": [
|
||||||
|
"obs-001"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"robotTypes": [
|
||||||
|
{
|
||||||
|
"type": "biped",
|
||||||
|
"source": "inferred",
|
||||||
|
"reason": "类人人形机器人形态对应目录中的双足机器人模板",
|
||||||
|
"evidenceIds": [
|
||||||
|
"obs-001"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"partCategories": [
|
||||||
|
{
|
||||||
|
"category": "TORSO_0",
|
||||||
|
"source": "inferred",
|
||||||
|
"reason": "双足人形机器人基础构成部件,为整机躯干",
|
||||||
|
"evidenceIds": [
|
||||||
|
"obs-001"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"category": "HEAD_0",
|
||||||
|
"source": "inferred",
|
||||||
|
"reason": "双足人形机器人基础构成部件,本轮用户要求更换该部件",
|
||||||
|
"evidenceIds": [
|
||||||
|
"obs-001",
|
||||||
|
"obs-002"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"category": "WAIST_0",
|
||||||
|
"source": "inferred",
|
||||||
|
"reason": "双足人形机器人基础构成部件,为连接躯干的腰部结构",
|
||||||
|
"evidenceIds": [
|
||||||
|
"obs-001"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"category": "ARM_L",
|
||||||
|
"source": "inferred",
|
||||||
|
"reason": "双足人形机器人默认配置左臂部件",
|
||||||
|
"evidenceIds": [
|
||||||
|
"obs-001"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"category": "ARM_R",
|
||||||
|
"source": "inferred",
|
||||||
|
"reason": "双足人形机器人默认配置右臂部件",
|
||||||
|
"evidenceIds": [
|
||||||
|
"obs-001"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"category": "HAND_L",
|
||||||
|
"source": "inferred",
|
||||||
|
"reason": "双足人形机器人默认配置左手部件",
|
||||||
|
"evidenceIds": [
|
||||||
|
"obs-001"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"category": "HAND_R",
|
||||||
|
"source": "inferred",
|
||||||
|
"reason": "双足人形机器人默认配置右手部件",
|
||||||
|
"evidenceIds": [
|
||||||
|
"obs-001"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"category": "LEG_L",
|
||||||
|
"source": "inferred",
|
||||||
|
"reason": "双足人形机器人默认配置左足部件",
|
||||||
|
"evidenceIds": [
|
||||||
|
"obs-001"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"category": "LEG_R",
|
||||||
|
"source": "inferred",
|
||||||
|
"reason": "双足人形机器人默认配置右足部件",
|
||||||
|
"evidenceIds": [
|
||||||
|
"obs-001"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"category": "FOOT_L",
|
||||||
|
"source": "inferred",
|
||||||
|
"reason": "双足人形机器人默认配置左脚部件",
|
||||||
|
"evidenceIds": [
|
||||||
|
"obs-001"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"category": "FOOT_R",
|
||||||
|
"source": "inferred",
|
||||||
|
"reason": "双足人形机器人默认配置右脚部件",
|
||||||
|
"evidenceIds": [
|
||||||
|
"obs-001"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"excludedCategories": [],
|
||||||
|
"constraints": [],
|
||||||
|
"unmodeled": [
|
||||||
|
{
|
||||||
|
"text": "未明确指定人形机器人的具体自由度、运动性能、载荷、尺寸、材料、外观细节、应用场景及执行任务等参数",
|
||||||
|
"reason": "用户仅提出人形整机形态要求,未提供可对应到目录组件的具体可投影约束信息",
|
||||||
|
"evidenceIds": [
|
||||||
|
"obs-001"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"text": "未明确指定更换后头部组件的具体形态、自由度、尺寸、材料、功能等参数",
|
||||||
|
"reason": "用户仅提出更换头部的操作要求,未提供新头部部件的具体可投影约束信息",
|
||||||
|
"evidenceIds": [
|
||||||
|
"obs-002"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"questions": [],
|
||||||
|
"operation": {
|
||||||
|
"type": "replace",
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"family": "HEAD",
|
||||||
|
"side": "0",
|
||||||
|
"instanceId": "",
|
||||||
|
"ordinal": "",
|
||||||
|
"evidenceIds": [
|
||||||
|
"obs-002"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,332 @@
|
|||||||
|
[
|
||||||
|
{
|
||||||
|
"component_code": "CW-BFXXH6TAVTBATHRV",
|
||||||
|
"component_name": "躯干_0_八边棱柱",
|
||||||
|
"category": "torso_0",
|
||||||
|
"urdf_info": {
|
||||||
|
"frames": [
|
||||||
|
{
|
||||||
|
"rpy": [
|
||||||
|
-1.5708,
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"xyz": [
|
||||||
|
0,
|
||||||
|
0.08835,
|
||||||
|
0.07156
|
||||||
|
],
|
||||||
|
"axis": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"kind": "joint",
|
||||||
|
"name": "LINK_HAND_L",
|
||||||
|
"type": "fixed",
|
||||||
|
"child": "LINK_HAND_L",
|
||||||
|
"limits": {},
|
||||||
|
"parent": "base_link",
|
||||||
|
"interfaceType": "hand_l",
|
||||||
|
"originExplicit": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"rpy": [
|
||||||
|
1.5708,
|
||||||
|
1.5708,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"xyz": [
|
||||||
|
0,
|
||||||
|
-0.08835,
|
||||||
|
0.07156
|
||||||
|
],
|
||||||
|
"axis": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"kind": "joint",
|
||||||
|
"name": "LINK_HAND_R",
|
||||||
|
"type": "fixed",
|
||||||
|
"child": "LINK_HAND_R",
|
||||||
|
"limits": {},
|
||||||
|
"parent": "base_link",
|
||||||
|
"interfaceType": "hand_r",
|
||||||
|
"originExplicit": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"rpy": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"xyz": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0.109
|
||||||
|
],
|
||||||
|
"axis": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"kind": "joint",
|
||||||
|
"name": "LINK_HEAD_0",
|
||||||
|
"type": "fixed",
|
||||||
|
"child": "LINK_HEAD_0",
|
||||||
|
"limits": {},
|
||||||
|
"parent": "base_link",
|
||||||
|
"interfaceType": "head_0",
|
||||||
|
"originExplicit": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"rpy": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"xyz": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"axis": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"kind": "joint",
|
||||||
|
"name": "LINK_WAIST_0",
|
||||||
|
"type": "fixed",
|
||||||
|
"child": "LINK_WAIST_0",
|
||||||
|
"limits": {},
|
||||||
|
"parent": "base_link",
|
||||||
|
"interfaceType": "waist_0",
|
||||||
|
"originExplicit": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"rootLink": "base_link",
|
||||||
|
"robotName": "躯干_0_八边棱柱"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"component_code": "CW-HANKCSXC8XRV1BRP",
|
||||||
|
"component_name": "腰_0_八边棱柱(腰固定)",
|
||||||
|
"category": "waist_0",
|
||||||
|
"urdf_info": {
|
||||||
|
"frames": [
|
||||||
|
{
|
||||||
|
"rpy": [
|
||||||
|
3.14159265358979,
|
||||||
|
0,
|
||||||
|
3.14159265358979
|
||||||
|
],
|
||||||
|
"xyz": [
|
||||||
|
0,
|
||||||
|
0.0725,
|
||||||
|
-0.05035
|
||||||
|
],
|
||||||
|
"axis": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
1
|
||||||
|
],
|
||||||
|
"kind": "joint",
|
||||||
|
"name": "LINK_LEG_L",
|
||||||
|
"type": "fixed",
|
||||||
|
"child": "LINK_LEG_L",
|
||||||
|
"limits": {
|
||||||
|
"effort": 100,
|
||||||
|
"velocity": 50
|
||||||
|
},
|
||||||
|
"parent": "LINK_WAIST_0",
|
||||||
|
"interfaceType": "leg_l",
|
||||||
|
"originExplicit": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"rpy": [
|
||||||
|
3.14159265358979,
|
||||||
|
0,
|
||||||
|
3.14159265358979
|
||||||
|
],
|
||||||
|
"xyz": [
|
||||||
|
0,
|
||||||
|
-0.0725,
|
||||||
|
-0.05035
|
||||||
|
],
|
||||||
|
"axis": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
1
|
||||||
|
],
|
||||||
|
"kind": "joint",
|
||||||
|
"name": "LINK_LEG_R",
|
||||||
|
"type": "fixed",
|
||||||
|
"child": "LINK_LEG_R",
|
||||||
|
"limits": {
|
||||||
|
"effort": 100,
|
||||||
|
"velocity": 50
|
||||||
|
},
|
||||||
|
"parent": "LINK_WAIST_0",
|
||||||
|
"interfaceType": "leg_r",
|
||||||
|
"originExplicit": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"rootLink": "LINK_WAIST_0",
|
||||||
|
"robotName": "腰_0_八边棱柱(腰固定)"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"component_code": "CW-DA36W433NBBHXJJE",
|
||||||
|
"component_name": "头_0_卤蛋形状零自由度头",
|
||||||
|
"category": "head_0",
|
||||||
|
"urdf_info": {
|
||||||
|
"frames": [
|
||||||
|
{
|
||||||
|
"rpy": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"xyz": [
|
||||||
|
7.21972081179142e-05,
|
||||||
|
0,
|
||||||
|
-0.005
|
||||||
|
],
|
||||||
|
"axis": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
1
|
||||||
|
],
|
||||||
|
"kind": "joint",
|
||||||
|
"name": "LINK_HEAD_0",
|
||||||
|
"type": "revolute",
|
||||||
|
"child": "LINK_HEAD_0",
|
||||||
|
"limits": {
|
||||||
|
"lower": -1.8,
|
||||||
|
"upper": 1.8,
|
||||||
|
"effort": 100,
|
||||||
|
"velocity": 50
|
||||||
|
},
|
||||||
|
"parent": "base_link",
|
||||||
|
"interfaceType": "head_0",
|
||||||
|
"originExplicit": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"rootLink": "base_link",
|
||||||
|
"robotName": "头_0_卤蛋形状零自由度头"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"component_code": "CW-7CYFG066SE849X84",
|
||||||
|
"component_name": "躯干_0_宽躯躯干",
|
||||||
|
"category": "torso_0",
|
||||||
|
"urdf_info": {
|
||||||
|
"frames": [
|
||||||
|
{
|
||||||
|
"rpy": [
|
||||||
|
1.5707963267949,
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"xyz": [
|
||||||
|
0,
|
||||||
|
-0.100381817826158,
|
||||||
|
0.00999999999999999
|
||||||
|
],
|
||||||
|
"axis": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"kind": "joint",
|
||||||
|
"name": "J1",
|
||||||
|
"type": "fixed",
|
||||||
|
"child": "LINK_arm_r",
|
||||||
|
"limits": {},
|
||||||
|
"parent": "BASE",
|
||||||
|
"interfaceType": "arm_r",
|
||||||
|
"originExplicit": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"rpy": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"xyz": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0.0434269852498788
|
||||||
|
],
|
||||||
|
"axis": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"kind": "joint",
|
||||||
|
"name": "J2",
|
||||||
|
"type": "fixed",
|
||||||
|
"child": "LINK_head_0",
|
||||||
|
"limits": {},
|
||||||
|
"parent": "BASE",
|
||||||
|
"interfaceType": "head_0",
|
||||||
|
"originExplicit": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"rpy": [
|
||||||
|
-1.5707963267949,
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"xyz": [
|
||||||
|
0,
|
||||||
|
0.100381817826158,
|
||||||
|
0.01
|
||||||
|
],
|
||||||
|
"axis": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"kind": "joint",
|
||||||
|
"name": "J3",
|
||||||
|
"type": "fixed",
|
||||||
|
"child": "LINK_arm_l",
|
||||||
|
"limits": {},
|
||||||
|
"parent": "BASE",
|
||||||
|
"interfaceType": "arm_l",
|
||||||
|
"originExplicit": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"rpy": [
|
||||||
|
3.14159265358979,
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"xyz": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
-0.0984730140388012
|
||||||
|
],
|
||||||
|
"axis": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"kind": "joint",
|
||||||
|
"name": "J4",
|
||||||
|
"type": "fixed",
|
||||||
|
"child": "LINK_waist_0",
|
||||||
|
"limits": {},
|
||||||
|
"parent": "BASE",
|
||||||
|
"interfaceType": "waist_0",
|
||||||
|
"originExplicit": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"rootLink": "BASE",
|
||||||
|
"robotName": "躯干_0_宽躯躯干"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,584 @@
|
|||||||
|
[
|
||||||
|
{
|
||||||
|
"component_code": "CW-GFQGN4DVNT5Q79FW",
|
||||||
|
"component_name": "脚_0_六足脚1",
|
||||||
|
"category": "FOOT_0",
|
||||||
|
"description": "六足机器人脚",
|
||||||
|
"material": "",
|
||||||
|
"mass_kg": 0.0,
|
||||||
|
"degrees_of_freedom": 1,
|
||||||
|
"function_description": "",
|
||||||
|
"shape": "",
|
||||||
|
"size": "",
|
||||||
|
"torque_nm": 0.0,
|
||||||
|
"bom_list": [],
|
||||||
|
"urdf_info": {
|
||||||
|
"frames": [
|
||||||
|
{
|
||||||
|
"rpy": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"xyz": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"kind": "interface",
|
||||||
|
"name": "__root_interface__",
|
||||||
|
"child": "LINK_FOOT_0",
|
||||||
|
"isRoot": true,
|
||||||
|
"limits": {},
|
||||||
|
"parent": null,
|
||||||
|
"synthetic": true,
|
||||||
|
"interfaceName": "LINK_FOOT_0",
|
||||||
|
"interfaceType": "FOOT_0",
|
||||||
|
"originExplicit": false
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"rootLink": "LINK_FOOT_0",
|
||||||
|
"robotName": "脚_0_六足脚1"
|
||||||
|
},
|
||||||
|
"step_object_key": "components/CW-GFQGN4DVNT5Q79FW/model.step",
|
||||||
|
"urdf_prefix": "components/CW-GFQGN4DVNT5Q79FW/urdf/",
|
||||||
|
"urdf_main_object_key": "components/CW-GFQGN4DVNT5Q79FW/urdf/robot.urdf",
|
||||||
|
"urdf_files": [
|
||||||
|
{
|
||||||
|
"relativePath": "robot.urdf",
|
||||||
|
"sizeBytes": 1
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"version": 1
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"component_code": "CW-8ZDENK5SQW1APH2S",
|
||||||
|
"component_name": "头_0_六足头1",
|
||||||
|
"category": "HEAD_0",
|
||||||
|
"description": "六足机器人头",
|
||||||
|
"material": "",
|
||||||
|
"mass_kg": 0.0,
|
||||||
|
"degrees_of_freedom": 1,
|
||||||
|
"function_description": "",
|
||||||
|
"shape": "",
|
||||||
|
"size": "",
|
||||||
|
"torque_nm": 0.0,
|
||||||
|
"bom_list": [],
|
||||||
|
"urdf_info": {
|
||||||
|
"frames": [
|
||||||
|
{
|
||||||
|
"rpy": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"xyz": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"kind": "interface",
|
||||||
|
"name": "__root_interface__",
|
||||||
|
"child": "LINK_WAIST_0",
|
||||||
|
"isRoot": true,
|
||||||
|
"limits": {},
|
||||||
|
"parent": null,
|
||||||
|
"synthetic": true,
|
||||||
|
"interfaceName": "LINK_WAIST_0",
|
||||||
|
"interfaceType": "WAIST_0",
|
||||||
|
"originExplicit": false
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"rootLink": "LINK_WAIST_0",
|
||||||
|
"robotName": "头_0_六足头1"
|
||||||
|
},
|
||||||
|
"step_object_key": "components/CW-8ZDENK5SQW1APH2S/model.step",
|
||||||
|
"urdf_prefix": "components/CW-8ZDENK5SQW1APH2S/urdf/",
|
||||||
|
"urdf_main_object_key": "components/CW-8ZDENK5SQW1APH2S/urdf/robot.urdf",
|
||||||
|
"urdf_files": [
|
||||||
|
{
|
||||||
|
"relativePath": "robot.urdf",
|
||||||
|
"sizeBytes": 1
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"version": 1
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"component_code": "CW-3Z2XH5K45D4K8JPP",
|
||||||
|
"component_name": "足_0_虫足3DOF摆动",
|
||||||
|
"category": "LEG_0",
|
||||||
|
"description": "六足机器人足",
|
||||||
|
"material": "",
|
||||||
|
"mass_kg": 0.0,
|
||||||
|
"degrees_of_freedom": 1,
|
||||||
|
"function_description": "",
|
||||||
|
"shape": "",
|
||||||
|
"size": "",
|
||||||
|
"torque_nm": 0.0,
|
||||||
|
"bom_list": [],
|
||||||
|
"urdf_info": {
|
||||||
|
"frames": [
|
||||||
|
{
|
||||||
|
"rpy": [
|
||||||
|
1.5707963267949,
|
||||||
|
1.5707963267949,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"xyz": [
|
||||||
|
0.0445,
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"axis": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
-1
|
||||||
|
],
|
||||||
|
"kind": "joint",
|
||||||
|
"name": "J_1_Link",
|
||||||
|
"type": "revolute",
|
||||||
|
"child": "1_Link",
|
||||||
|
"limits": {
|
||||||
|
"lower": -1.57,
|
||||||
|
"upper": 0.785,
|
||||||
|
"effort": 0,
|
||||||
|
"velocity": 0
|
||||||
|
},
|
||||||
|
"parent": "LINK_LEG_0",
|
||||||
|
"interfaceName": null,
|
||||||
|
"interfaceType": null,
|
||||||
|
"originExplicit": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"rpy": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"xyz": [
|
||||||
|
0.0395979797464467,
|
||||||
|
0.0395979797464466,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"axis": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
-1
|
||||||
|
],
|
||||||
|
"kind": "joint",
|
||||||
|
"name": "J_2_Link",
|
||||||
|
"type": "revolute",
|
||||||
|
"child": "2_Link",
|
||||||
|
"limits": {
|
||||||
|
"lower": -0.785,
|
||||||
|
"upper": 1.57,
|
||||||
|
"effort": 0,
|
||||||
|
"velocity": 0
|
||||||
|
},
|
||||||
|
"parent": "1_Link",
|
||||||
|
"interfaceName": null,
|
||||||
|
"interfaceType": null,
|
||||||
|
"originExplicit": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"rpy": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
3.14159265358979
|
||||||
|
],
|
||||||
|
"xyz": [
|
||||||
|
-0.0395979797464466,
|
||||||
|
0.0395979797464467,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"axis": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
1
|
||||||
|
],
|
||||||
|
"kind": "joint",
|
||||||
|
"name": "J_LINK_FOOT_0",
|
||||||
|
"type": "continuous",
|
||||||
|
"child": "LINK_FOOT_0",
|
||||||
|
"limits": {},
|
||||||
|
"parent": "2_Link",
|
||||||
|
"interfaceName": "LINK_FOOT_0",
|
||||||
|
"interfaceType": "FOOT_0",
|
||||||
|
"originExplicit": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"rpy": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"xyz": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"kind": "interface",
|
||||||
|
"name": "__root_interface__",
|
||||||
|
"child": "LINK_LEG_0",
|
||||||
|
"isRoot": true,
|
||||||
|
"limits": {},
|
||||||
|
"parent": null,
|
||||||
|
"synthetic": true,
|
||||||
|
"interfaceName": "LINK_LEG_0",
|
||||||
|
"interfaceType": "LEG_0",
|
||||||
|
"originExplicit": false
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"rootLink": "LINK_LEG_0",
|
||||||
|
"robotName": "足_0_虫足3DOF摆动"
|
||||||
|
},
|
||||||
|
"step_object_key": "components/CW-3Z2XH5K45D4K8JPP/model.step",
|
||||||
|
"urdf_prefix": "components/CW-3Z2XH5K45D4K8JPP/urdf/",
|
||||||
|
"urdf_main_object_key": "components/CW-3Z2XH5K45D4K8JPP/urdf/robot.urdf",
|
||||||
|
"urdf_files": [
|
||||||
|
{
|
||||||
|
"relativePath": "robot.urdf",
|
||||||
|
"sizeBytes": 1
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"version": 1
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"component_code": "CW-FS081NP1VD45Z7NJ",
|
||||||
|
"component_name": "躯干_0_直筒披肩机器人",
|
||||||
|
"category": "TORSO_0",
|
||||||
|
"description": "",
|
||||||
|
"material": "",
|
||||||
|
"mass_kg": 0.0,
|
||||||
|
"degrees_of_freedom": 1,
|
||||||
|
"function_description": "",
|
||||||
|
"shape": "",
|
||||||
|
"size": "",
|
||||||
|
"torque_nm": 0.0,
|
||||||
|
"bom_list": [],
|
||||||
|
"urdf_info": {
|
||||||
|
"frames": [
|
||||||
|
{
|
||||||
|
"rpy": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"xyz": [
|
||||||
|
0.0018067,
|
||||||
|
0,
|
||||||
|
0.0935
|
||||||
|
],
|
||||||
|
"axis": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
-1
|
||||||
|
],
|
||||||
|
"kind": "joint",
|
||||||
|
"name": "J1",
|
||||||
|
"type": "continuous",
|
||||||
|
"child": "LINK_HEAD_0",
|
||||||
|
"limits": {},
|
||||||
|
"parent": "LINK_WAIST_0",
|
||||||
|
"interfaceName": "LINK_HEAD_0",
|
||||||
|
"interfaceType": "HEAD_0",
|
||||||
|
"originExplicit": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"rpy": [
|
||||||
|
-1.5708,
|
||||||
|
1.5708,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"xyz": [
|
||||||
|
0.0018067,
|
||||||
|
0.0505,
|
||||||
|
0.0675
|
||||||
|
],
|
||||||
|
"axis": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
-1
|
||||||
|
],
|
||||||
|
"kind": "joint",
|
||||||
|
"name": "J2",
|
||||||
|
"type": "continuous",
|
||||||
|
"child": "LINK_ARM_L",
|
||||||
|
"limits": {},
|
||||||
|
"parent": "LINK_WAIST_0",
|
||||||
|
"interfaceName": "LINK_ARM_L",
|
||||||
|
"interfaceType": "ARM_L",
|
||||||
|
"originExplicit": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"rpy": [
|
||||||
|
1.5707963267949,
|
||||||
|
1.5707963267949,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"xyz": [
|
||||||
|
0.00180667202154026,
|
||||||
|
-0.0505,
|
||||||
|
0.0675
|
||||||
|
],
|
||||||
|
"axis": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
-1
|
||||||
|
],
|
||||||
|
"kind": "joint",
|
||||||
|
"name": "J3",
|
||||||
|
"type": "continuous",
|
||||||
|
"child": "LINK_ARM_R",
|
||||||
|
"limits": {},
|
||||||
|
"parent": "LINK_WAIST_0",
|
||||||
|
"interfaceName": "LINK_ARM_R",
|
||||||
|
"interfaceType": "ARM_R",
|
||||||
|
"originExplicit": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"rpy": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"xyz": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"kind": "interface",
|
||||||
|
"name": "__root_interface__",
|
||||||
|
"child": "LINK_WAIST_0",
|
||||||
|
"isRoot": true,
|
||||||
|
"limits": {},
|
||||||
|
"parent": null,
|
||||||
|
"synthetic": true,
|
||||||
|
"interfaceName": "LINK_WAIST_0",
|
||||||
|
"interfaceType": "WAIST_0",
|
||||||
|
"originExplicit": false
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"rootLink": "LINK_WAIST_0",
|
||||||
|
"robotName": "躯干_0_直筒披肩机器人"
|
||||||
|
},
|
||||||
|
"step_object_key": "components/CW-FS081NP1VD45Z7NJ/model.step",
|
||||||
|
"urdf_prefix": "components/CW-FS081NP1VD45Z7NJ/urdf/",
|
||||||
|
"urdf_main_object_key": "components/CW-FS081NP1VD45Z7NJ/urdf/robot.urdf",
|
||||||
|
"urdf_files": [
|
||||||
|
{
|
||||||
|
"relativePath": "robot.urdf",
|
||||||
|
"sizeBytes": 1
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"version": 5
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"component_code": "CW-3JB52HZTFYTPZ1F0",
|
||||||
|
"component_name": "腰_0_六足腰2",
|
||||||
|
"category": "WAIST_0",
|
||||||
|
"description": "六足机器人腰部",
|
||||||
|
"material": "",
|
||||||
|
"mass_kg": 0.0,
|
||||||
|
"degrees_of_freedom": 1,
|
||||||
|
"function_description": "",
|
||||||
|
"shape": "",
|
||||||
|
"size": "",
|
||||||
|
"torque_nm": 0.0,
|
||||||
|
"bom_list": [],
|
||||||
|
"urdf_info": {
|
||||||
|
"frames": [
|
||||||
|
{
|
||||||
|
"rpy": [
|
||||||
|
3.14159265358979,
|
||||||
|
0,
|
||||||
|
-1.5707963267949
|
||||||
|
],
|
||||||
|
"xyz": [
|
||||||
|
0,
|
||||||
|
-0.0845000000000002,
|
||||||
|
-0.027
|
||||||
|
],
|
||||||
|
"axis": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
1
|
||||||
|
],
|
||||||
|
"kind": "joint",
|
||||||
|
"name": "J_LINK#1_LEG_0",
|
||||||
|
"type": "continuous",
|
||||||
|
"child": "LINK_LEG_0",
|
||||||
|
"limits": {},
|
||||||
|
"parent": "LINK_WAIST_0",
|
||||||
|
"interfaceName": "LINK_LEG_0",
|
||||||
|
"interfaceType": "LEG_0",
|
||||||
|
"originExplicit": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"rpy": [
|
||||||
|
3.14159265358979,
|
||||||
|
0,
|
||||||
|
-2.61799387799148
|
||||||
|
],
|
||||||
|
"xyz": [
|
||||||
|
-0.0731791466197846,
|
||||||
|
-0.0422500000000013,
|
||||||
|
-0.027
|
||||||
|
],
|
||||||
|
"axis": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
1
|
||||||
|
],
|
||||||
|
"kind": "joint",
|
||||||
|
"name": "J_LINK#2_LEG_0",
|
||||||
|
"type": "continuous",
|
||||||
|
"child": "LINK_LEG_0",
|
||||||
|
"limits": {},
|
||||||
|
"parent": "LINK_WAIST_0",
|
||||||
|
"interfaceName": "LINK_LEG_0",
|
||||||
|
"interfaceType": "LEG_0",
|
||||||
|
"originExplicit": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"rpy": [
|
||||||
|
3.14159265358979,
|
||||||
|
0,
|
||||||
|
2.61799387799151
|
||||||
|
],
|
||||||
|
"xyz": [
|
||||||
|
-0.0731791466197859,
|
||||||
|
0.0422499999999991,
|
||||||
|
-0.027
|
||||||
|
],
|
||||||
|
"axis": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
1
|
||||||
|
],
|
||||||
|
"kind": "joint",
|
||||||
|
"name": "J_LINK#3_LEG_0",
|
||||||
|
"type": "continuous",
|
||||||
|
"child": "LINK_LEG_0",
|
||||||
|
"limits": {},
|
||||||
|
"parent": "LINK_WAIST_0",
|
||||||
|
"interfaceName": "LINK_LEG_0",
|
||||||
|
"interfaceType": "LEG_0",
|
||||||
|
"originExplicit": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"rpy": [
|
||||||
|
3.14159265358979,
|
||||||
|
0,
|
||||||
|
1.5707963267949
|
||||||
|
],
|
||||||
|
"xyz": [
|
||||||
|
0,
|
||||||
|
0.0845000000000002,
|
||||||
|
-0.027
|
||||||
|
],
|
||||||
|
"axis": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
1
|
||||||
|
],
|
||||||
|
"kind": "joint",
|
||||||
|
"name": "J_LINK#4_LEG_0",
|
||||||
|
"type": "continuous",
|
||||||
|
"child": "LINK_LEG_0",
|
||||||
|
"limits": {},
|
||||||
|
"parent": "LINK_WAIST_0",
|
||||||
|
"interfaceName": "LINK_LEG_0",
|
||||||
|
"interfaceType": "LEG_0",
|
||||||
|
"originExplicit": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"rpy": [
|
||||||
|
-3.14159265358979,
|
||||||
|
0,
|
||||||
|
0.523598775598312
|
||||||
|
],
|
||||||
|
"xyz": [
|
||||||
|
0.0731791466197847,
|
||||||
|
0.0422500000000008,
|
||||||
|
-0.027
|
||||||
|
],
|
||||||
|
"axis": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
1
|
||||||
|
],
|
||||||
|
"kind": "joint",
|
||||||
|
"name": "J_LINK#5_LEG_0",
|
||||||
|
"type": "continuous",
|
||||||
|
"child": "LINK_LEG_0",
|
||||||
|
"limits": {},
|
||||||
|
"parent": "LINK_WAIST_0",
|
||||||
|
"interfaceName": "LINK_LEG_0",
|
||||||
|
"interfaceType": "LEG_0",
|
||||||
|
"originExplicit": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"rpy": [
|
||||||
|
-3.14159265358979,
|
||||||
|
0,
|
||||||
|
-0.523598775598288
|
||||||
|
],
|
||||||
|
"xyz": [
|
||||||
|
0.0731791466197853,
|
||||||
|
-0.0422499999999998,
|
||||||
|
-0.027
|
||||||
|
],
|
||||||
|
"axis": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
1
|
||||||
|
],
|
||||||
|
"kind": "joint",
|
||||||
|
"name": "J_LINK#6_LEG_0",
|
||||||
|
"type": "continuous",
|
||||||
|
"child": "LINK_LEG_0",
|
||||||
|
"limits": {},
|
||||||
|
"parent": "LINK_WAIST_0",
|
||||||
|
"interfaceName": "LINK_LEG_0",
|
||||||
|
"interfaceType": "LEG_0",
|
||||||
|
"originExplicit": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"rpy": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"xyz": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"kind": "interface",
|
||||||
|
"name": "__root_interface__",
|
||||||
|
"child": "LINK_WAIST_0",
|
||||||
|
"isRoot": true,
|
||||||
|
"limits": {},
|
||||||
|
"parent": null,
|
||||||
|
"synthetic": true,
|
||||||
|
"interfaceName": "LINK_WAIST_0",
|
||||||
|
"interfaceType": "WAIST_0",
|
||||||
|
"originExplicit": false
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"rootLink": "LINK_WAIST_0",
|
||||||
|
"robotName": "腰_0_六足腰2"
|
||||||
|
},
|
||||||
|
"step_object_key": "components/CW-3JB52HZTFYTPZ1F0/model.step",
|
||||||
|
"urdf_prefix": "components/CW-3JB52HZTFYTPZ1F0/urdf/",
|
||||||
|
"urdf_main_object_key": "components/CW-3JB52HZTFYTPZ1F0/urdf/robot.urdf",
|
||||||
|
"urdf_files": [
|
||||||
|
{
|
||||||
|
"relativePath": "robot.urdf",
|
||||||
|
"sizeBytes": 1
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"version": 1
|
||||||
|
}
|
||||||
|
]
|
||||||
+137
@@ -0,0 +1,137 @@
|
|||||||
|
{
|
||||||
|
"summary": "参照图片中相邻长方体块的块状外观生成通用机器人方案,未指定腿数、性能、尺寸或排除部件。",
|
||||||
|
"intentItems": [
|
||||||
|
{
|
||||||
|
"id": "ii-1",
|
||||||
|
"dimension": "other",
|
||||||
|
"subject": "机器人整机",
|
||||||
|
"requirement": "提供可装配的通用机器人",
|
||||||
|
"priority": "must",
|
||||||
|
"source": "explicit",
|
||||||
|
"evidenceIds": [
|
||||||
|
"obs-1"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "ii-2",
|
||||||
|
"dimension": "form",
|
||||||
|
"subject": "机器人整机",
|
||||||
|
"requirement": "参照图中由相邻长方体块组成的块状整机形态",
|
||||||
|
"priority": "must",
|
||||||
|
"source": "inferred",
|
||||||
|
"evidenceIds": [
|
||||||
|
"obs-3",
|
||||||
|
"obs-5"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"images": [
|
||||||
|
{
|
||||||
|
"imageId": "image-current",
|
||||||
|
"type": "other",
|
||||||
|
"usage": "requirements",
|
||||||
|
"uncertainties": [
|
||||||
|
"两个长方体分别对应哪个目录部件无法确认",
|
||||||
|
"隐藏部件、尺寸、材质、颜色和相对位姿不可见",
|
||||||
|
"界面控件与操作提示不属于机器人需求"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"observations": [
|
||||||
|
{
|
||||||
|
"id": "obs-1",
|
||||||
|
"messageId": "m1",
|
||||||
|
"imageId": "",
|
||||||
|
"kind": "user_text",
|
||||||
|
"content": "给我个机器人",
|
||||||
|
"clarity": "clear",
|
||||||
|
"region": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "obs-2",
|
||||||
|
"messageId": "m2",
|
||||||
|
"imageId": "",
|
||||||
|
"kind": "user_text",
|
||||||
|
"content": "换个左手",
|
||||||
|
"clarity": "clear",
|
||||||
|
"region": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "obs-3",
|
||||||
|
"messageId": "m3",
|
||||||
|
"imageId": "image-current",
|
||||||
|
"kind": "user_text",
|
||||||
|
"content": "拼一个这样的机器人",
|
||||||
|
"clarity": "clear",
|
||||||
|
"region": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "obs-4",
|
||||||
|
"messageId": "m3",
|
||||||
|
"imageId": "image-current",
|
||||||
|
"kind": "image_text",
|
||||||
|
"content": "匹配方案 · 装配预览;匹配方案 | 后端装配位姿;左键旋转 · 右键平移 · 滚轮缩放",
|
||||||
|
"clarity": "clear",
|
||||||
|
"region": [
|
||||||
|
0.17,
|
||||||
|
0.12,
|
||||||
|
0.83,
|
||||||
|
0.88
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "obs-5",
|
||||||
|
"messageId": "m3",
|
||||||
|
"imageId": "image-current",
|
||||||
|
"kind": "image_visual",
|
||||||
|
"content": "3D预览视图中可见一个竖向浅蓝色长方体块,其侧旁附接一个较薄的浅灰色长方体块,无可见臂、腿、头等部件,右下角有XYZ坐标轴",
|
||||||
|
"clarity": "clear",
|
||||||
|
"region": [
|
||||||
|
0.35,
|
||||||
|
0.3,
|
||||||
|
0.6,
|
||||||
|
0.85
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"keywords": [
|
||||||
|
{
|
||||||
|
"term": "机器人",
|
||||||
|
"source": "explicit",
|
||||||
|
"reason": "用户明确要求组装机器人",
|
||||||
|
"negated": false,
|
||||||
|
"evidenceIds": [
|
||||||
|
"obs-1",
|
||||||
|
"obs-3"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"term": "长方体块状外观",
|
||||||
|
"source": "inferred",
|
||||||
|
"reason": "3D预览中可见竖向长方体与附接扁长方体",
|
||||||
|
"negated": false,
|
||||||
|
"evidenceIds": [
|
||||||
|
"obs-5"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"robotTypes": [],
|
||||||
|
"partCategories": [],
|
||||||
|
"excludedCategories": [],
|
||||||
|
"constraints": [],
|
||||||
|
"unmodeled": [
|
||||||
|
{
|
||||||
|
"text": "预览图中两个长方体的精确尺寸、颜色、相对安装位姿及其对应部件归属无法从需求确定",
|
||||||
|
"reason": "图片仅为装配预览截图,无清晰尺寸标注、材质或接口信息,且未画出可明确辨识的臂、腿、头等部件",
|
||||||
|
"evidenceIds": [
|
||||||
|
"obs-4",
|
||||||
|
"obs-5"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"questions": [],
|
||||||
|
"operation": {
|
||||||
|
"type": "generate",
|
||||||
|
"targets": []
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,335 @@
|
|||||||
|
[
|
||||||
|
{
|
||||||
|
"component_code": "CW-AG3XMNWJMN3Q89NX",
|
||||||
|
"component_name": "腰_0_椭圆形(大白)装配",
|
||||||
|
"category": "WAIST_0",
|
||||||
|
"urdf_info": {
|
||||||
|
"frames": [
|
||||||
|
{
|
||||||
|
"rpy": [
|
||||||
|
3.1416,
|
||||||
|
0,
|
||||||
|
3.1416
|
||||||
|
],
|
||||||
|
"xyz": [
|
||||||
|
0,
|
||||||
|
-0.065004,
|
||||||
|
-0.0525
|
||||||
|
],
|
||||||
|
"axis": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
-1
|
||||||
|
],
|
||||||
|
"kind": "joint",
|
||||||
|
"name": "LINK_LEG_R",
|
||||||
|
"type": "continuous",
|
||||||
|
"child": "LINK_LEG_R",
|
||||||
|
"limits": {},
|
||||||
|
"parent": "LINK_WAIST_0",
|
||||||
|
"interfaceName": "LINK_LEG_R",
|
||||||
|
"interfaceType": "LEG_R",
|
||||||
|
"originExplicit": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"rpy": [
|
||||||
|
-3.1416,
|
||||||
|
0,
|
||||||
|
3.1416
|
||||||
|
],
|
||||||
|
"xyz": [
|
||||||
|
0,
|
||||||
|
0.064996,
|
||||||
|
-0.0525
|
||||||
|
],
|
||||||
|
"axis": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
-1
|
||||||
|
],
|
||||||
|
"kind": "joint",
|
||||||
|
"name": "LINK_LEG_L",
|
||||||
|
"type": "continuous",
|
||||||
|
"child": "LINK_LEG_L",
|
||||||
|
"limits": {},
|
||||||
|
"parent": "LINK_WAIST_0",
|
||||||
|
"interfaceName": "LINK_LEG_L",
|
||||||
|
"interfaceType": "LEG_L",
|
||||||
|
"originExplicit": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"rpy": [
|
||||||
|
-2.3562,
|
||||||
|
0,
|
||||||
|
1.5708
|
||||||
|
],
|
||||||
|
"xyz": [
|
||||||
|
-0.046279,
|
||||||
|
0,
|
||||||
|
-0.031093
|
||||||
|
],
|
||||||
|
"axis": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
-1
|
||||||
|
],
|
||||||
|
"kind": "joint",
|
||||||
|
"name": "LINK_TAIL_0",
|
||||||
|
"type": "continuous",
|
||||||
|
"child": "LINK_TAIL_0",
|
||||||
|
"limits": {},
|
||||||
|
"parent": "LINK_WAIST_0",
|
||||||
|
"interfaceName": "LINK_TAIL_0",
|
||||||
|
"interfaceType": "TAIL_0",
|
||||||
|
"originExplicit": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"rpy": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"xyz": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"kind": "interface",
|
||||||
|
"name": "__root_interface__",
|
||||||
|
"child": "LINK_WAIST_0",
|
||||||
|
"isRoot": true,
|
||||||
|
"limits": {},
|
||||||
|
"parent": null,
|
||||||
|
"synthetic": true,
|
||||||
|
"interfaceName": "LINK_WAIST_0",
|
||||||
|
"interfaceType": "WAIST_0",
|
||||||
|
"originExplicit": false
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"rootLink": "LINK_WAIST_0",
|
||||||
|
"robotName": "腰_0_椭圆形(大白)装配"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"component_code": "CW-JP19A0XZY9H7YNBN",
|
||||||
|
"component_name": "足_L_足下出基础",
|
||||||
|
"category": "LEG_L",
|
||||||
|
"urdf_info": {
|
||||||
|
"frames": [
|
||||||
|
{
|
||||||
|
"rpy": [
|
||||||
|
0.0012343,
|
||||||
|
0,
|
||||||
|
0.039823
|
||||||
|
],
|
||||||
|
"xyz": [
|
||||||
|
-0.072777,
|
||||||
|
-0.20292,
|
||||||
|
-0.040497
|
||||||
|
],
|
||||||
|
"axis": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
-1
|
||||||
|
],
|
||||||
|
"kind": "joint",
|
||||||
|
"name": "j_1_Link",
|
||||||
|
"type": "continuous",
|
||||||
|
"child": "1_Link",
|
||||||
|
"limits": {},
|
||||||
|
"parent": "LINK_LEG_L",
|
||||||
|
"interfaceName": null,
|
||||||
|
"interfaceType": null,
|
||||||
|
"originExplicit": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"rpy": [
|
||||||
|
1.5708,
|
||||||
|
0,
|
||||||
|
0.056332
|
||||||
|
],
|
||||||
|
"xyz": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"axis": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
-1
|
||||||
|
],
|
||||||
|
"kind": "joint",
|
||||||
|
"name": "j_2_Link",
|
||||||
|
"type": "continuous",
|
||||||
|
"child": "2_Link",
|
||||||
|
"limits": {},
|
||||||
|
"parent": "1_Link",
|
||||||
|
"interfaceName": null,
|
||||||
|
"interfaceType": null,
|
||||||
|
"originExplicit": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"rpy": [
|
||||||
|
-1.5708,
|
||||||
|
-0.096155,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"xyz": [
|
||||||
|
0,
|
||||||
|
0.000525,
|
||||||
|
0.085
|
||||||
|
],
|
||||||
|
"axis": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"kind": "joint",
|
||||||
|
"name": "J_LINK_FOOT_0",
|
||||||
|
"type": "fixed",
|
||||||
|
"child": "LINK_FOOT_0",
|
||||||
|
"limits": {},
|
||||||
|
"parent": "2_Link",
|
||||||
|
"interfaceName": "LINK_FOOT_0",
|
||||||
|
"interfaceType": "FOOT_0",
|
||||||
|
"originExplicit": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"rpy": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"xyz": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"kind": "interface",
|
||||||
|
"name": "__root_interface__",
|
||||||
|
"child": "LINK_LEG_L",
|
||||||
|
"isRoot": true,
|
||||||
|
"limits": {},
|
||||||
|
"parent": null,
|
||||||
|
"synthetic": true,
|
||||||
|
"interfaceName": "LINK_LEG_L",
|
||||||
|
"interfaceType": "LEG_L",
|
||||||
|
"originExplicit": false
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"rootLink": "LINK_LEG_L",
|
||||||
|
"robotName": "足_L_足下出基础"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"component_code": "CW-JBJWXQ7N4C9P03TJ",
|
||||||
|
"component_name": "足_R_足下出基础",
|
||||||
|
"category": "LEG_R",
|
||||||
|
"urdf_info": {
|
||||||
|
"frames": [
|
||||||
|
{
|
||||||
|
"rpy": [
|
||||||
|
0.0012343,
|
||||||
|
0,
|
||||||
|
0.039823
|
||||||
|
],
|
||||||
|
"xyz": [
|
||||||
|
-0.072777,
|
||||||
|
-0.20292,
|
||||||
|
-0.040497
|
||||||
|
],
|
||||||
|
"axis": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
-1
|
||||||
|
],
|
||||||
|
"kind": "joint",
|
||||||
|
"name": "j_1_Link",
|
||||||
|
"type": "continuous",
|
||||||
|
"child": "1_Link",
|
||||||
|
"limits": {},
|
||||||
|
"parent": "LINK_LEG_R",
|
||||||
|
"interfaceName": null,
|
||||||
|
"interfaceType": null,
|
||||||
|
"originExplicit": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"rpy": [
|
||||||
|
1.5708,
|
||||||
|
0,
|
||||||
|
0.056332
|
||||||
|
],
|
||||||
|
"xyz": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"axis": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
-1
|
||||||
|
],
|
||||||
|
"kind": "joint",
|
||||||
|
"name": "j_2_Link",
|
||||||
|
"type": "continuous",
|
||||||
|
"child": "2_Link",
|
||||||
|
"limits": {},
|
||||||
|
"parent": "1_Link",
|
||||||
|
"interfaceName": null,
|
||||||
|
"interfaceType": null,
|
||||||
|
"originExplicit": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"rpy": [
|
||||||
|
-1.5708,
|
||||||
|
-0.096155,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"xyz": [
|
||||||
|
0,
|
||||||
|
0.000525,
|
||||||
|
0.085
|
||||||
|
],
|
||||||
|
"axis": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"kind": "joint",
|
||||||
|
"name": "J_LINK_FOOT_0",
|
||||||
|
"type": "fixed",
|
||||||
|
"child": "LINK_FOOT_0",
|
||||||
|
"limits": {},
|
||||||
|
"parent": "2_Link",
|
||||||
|
"interfaceName": "LINK_FOOT_0",
|
||||||
|
"interfaceType": "FOOT_0",
|
||||||
|
"originExplicit": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"rpy": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"xyz": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"kind": "interface",
|
||||||
|
"name": "__root_interface__",
|
||||||
|
"child": "LINK_LEG_R",
|
||||||
|
"isRoot": true,
|
||||||
|
"limits": {},
|
||||||
|
"parent": null,
|
||||||
|
"synthetic": true,
|
||||||
|
"interfaceName": "LINK_LEG_R",
|
||||||
|
"interfaceType": "LEG_R",
|
||||||
|
"originExplicit": false
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"rootLink": "LINK_LEG_R",
|
||||||
|
"robotName": "足_R_足下出基础"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.linkerbot</groupId>
|
||||||
|
<artifactId>cadworld</artifactId>
|
||||||
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
<relativePath>../pom.xml</relativePath>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<artifactId>cadworld-bean</artifactId>
|
||||||
|
<packaging>jar</packaging>
|
||||||
|
<name>cadworld-bean</name>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.linkerbot</groupId>
|
||||||
|
<artifactId>cadworld-common</artifactId>
|
||||||
|
<version>${project.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-validation</artifactId>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
</project>
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
package com.linkerbot.cadworld.dto.auth;
|
||||||
|
|
||||||
|
public record CaptchaResponse(String captchaCode, String image, long expiresIn) {
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "CaptchaResponse[expiresIn=" + expiresIn + "]";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
package com.linkerbot.cadworld.dto.auth;
|
||||||
|
|
||||||
|
import com.linkerbot.cadworld.common.util.EmailAddresses;
|
||||||
|
import jakarta.validation.constraints.Email;
|
||||||
|
import jakarta.validation.constraints.NotBlank;
|
||||||
|
import jakarta.validation.constraints.Size;
|
||||||
|
|
||||||
|
public record LoginRequest(
|
||||||
|
@NotBlank @Email(message = "邮箱格式不正确") @Size(max = 254) String email,
|
||||||
|
@NotBlank @Size(max = 64) String captchaCode,
|
||||||
|
@NotBlank @Size(max = 32) String captchaAnswer) {
|
||||||
|
public LoginRequest {
|
||||||
|
email = EmailAddresses.normalize(email);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "LoginRequest[redacted]";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
package com.linkerbot.cadworld.dto.auth;
|
||||||
|
|
||||||
|
public record LoginResponse(String token, String tokenType, long expiresIn, LoginUserResponse user) {
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "LoginResponse[tokenType=" + tokenType + ", expiresIn=" + expiresIn + "]";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
package com.linkerbot.cadworld.dto.auth;
|
||||||
|
|
||||||
|
public record LoginUserResponse(String userCode, String nickname, String email) {
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
package com.linkerbot.cadworld.dto.common;
|
||||||
|
|
||||||
|
public record SuccessResponse(boolean success) {
|
||||||
|
|
||||||
|
public static SuccessResponse ok() {
|
||||||
|
return new SuccessResponse(true);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
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;
|
||||||
|
|
||||||
|
/** 新增和全量修改共用的表单字段。 */
|
||||||
|
public interface ComponentForm {
|
||||||
|
String componentName();
|
||||||
|
String category();
|
||||||
|
ComponentStatus status();
|
||||||
|
String description();
|
||||||
|
String material();
|
||||||
|
BigDecimal massKg();
|
||||||
|
Integer degreesOfFreedom();
|
||||||
|
RotationAxis rotationAxis();
|
||||||
|
String functionDescription();
|
||||||
|
String shape();
|
||||||
|
String size();
|
||||||
|
BigDecimal torqueNm();
|
||||||
|
JsonNode bomList();
|
||||||
|
JsonNode urdfInfo();
|
||||||
|
List<CustomField> basicFields();
|
||||||
|
List<CustomField> parameterFields();
|
||||||
|
}
|
||||||
+16
@@ -0,0 +1,16 @@
|
|||||||
|
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,
|
||||||
|
LocalDateTime createdAt, LocalDateTime updatedAt
|
||||||
|
) { }
|
||||||
+21
@@ -0,0 +1,21 @@
|
|||||||
|
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;
|
||||||
|
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,
|
||||||
|
JsonNode urdfInfo, List<CustomField> basicFields, List<CustomField> parameterFields,
|
||||||
|
String stepObjectKey, String stepUrl, String urdfPrefix, String urdfBaseUrl,
|
||||||
|
String urdfMainObjectKey, String urdfUrl, List<UrdfFile> urdfFiles, Long version,
|
||||||
|
LocalDateTime createdAt, LocalDateTime updatedAt
|
||||||
|
) { }
|
||||||
+34
@@ -0,0 +1,34 @@
|
|||||||
|
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.*;
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
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,
|
||||||
|
@Min(0) @JsonDeserialize(using = DegreesOfFreedomDeserializer.class) Integer degreesOfFreedom,
|
||||||
|
RotationAxis rotationAxis,
|
||||||
|
@Size(max = 512) String functionDescription,
|
||||||
|
@Size(max = 128) String shape,
|
||||||
|
@Size(max = 128) String size,
|
||||||
|
@DecimalMin("0") @Digits(integer = 12, fraction = 6) BigDecimal torqueNm,
|
||||||
|
JsonNode bomList,
|
||||||
|
JsonNode urdfInfo,
|
||||||
|
@Size(max = 100) List<@NotNull @Valid CustomField> basicFields,
|
||||||
|
@Size(max = 100) List<@NotNull @Valid CustomField> parameterFields,
|
||||||
|
@NotBlank @Size(max = 4096) String uploadSessionToken,
|
||||||
|
@NotBlank @Size(max = 512) String stepObjectKey,
|
||||||
|
@Size(max = 1000) List<@NotBlank @Size(max = 512) String> urdfObjectKeys
|
||||||
|
) implements ComponentForm {
|
||||||
|
@Override public String toString() { return "CreateComponentRequest[redacted]"; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
package com.linkerbot.cadworld.dto.component;
|
||||||
|
|
||||||
|
import jakarta.validation.constraints.NotBlank;
|
||||||
|
import jakarta.validation.constraints.NotNull;
|
||||||
|
import jakarta.validation.constraints.Size;
|
||||||
|
|
||||||
|
public record CustomField(@NotBlank @Size(max = 64) String name,
|
||||||
|
@NotNull @Size(max = 2000) String value) { }
|
||||||
+22
@@ -0,0 +1,22 @@
|
|||||||
|
package com.linkerbot.cadworld.dto.component;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.core.JsonParser;
|
||||||
|
import com.fasterxml.jackson.core.JsonToken;
|
||||||
|
import com.fasterxml.jackson.databind.DeserializationContext;
|
||||||
|
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
/** 自由度仅接受 JSON 整数,避免小数截断或字符串隐式转换。 */
|
||||||
|
public class DegreesOfFreedomDeserializer extends StdDeserializer<Integer> {
|
||||||
|
public DegreesOfFreedomDeserializer() {
|
||||||
|
super(Integer.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Integer deserialize(JsonParser parser, DeserializationContext context) throws IOException {
|
||||||
|
if (!parser.hasToken(JsonToken.VALUE_NUMBER_INT)) {
|
||||||
|
return context.reportInputMismatch(Integer.class, "自由度必须为整数");
|
||||||
|
}
|
||||||
|
return parser.getIntValue();
|
||||||
|
}
|
||||||
|
}
|
||||||
+36
@@ -0,0 +1,36 @@
|
|||||||
|
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.*;
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
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,
|
||||||
|
@Min(0) @JsonDeserialize(using = DegreesOfFreedomDeserializer.class) Integer degreesOfFreedom,
|
||||||
|
RotationAxis rotationAxis,
|
||||||
|
@Size(max = 512) String functionDescription,
|
||||||
|
@Size(max = 128) String shape,
|
||||||
|
@Size(max = 128) String size,
|
||||||
|
@DecimalMin("0") @Digits(integer = 12, fraction = 6) BigDecimal torqueNm,
|
||||||
|
JsonNode bomList,
|
||||||
|
@NotNull JsonNode urdfInfo,
|
||||||
|
@Size(max = 100) List<@NotNull @Valid CustomField> basicFields,
|
||||||
|
@Size(max = 100) List<@NotNull @Valid CustomField> parameterFields,
|
||||||
|
@NotNull @Min(1) @Max(4294967295L) Long version,
|
||||||
|
@Size(max = 4096) String uploadSessionToken,
|
||||||
|
@Size(max = 512) String stepObjectKey,
|
||||||
|
@Size(min = 1, max = 1000) List<@NotBlank @Size(max = 512) String> urdfObjectKeys
|
||||||
|
) implements ComponentForm {
|
||||||
|
@Override public String toString() { return "UpdateComponentRequest[redacted]"; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
package com.linkerbot.cadworld.dto.component;
|
||||||
|
|
||||||
|
public record UrdfFile(String relativePath, long sizeBytes) { }
|
||||||
+14
@@ -0,0 +1,14 @@
|
|||||||
|
package com.linkerbot.cadworld.dto.demand;
|
||||||
|
|
||||||
|
import jakarta.validation.constraints.NotBlank;
|
||||||
|
import jakarta.validation.constraints.NotNull;
|
||||||
|
import jakarta.validation.constraints.Pattern;
|
||||||
|
import jakarta.validation.constraints.Size;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public record DemandMessageRequest(
|
||||||
|
@NotBlank @Pattern(regexp = "[A-Za-z0-9_-]{1,80}") String messageId,
|
||||||
|
@NotNull @Size(max = 20000) String text,
|
||||||
|
@Size(max = 4) List<@NotBlank @Pattern(regexp = "DA-[a-f0-9]{32}") String> attachmentIds) {
|
||||||
|
@Override public String toString() { return "DemandMessageRequest[messageId=" + messageId + ", attachmentCount=" + (attachmentIds == null ? 0 : attachmentIds.size()) + "]"; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
package com.linkerbot.cadworld.dto.matching;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||||
|
import com.linkerbot.cadworld.dto.component.DegreesOfFreedomDeserializer;
|
||||||
|
import jakarta.validation.constraints.Digits;
|
||||||
|
import jakarta.validation.constraints.Min;
|
||||||
|
import jakarta.validation.constraints.Max;
|
||||||
|
import jakarta.validation.constraints.NotBlank;
|
||||||
|
import jakarta.validation.constraints.PositiveOrZero;
|
||||||
|
import jakarta.validation.constraints.Size;
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
public record PartRequirements(
|
||||||
|
@NotBlank @Size(max = 64) String category,
|
||||||
|
@Size(max = 128) String material,
|
||||||
|
@Min(0) @JsonDeserialize(using = DegreesOfFreedomDeserializer.class) Integer degreesOfFreedom,
|
||||||
|
@PositiveOrZero @Digits(integer = 12, fraction = 6) BigDecimal massKg,
|
||||||
|
@PositiveOrZero @Digits(integer = 12, fraction = 6) BigDecimal torqueNm,
|
||||||
|
@Size(max = 512) String functionDescription,
|
||||||
|
@Size(max = 128) String shape,
|
||||||
|
@Size(max = 128) String size,
|
||||||
|
Map<String, String> operators,
|
||||||
|
@Size(max = 128) String componentName,
|
||||||
|
@Size(max = 20000) String description,
|
||||||
|
@Min(1) @Max(24) @JsonDeserialize(using = QuantityDeserializer.class) Integer quantity) {
|
||||||
|
public PartRequirements(String category, String material, Integer degreesOfFreedom, BigDecimal massKg,
|
||||||
|
BigDecimal torqueNm, String functionDescription, String shape, String size, Map<String, String> operators,
|
||||||
|
String componentName, String description) {
|
||||||
|
this(category, material, degreesOfFreedom, massKg, torqueNm, functionDescription, shape, size, operators, componentName, description, null);
|
||||||
|
}
|
||||||
|
public PartRequirements(String category, String material, Integer degreesOfFreedom, BigDecimal massKg,
|
||||||
|
BigDecimal torqueNm, String functionDescription, String shape, String size, Map<String, String> operators) {
|
||||||
|
this(category, material, degreesOfFreedom, massKg, torqueNm, functionDescription, shape, size, operators, null, null, null);
|
||||||
|
}
|
||||||
|
}
|
||||||
+31
@@ -0,0 +1,31 @@
|
|||||||
|
package com.linkerbot.cadworld.dto.matching;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
|
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||||
|
import com.linkerbot.cadworld.enums.RotationAxis;
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
|
||||||
|
/** 用户端白名单:不得通过序列化实体添加数据库ID或内部存储字段。 */
|
||||||
|
public record PublicComponentResponse(
|
||||||
|
String componentCode, String componentName, String category, String description, String material,
|
||||||
|
BigDecimal massKg, Integer degreesOfFreedom, @JsonInclude(JsonInclude.Include.ALWAYS) RotationAxis rotationAxis,
|
||||||
|
String functionDescription, String shape, String size,
|
||||||
|
BigDecimal torqueNm, JsonNode bomList, JsonNode urdfInfo, Long version, String stepUrl, String urdfUrl,
|
||||||
|
@JsonInclude(JsonInclude.Include.NON_NULL) String instanceId) {
|
||||||
|
public PublicComponentResponse(String componentCode, String componentName, String category, String description, String material,
|
||||||
|
BigDecimal massKg, Integer degreesOfFreedom, RotationAxis rotationAxis,
|
||||||
|
String functionDescription, String shape, String size, BigDecimal torqueNm,
|
||||||
|
JsonNode bomList, JsonNode urdfInfo, Long version, String stepUrl, String urdfUrl) {
|
||||||
|
this(componentCode, componentName, category, description, material, massKg, degreesOfFreedom, rotationAxis,
|
||||||
|
functionDescription, shape, size, torqueNm, bomList, urdfInfo, version, stepUrl, urdfUrl, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public PublicComponentResponse withInstanceId(String value) {
|
||||||
|
return new PublicComponentResponse(componentCode, componentName, category, description, material, massKg,
|
||||||
|
degreesOfFreedom, rotationAxis, functionDescription, shape, size, torqueNm, bomList, urdfInfo, version, stepUrl, urdfUrl, value);
|
||||||
|
}
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "PublicComponentResponse[componentCode=" + componentCode + ", category=" + category + ", version=" + version + "]";
|
||||||
|
}
|
||||||
|
}
|
||||||
+18
@@ -0,0 +1,18 @@
|
|||||||
|
package com.linkerbot.cadworld.dto.matching;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.core.JsonParser;
|
||||||
|
import com.fasterxml.jackson.core.JsonToken;
|
||||||
|
import com.fasterxml.jackson.databind.DeserializationContext;
|
||||||
|
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
/** 实例数量仅接受 JSON 整数,避免小数截断和字符串隐式转换。 */
|
||||||
|
public class QuantityDeserializer extends StdDeserializer<Integer> {
|
||||||
|
public QuantityDeserializer() { super(Integer.class); }
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Integer deserialize(JsonParser parser, DeserializationContext context) throws IOException {
|
||||||
|
if (!parser.hasToken(JsonToken.VALUE_NUMBER_INT)) return context.reportInputMismatch(Integer.class, "组件数量必须为整数");
|
||||||
|
return parser.getIntValue();
|
||||||
|
}
|
||||||
|
}
|
||||||
+22
@@ -0,0 +1,22 @@
|
|||||||
|
package com.linkerbot.cadworld.dto.matching;
|
||||||
|
|
||||||
|
import jakarta.validation.Valid;
|
||||||
|
import jakarta.validation.constraints.NotBlank;
|
||||||
|
import jakarta.validation.constraints.NotEmpty;
|
||||||
|
import jakarta.validation.constraints.NotNull;
|
||||||
|
import jakarta.validation.constraints.Size;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public record RobotMatchRequest(
|
||||||
|
@Size(max = 4000) String userInput,
|
||||||
|
@Size(max = 32) List<@NotBlank @Size(max = 128) String> requirements,
|
||||||
|
@NotEmpty @Size(max = 24) List<@NotBlank @Size(max = 64) String> requiredParts,
|
||||||
|
@Valid RobotRequirements robotRequirements,
|
||||||
|
@Size(max = 16) List<@NotNull @Valid PartRequirements> partRequirements) {
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "RobotMatchRequest[requiredPartCount=" + (requiredParts == null ? 0 : requiredParts.size())
|
||||||
|
+ ", keywordCount=" + (requirements == null ? 0 : requirements.size())
|
||||||
|
+ ", partRequirementCount=" + (partRequirements == null ? 0 : partRequirements.size()) + "]";
|
||||||
|
}
|
||||||
|
}
|
||||||
+42
@@ -0,0 +1,42 @@
|
|||||||
|
package com.linkerbot.cadworld.dto.matching;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public record RobotMatchResponse(
|
||||||
|
String status, String rootCategory, List<PublicComponentResponse> parts,
|
||||||
|
List<Connection> connections, List<Alternatives> alternatives, Totals totals,
|
||||||
|
List<UnmetRequirement> unmetRequirements, List<String> unmatchedKeywords,
|
||||||
|
List<MissingPart> missingParts, List<MissingPartGroup> missingPartGroups, boolean searchLimited) {
|
||||||
|
|
||||||
|
public RobotMatchResponse(String status, String rootCategory, List<PublicComponentResponse> parts,
|
||||||
|
List<Connection> connections, List<Alternatives> alternatives, Totals totals,
|
||||||
|
List<UnmetRequirement> unmetRequirements, List<String> unmatchedKeywords,
|
||||||
|
List<MissingPart> missingParts, boolean searchLimited) {
|
||||||
|
this(status, rootCategory, parts, connections, alternatives, totals, unmetRequirements, unmatchedKeywords,
|
||||||
|
missingParts, List.of(), searchLimited);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** category 表示本次装配角色;interfaceChild 保留父接口原始 child,子接口通过下标定位。 */
|
||||||
|
public record Connection(String parentCategory, String parentComponentCode, String parentLink,
|
||||||
|
String frameName, String childCategory, String childComponentCode,
|
||||||
|
String childRootLink, String parentInstanceId, String childInstanceId,
|
||||||
|
String interfaceChild, int parentFrameIndex, int childFrameIndex) { }
|
||||||
|
|
||||||
|
public record Totals(long degreesOfFreedom, BigDecimal massKg, BigDecimal knownMassKg, boolean massComplete) { }
|
||||||
|
|
||||||
|
public record UnmetRequirement(String scope, String category, String field, String operator,
|
||||||
|
Object expected, Object actual, String reason) { }
|
||||||
|
|
||||||
|
public record MissingPart(String category, String reason, int expectedQuantity, int actualQuantity, int missingQuantity) {
|
||||||
|
public MissingPart(String category, String reason) { this(category, reason, 1, 0, 1); }
|
||||||
|
}
|
||||||
|
|
||||||
|
public record MissingPartGroup(String family, List<String> categories, String reason,
|
||||||
|
int expectedQuantity, int actualQuantity, int missingQuantity) { }
|
||||||
|
|
||||||
|
public record Alternatives(String category, String instanceId, List<Replacement> items) { }
|
||||||
|
|
||||||
|
public record Replacement(PublicComponentResponse component, List<Connection> connections, Totals totals,
|
||||||
|
List<UnmetRequirement> unmetRequirements, List<String> unmatchedKeywords) { }
|
||||||
|
}
|
||||||
+16
@@ -0,0 +1,16 @@
|
|||||||
|
package com.linkerbot.cadworld.dto.matching;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||||
|
import com.linkerbot.cadworld.dto.component.DegreesOfFreedomDeserializer;
|
||||||
|
import jakarta.validation.constraints.Digits;
|
||||||
|
import jakarta.validation.constraints.Min;
|
||||||
|
import jakarta.validation.constraints.PositiveOrZero;
|
||||||
|
import jakarta.validation.constraints.Size;
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
public record RobotRequirements(
|
||||||
|
@Min(0) @JsonDeserialize(using = DegreesOfFreedomDeserializer.class) Integer degreesOfFreedom,
|
||||||
|
@PositiveOrZero @Digits(integer = 12, fraction = 6) BigDecimal massKg,
|
||||||
|
@Size(max = 512) String functionDescription,
|
||||||
|
Map<String, String> operators) { }
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
package com.linkerbot.cadworld.dto.matching;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/** 后端模板生成的同部位数量要求,不作为消息或结构化匹配的请求参数。 */
|
||||||
|
public record TemplatePartGroup(String family, List<String> categories, int minimumQuantity) { }
|
||||||
+9
@@ -0,0 +1,9 @@
|
|||||||
|
package com.linkerbot.cadworld.dto.project;
|
||||||
|
|
||||||
|
import jakarta.validation.constraints.NotBlank;
|
||||||
|
import jakarta.validation.constraints.Size;
|
||||||
|
|
||||||
|
public record CreateProjectRequest(
|
||||||
|
@NotBlank @Size(max = 64) String analysisCode,
|
||||||
|
@NotBlank @Size(max = 128) String projectName,
|
||||||
|
@Size(max = 2000) String description) { }
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
package com.linkerbot.cadworld.dto.project;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||||
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
|
import java.time.Instant;
|
||||||
|
|
||||||
|
/** 列表省略 snapshot,详情包含装配快照;不序列化数据库实体。 */
|
||||||
|
public record ProjectResponse(
|
||||||
|
String projectCode, String ownerUserCode, String projectName, String description,
|
||||||
|
String coverRelativePath, String coverUrl, String schemaVersion,
|
||||||
|
String matchStatus, String assemblyStatus, String sourceProjectCode,
|
||||||
|
String visibility, Instant publishedAt, Instant createdAt, Instant updatedAt,
|
||||||
|
@JsonInclude(JsonInclude.Include.NON_NULL) JsonNode snapshot) {
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "ProjectResponse[projectCode=" + projectCode + ", visibility=" + visibility + "]";
|
||||||
|
}
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user