Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 49249cfd7e | |||
| 8956ff9e1d | |||
| 9d8432d8bf | |||
| 0f52055f5e | |||
| cc2c8d16f0 | |||
| f9fec2b084 |
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"name": "cadworld-management-client-regression",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
"three": "0.183.2",
|
||||
"urdf-loader": "0.12.6"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/three": "0.183.1"
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,8 @@ export interface AnalysisView {
|
||||
questions: string[];
|
||||
warnings: string[];
|
||||
result: AnalysisResult | null;
|
||||
/** The saved matching snapshot returned by the new one-step API. */
|
||||
match: DemandMatch | null;
|
||||
}
|
||||
export interface AnalysisProgress {
|
||||
analysisId: string;
|
||||
@@ -29,6 +31,23 @@ export interface AnalysisProgress {
|
||||
stage: string;
|
||||
message: string;
|
||||
}
|
||||
export interface UrdfFrame {
|
||||
name: string;
|
||||
kind?: "joint" | "interface" | string;
|
||||
type?: string;
|
||||
parent?: string | null;
|
||||
child: string;
|
||||
interfaceType?: string | null;
|
||||
interfaceName?: string | null;
|
||||
isRoot?: boolean;
|
||||
synthetic?: boolean;
|
||||
originExplicit?: boolean;
|
||||
xyz?: number[];
|
||||
rpy?: number[];
|
||||
axis?: number[];
|
||||
limits?: Record<string, unknown>;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
export interface Attachment {
|
||||
attachmentId: string;
|
||||
mimeType: string;
|
||||
@@ -68,7 +87,7 @@ export interface ComponentDto {
|
||||
bomList?: unknown;
|
||||
urdfInfo: {
|
||||
rootLink?: string;
|
||||
frames?: unknown[];
|
||||
frames?: UrdfFrame[];
|
||||
assembly?: { mountingFrame?: string; pairingConvention?: string };
|
||||
[key: string]: unknown;
|
||||
};
|
||||
@@ -82,19 +101,18 @@ export interface SelectedComponent {
|
||||
}
|
||||
export interface Connection {
|
||||
parentInstanceId: string;
|
||||
parentFrame: string;
|
||||
parentLink: string;
|
||||
parentFrame: string | null;
|
||||
parentLink: string | null;
|
||||
childInstanceId: string;
|
||||
childFrame: string;
|
||||
childRootLink: string;
|
||||
parentRootToInterface: number[];
|
||||
childRootToInterface: number[];
|
||||
childRootRelativeToParentRoot: number[];
|
||||
childFrame: string | null;
|
||||
childRootLink: string | null;
|
||||
interfaceChild: string;
|
||||
parentFrameIndex: number;
|
||||
childFrameIndex: number;
|
||||
}
|
||||
export interface Assembly {
|
||||
status: "ready" | "blocked";
|
||||
rootInstanceId: string;
|
||||
matrixLayout: "column-major";
|
||||
rootInstanceId: string | null;
|
||||
connections: Connection[];
|
||||
issues: Issue[];
|
||||
}
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
export type PartCategory =
|
||||
| "torso_0"
|
||||
| "head_0"
|
||||
| "waist_0"
|
||||
| "arm_l"
|
||||
| "arm_r"
|
||||
| "hand_l"
|
||||
| "hand_r"
|
||||
| "leg_l"
|
||||
| "leg_r"
|
||||
| "foot_l"
|
||||
| "foot_r"
|
||||
| "tail_0";
|
||||
| "TORSO_0"
|
||||
| "HEAD_0"
|
||||
| "WAIST_0"
|
||||
| "ARM_L"
|
||||
| "ARM_R"
|
||||
| "HAND_L"
|
||||
| "HAND_R"
|
||||
| "LEG_L"
|
||||
| "LEG_R"
|
||||
| "FOOT_L"
|
||||
| "FOOT_R"
|
||||
| "TAIL_0";
|
||||
export interface RequirementFields {
|
||||
componentName?: string;
|
||||
degreesOfFreedom?: number;
|
||||
|
||||
@@ -50,7 +50,7 @@ const labels: Record<string, string> = {
|
||||
ankle_pitch: "踝部俯仰",
|
||||
ankle_roll: "踝部侧摆",
|
||||
arm_pitch: "肩部俯仰",
|
||||
arm_roll: "肩部侧摆",
|
||||
ARM_Roll: "肩部侧摆",
|
||||
arm_yaw: "上臂旋转",
|
||||
elbow_pitch: "肘部俯仰",
|
||||
elbow_yaw: "前臂旋转",
|
||||
|
||||
@@ -33,9 +33,6 @@ export function connectComponentGroups(
|
||||
for (const connection of connections) {
|
||||
const parent = groups.get(connection.parent)!,
|
||||
child = groups.get(connection.child)!;
|
||||
const parentPart = parts.find(
|
||||
(part) => part.item.instanceId === connection.parent,
|
||||
)!;
|
||||
const childPart = parts.find(
|
||||
(part) => part.item.instanceId === connection.child,
|
||||
)!;
|
||||
@@ -58,12 +55,12 @@ export function connectComponentGroups(
|
||||
const id = `assembly/${connection.child}`;
|
||||
pivot.name = `${id}/interface`;
|
||||
pivot.matrixAutoUpdate = false;
|
||||
pivot.matrix.copy(parentPart.frames.get(connection.parentFrame)!);
|
||||
pivot.matrix.copy(connection.parentInterface);
|
||||
rotor.name = id;
|
||||
parent.add(pivot);
|
||||
pivot.add(rotor);
|
||||
rotor.add(child);
|
||||
child.matrix.copy(childPart.frames.get(connection.childFrame)!).invert();
|
||||
child.matrix.copy(connection.childInterface).invert();
|
||||
const axis = rotationAxisVector(rotationAxis),
|
||||
vector = new Vector3(...axis);
|
||||
motions.push({
|
||||
|
||||
@@ -6,6 +6,11 @@ export function modelResourceUrl(value: string, origin: string): string {
|
||||
return resourceDownloadUrl(value, origin);
|
||||
}
|
||||
|
||||
// urdf-loader appends the separator after this package prefix.
|
||||
export function urdfPackagePath(name: string): string {
|
||||
return `package://${name}`;
|
||||
}
|
||||
|
||||
/** A placement must be rigid: never scale, shear or mirror a component. */
|
||||
export function isRigidTransform(matrix: Matrix4): boolean {
|
||||
const e = matrix.elements;
|
||||
@@ -31,14 +36,6 @@ export function isRigidTransform(matrix: Matrix4): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
// Accumulated root-to-port transforms. Match the full coordinate frames,
|
||||
// including their file-defined directions; never insert a corrective rotation.
|
||||
export function alignInterfaceFrames(parent: Matrix4, child: Matrix4): Matrix4 {
|
||||
if (!isRigidTransform(parent) || !isRigidTransform(child))
|
||||
throw Error("安装节点的坐标矩阵无效。");
|
||||
return parent.clone().multiply(child.clone().invert());
|
||||
}
|
||||
|
||||
export function resourcePath(value: string): string {
|
||||
const clean = value
|
||||
.replace(/\\/g, "/")
|
||||
|
||||
@@ -1,27 +1,40 @@
|
||||
import {
|
||||
canonicalInterfaceLinkName,
|
||||
interfaceIdentityFromLink,
|
||||
partIdentityFromFileName,
|
||||
} from "../../../shared/part-naming.ts";
|
||||
import { Matrix4 } from "three";
|
||||
import { alignInterfaceFrames } from "./assembly-plan.ts";
|
||||
import type { Assembly, SelectedComponent } from "../ai/demand-types";
|
||||
import { isRigidTransform } from "./assembly-plan.ts";
|
||||
import type {
|
||||
Assembly,
|
||||
SelectedComponent,
|
||||
UrdfFrame,
|
||||
} from "../ai/demand-types";
|
||||
|
||||
export interface ComponentFrames {
|
||||
item: SelectedComponent;
|
||||
rootLink: string;
|
||||
frames: Map<string, Matrix4>;
|
||||
/** Actual Link names from the loaded URDF, indexed by backend frame index. */
|
||||
frameLinks?: Map<number, string>;
|
||||
ports: Map<string, string>;
|
||||
urdfFrames: UrdfFrame[];
|
||||
}
|
||||
|
||||
export interface ResolvedConnection {
|
||||
parent: string;
|
||||
child: string;
|
||||
parentFrame: string;
|
||||
childFrame: string;
|
||||
relative: Matrix4;
|
||||
parentInterface: Matrix4;
|
||||
childInterface: Matrix4;
|
||||
}
|
||||
|
||||
export function interfaceCategory(name: string): string | undefined {
|
||||
return interfaceIdentityFromLink(name)?.key;
|
||||
}
|
||||
|
||||
/** Prefer declared names; for existing files use the backend's explicit port type. */
|
||||
export function componentPorts(linkNames: string[], metadata: unknown[] = []) {
|
||||
const links = new Set(linkNames);
|
||||
@@ -32,21 +45,32 @@ export function componentPorts(linkNames: string[], metadata: unknown[] = []) {
|
||||
}
|
||||
for (const value of metadata) {
|
||||
if (!value || typeof value !== "object") continue;
|
||||
const frame = value as { child?: unknown; interfaceType?: unknown };
|
||||
if (
|
||||
typeof frame.child !== "string" ||
|
||||
typeof frame.interfaceType !== "string" ||
|
||||
!links.has(frame.child) ||
|
||||
ports.has(frame.child)
|
||||
)
|
||||
const frame = value as {
|
||||
child?: unknown;
|
||||
interfaceType?: unknown;
|
||||
interfaceName?: unknown;
|
||||
};
|
||||
const child =
|
||||
typeof frame.child === "string" && links.has(frame.child)
|
||||
? frame.child
|
||||
: typeof frame.interfaceName === "string"
|
||||
? [...links].find(
|
||||
(name) =>
|
||||
canonicalInterfaceLinkName(name) === frame.interfaceName,
|
||||
)
|
||||
: undefined;
|
||||
if (!child || typeof frame.interfaceType !== "string" || ports.has(child))
|
||||
continue;
|
||||
const category = interfaceCategory(
|
||||
`LINK_${frame.interfaceType.toUpperCase()}`,
|
||||
typeof frame.interfaceName === "string"
|
||||
? frame.interfaceName
|
||||
: `LINK_${frame.interfaceType.toUpperCase()}`,
|
||||
);
|
||||
if (category) ports.set(frame.child, category);
|
||||
if (category) ports.set(child, category);
|
||||
}
|
||||
return ports;
|
||||
}
|
||||
|
||||
/** The main filename identifies the component; link names identify its sockets. */
|
||||
export function componentCategory(item: SelectedComponent): string {
|
||||
const filename = item.urdfMainPath?.split("/").at(-1) || "";
|
||||
@@ -58,113 +82,129 @@ export function componentCategory(item: SelectedComponent): string {
|
||||
}
|
||||
return (
|
||||
partIdentityFromFileName(decoded)?.key ||
|
||||
item.component.category.toLowerCase()
|
||||
item.component.category.toUpperCase()
|
||||
);
|
||||
}
|
||||
/** Display actual returned components. Business completeness never gates geometry. */
|
||||
|
||||
function frameAt(part: ComponentFrames, index: number): UrdfFrame | undefined {
|
||||
return Number.isInteger(index) && index >= 0
|
||||
? part.urdfFrames[index]
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function linkAt(part: ComponentFrames, index: number, frame: UrdfFrame): string | undefined {
|
||||
const mapped = part.frameLinks?.get(index);
|
||||
if (mapped && part.frames.has(mapped)) return mapped;
|
||||
if (part.frames.has(frame.child)) return frame.child;
|
||||
const canonical = canonicalInterfaceLinkName(frame.child);
|
||||
if (!canonical) return undefined;
|
||||
const candidates = [...part.frames.keys()].filter(
|
||||
(name) => canonicalInterfaceLinkName(name) === canonical,
|
||||
);
|
||||
return candidates.length === 1 ? candidates[0] : undefined;
|
||||
}
|
||||
|
||||
/** Resolve positions from the exact URDF frame indexes returned by the backend. */
|
||||
export function resolveAssembly(parts: ComponentFrames[], assembly: Assembly) {
|
||||
const warnings: string[] = [],
|
||||
connections: ResolvedConnection[] = [];
|
||||
const warnings: string[] = [];
|
||||
const connections: ResolvedConnection[] = [];
|
||||
const world = new Map<string, Matrix4>();
|
||||
if (!parts.length) return { world, connections, warnings };
|
||||
const root =
|
||||
parts.find((part) => part.item.instanceId === assembly.rootInstanceId) ||
|
||||
parts.find((part) => componentCategory(part.item) === "torso_0") ||
|
||||
parts[0];
|
||||
const root = parts.find(
|
||||
(part) => part.item.instanceId === assembly.rootInstanceId,
|
||||
);
|
||||
if (!root) {
|
||||
warnings.push("后端装配根实例未包含在组件列表中,未应用连接位姿。");
|
||||
return { world, connections, warnings };
|
||||
}
|
||||
world.set(root.item.instanceId, new Matrix4());
|
||||
const usedPorts = new Set<string>();
|
||||
let pending = parts.filter((part) => part !== root);
|
||||
const reasons = new Map<string, string>();
|
||||
while (pending.length) {
|
||||
if (assembly.status === "blocked") return { world, connections, warnings };
|
||||
|
||||
const byId = new Map(parts.map((part) => [part.item.instanceId, part]));
|
||||
const pending = new Map<string, (typeof assembly.connections)[number]>();
|
||||
for (const edge of assembly.connections) {
|
||||
if (pending.has(edge.childInstanceId)) {
|
||||
warnings.push(
|
||||
`${edge.childInstanceId}:后端返回多个父连接,未应用连接位姿。`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
pending.set(edge.childInstanceId, edge);
|
||||
}
|
||||
let remaining = [...pending.keys()];
|
||||
while (remaining.length) {
|
||||
let progressed = false;
|
||||
pending = pending.filter((child) => {
|
||||
const id = child.item.instanceId;
|
||||
const edges = assembly.connections.filter(
|
||||
(edge) => edge.childInstanceId === id,
|
||||
);
|
||||
if (edges.length > 1) {
|
||||
reasons.set(id, "后端返回了多个父连接");
|
||||
return true;
|
||||
}
|
||||
const edge = edges[0];
|
||||
if (edge && !world.has(edge.parentInstanceId)) {
|
||||
reasons.set(id, "父零件尚未连接");
|
||||
return true;
|
||||
}
|
||||
// The backend identifies resources and paired nodes. Always derive the
|
||||
// placement from the actual URDF frames, never from an override matrix.
|
||||
const candidates = parts.flatMap((parent) => {
|
||||
const parentId = parent.item.instanceId;
|
||||
if (
|
||||
!world.has(parentId) ||
|
||||
(edge && edge.parentInstanceId !== parentId)
|
||||
)
|
||||
return [];
|
||||
const requestedFrame = edge?.parentFrame || edge?.parentLink;
|
||||
if (requestedFrame && parent.frames.has(requestedFrame))
|
||||
return !usedPorts.has(`${parentId}/${requestedFrame}`)
|
||||
? [{ parent, frame: requestedFrame }]
|
||||
: [];
|
||||
return [...parent.ports]
|
||||
.filter(
|
||||
([frame, category]) =>
|
||||
category === componentCategory(child.item) &&
|
||||
!usedPorts.has(`${parentId}/${frame}`),
|
||||
)
|
||||
.map(([frame]) => ({ parent, frame }));
|
||||
});
|
||||
if (candidates.length !== 1) {
|
||||
reasons.set(
|
||||
id,
|
||||
candidates.length
|
||||
? "存在多个同类安装节点,无法唯一确定连接"
|
||||
: "未找到对应的父安装节点",
|
||||
remaining = remaining.filter((id) => {
|
||||
const edge = pending.get(id)!;
|
||||
const parent = byId.get(edge.parentInstanceId);
|
||||
const child = byId.get(id);
|
||||
if (!parent || !child || !world.has(edge.parentInstanceId)) return true;
|
||||
const parentFrame = frameAt(parent, edge.parentFrameIndex);
|
||||
const childFrame = frameAt(child, edge.childFrameIndex);
|
||||
if (!parentFrame?.child || !childFrame?.child) {
|
||||
warnings.push(
|
||||
`${child.item.component.componentName}:连接接口 frame 下标无效,未应用连接位姿。`,
|
||||
);
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
const ownPorts = [...child.ports].filter(
|
||||
([, category]) => category === componentCategory(child.item),
|
||||
);
|
||||
const childFrame = [
|
||||
edge?.childFrame,
|
||||
child.item.component.urdfInfo?.assembly?.mountingFrame,
|
||||
ownPorts.length === 1 ? ownPorts[0][0] : undefined,
|
||||
].find((name) => name && child.frames.has(name));
|
||||
if (!childFrame || !child.frames.has(childFrame)) {
|
||||
reasons.set(id, "无法唯一确定子安装节点");
|
||||
return true;
|
||||
}
|
||||
const { parent, frame } = candidates[0];
|
||||
let relative: Matrix4;
|
||||
try {
|
||||
relative = alignInterfaceFrames(
|
||||
parent.frames.get(frame)!,
|
||||
child.frames.get(childFrame)!,
|
||||
if (
|
||||
parentFrame.child !== edge.interfaceChild ||
|
||||
childFrame.child !== edge.interfaceChild
|
||||
) {
|
||||
warnings.push(
|
||||
`${child.item.component.componentName}:连接接口 Link 与 frame 下标不一致,未应用连接位姿。`,
|
||||
);
|
||||
} catch {
|
||||
reasons.set(id, "安装节点坐标不是有效刚体变换");
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
const parentLink = linkAt(parent, edge.parentFrameIndex, parentFrame);
|
||||
const childLink = linkAt(child, edge.childFrameIndex, childFrame);
|
||||
const parentInterface = parentLink ? parent.frames.get(parentLink) : undefined;
|
||||
const childInterface = childLink ? child.frames.get(childLink) : undefined;
|
||||
if (!parentInterface || !childInterface) {
|
||||
warnings.push(
|
||||
`${child.item.component.componentName}:无法定位连接接口 Link,未应用连接位姿。`,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
const relative = parentInterface
|
||||
.clone()
|
||||
.multiply(childInterface.clone().invert());
|
||||
if (!isRigidTransform(relative)) {
|
||||
warnings.push(
|
||||
`${child.item.component.componentName}:连接接口坐标不是有效刚体变换,未应用连接位姿。`,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
world.set(
|
||||
id,
|
||||
world.get(parent.item.instanceId)!.clone().multiply(relative),
|
||||
world.get(edge.parentInstanceId)!.clone().multiply(relative),
|
||||
);
|
||||
connections.push({
|
||||
parent: parent.item.instanceId,
|
||||
parent: edge.parentInstanceId,
|
||||
child: id,
|
||||
parentFrame: frame,
|
||||
childFrame,
|
||||
parentFrame: parentFrame.name,
|
||||
childFrame: childFrame.name,
|
||||
relative,
|
||||
parentInterface: parentInterface.clone(),
|
||||
childInterface: childInterface.clone(),
|
||||
});
|
||||
usedPorts.add(`${parent.item.instanceId}/${frame}`);
|
||||
progressed = true;
|
||||
return false;
|
||||
});
|
||||
if (!progressed) break;
|
||||
}
|
||||
for (const part of pending)
|
||||
warnings.push(
|
||||
`${part.item.component.componentName}:${reasons.get(part.item.instanceId) || "无法确定连接"},已单独展示。`,
|
||||
);
|
||||
for (const id of remaining) {
|
||||
const part = byId.get(id);
|
||||
if (part)
|
||||
warnings.push(
|
||||
`${part.item.component.componentName}:后端连接图不完整,已单独展示。`,
|
||||
);
|
||||
}
|
||||
for (const part of parts) {
|
||||
if (part !== root && !pending.has(part.item.instanceId))
|
||||
warnings.push(
|
||||
`${part.item.component.componentName}:后端未提供连接,已单独展示。`,
|
||||
);
|
||||
}
|
||||
return { world, connections, warnings };
|
||||
}
|
||||
|
||||
@@ -9,12 +9,14 @@ import {
|
||||
resourcePath,
|
||||
resolveResource,
|
||||
modelResourceUrl,
|
||||
urdfPackagePath,
|
||||
} from "./assembly-plan";
|
||||
import {
|
||||
componentPorts,
|
||||
resolveAssembly,
|
||||
type ComponentFrames,
|
||||
} from "./automatic-assembly";
|
||||
import { canonicalInterfaceLinkName } from "../../../shared/part-naming.ts";
|
||||
import type { ModelData, Vector } from "../data/model";
|
||||
import { disposeRobot } from "./robot";
|
||||
import type {
|
||||
@@ -66,7 +68,7 @@ async function loadComponent(item: SelectedComponent, signal: AbortSignal) {
|
||||
return modelResourceUrl(resolve(reference).url, window.location.origin);
|
||||
});
|
||||
loader.workingPath = resourcePath(item.urdfMainPath).replace(/[^/]*$/, "");
|
||||
loader.packages = (name) => `package://${name}/`;
|
||||
loader.packages = urdfPackagePath;
|
||||
loader.parseCollision = false;
|
||||
loader.loadMeshCb = (path, _manager, done) => {
|
||||
manager.itemStart(path);
|
||||
@@ -245,11 +247,35 @@ export async function createDemandRobot(
|
||||
...robot.links,
|
||||
}))
|
||||
entries.set(name, inverse.clone().multiply(frame.matrixWorld));
|
||||
const rawLinks = new Set(Object.keys(robot.links));
|
||||
const joints = new Map(Object.entries(robot.joints));
|
||||
const urdfFrames = item.component.urdfInfo?.frames || [];
|
||||
const frameLinks = new Map<number, string>();
|
||||
urdfFrames.forEach((frame, index) => {
|
||||
const joint = joints.get(frame.name);
|
||||
const jointChild = joint?.children.find((object) => "isURDFLink" in object)?.name;
|
||||
const canonical =
|
||||
typeof frame.interfaceName === "string"
|
||||
? frame.interfaceName
|
||||
: canonicalInterfaceLinkName(frame.child);
|
||||
const candidates = canonical
|
||||
? [...rawLinks].filter((name) => canonicalInterfaceLinkName(name) === canonical)
|
||||
: [];
|
||||
const raw = jointChild || (rawLinks.has(frame.child) ? frame.child : candidates.length === 1 ? candidates[0] : undefined);
|
||||
if (raw) frameLinks.set(index, raw);
|
||||
});
|
||||
const ports = componentPorts(
|
||||
Object.keys(robot.links),
|
||||
item.component.urdfInfo?.frames,
|
||||
urdfFrames,
|
||||
);
|
||||
return { item, rootLink: robot.name, frames: entries, ports };
|
||||
return {
|
||||
item,
|
||||
rootLink: robot.name,
|
||||
frames: entries,
|
||||
frameLinks,
|
||||
ports,
|
||||
urdfFrames,
|
||||
};
|
||||
});
|
||||
const result = resolveAssembly(frames, match.assembly);
|
||||
warnings.push(...result.warnings);
|
||||
@@ -334,9 +360,7 @@ export async function createDemandRobot(
|
||||
)!.robot;
|
||||
const moving = motion.motions.find((joint) => joint.instanceId === id);
|
||||
const jointFrame = moving
|
||||
? frames
|
||||
.find((part) => part.item.instanceId === connection.parent)!
|
||||
.frames.get(connection.parentFrame)!
|
||||
? connection.parentInterface
|
||||
: connection.relative;
|
||||
const pos = new THREE.Vector3().setFromMatrixPosition(jointFrame);
|
||||
const rot = new THREE.Euler().setFromRotationMatrix(jointFrame, "ZYX");
|
||||
@@ -345,12 +369,7 @@ export async function createDemandRobot(
|
||||
type: moving ? "continuous" : "fixed",
|
||||
assemblyJointId: moving?.id,
|
||||
childOffset: moving
|
||||
? frames
|
||||
.find((part) => part.item.instanceId === id)!
|
||||
.frames.get(connection.childFrame)!
|
||||
.clone()
|
||||
.invert()
|
||||
.toArray()
|
||||
? connection.childInterface.clone().invert().toArray()
|
||||
: undefined,
|
||||
name: `${connection.parentFrame} → ${connection.childFrame}`,
|
||||
parent: nodeId(connection.parent, parentRobot.name),
|
||||
|
||||
@@ -17,7 +17,7 @@ npm install
|
||||
npm run dev
|
||||
```
|
||||
|
||||
访问 `http://127.0.0.1:8091`。开发服务监听 `0.0.0.0`,同一局域网可通过本机 IP 加端口 8091 访问。浏览器局域网 HTTP 地址也可生成请求编号、读取 STEP 和 URDF,不依赖仅安全上下文可用的 SHA-256 API。
|
||||
访问 `http://127.0.0.1:8092`。开发服务监听 `0.0.0.0`,同一局域网可通过本机 IP 加端口 8092 访问。浏览器局域网 HTTP 地址也可生成请求编号、读取 STEP 和 URDF,不依赖仅安全上下文可用的 SHA-256 API。
|
||||
|
||||
`vite.config.ts` 将 `/admin-api` 代理至 `https://dev-cadworld-api.robotquan.com`,例如组件查询转发至 `https://dev-cadworld-api.robotquan.com/admin-api/components?page=1&size=10`,路径和查询参数保持不变。可通过 `ADMIN_API_TARGET` 环境变量覆盖,例如 `http://127.0.0.1:8992`。
|
||||
|
||||
@@ -25,7 +25,7 @@ npm run dev
|
||||
|
||||
正式部署使用 `npm run build` 生成的 `dist`,由静态 Web 服务托管。`../shared/api-origin.ts` 按页面域名选择 API:`dev-cadworld-admin.robotquan.com` 直连 `https://dev-cadworld-api.robotquan.com`,`cadworld-admin.robotquan.com` 直连 `https://cadworld-api.robotquan.com`;本机/局域网保留 Vite 开发代理。线上网页站点无需配置 `/admin-api` 代理,后端需允许对应网站的 CORS,OSS 另需允许实际上传来源。完整部署与验收要求见 `docs/deployment.md`。
|
||||
|
||||
目前文档没有认证或短信接口,登录继续保留约定的临时前端行为:填写手机号和验证码即可进入,获取验证码自动填入 `123456`。后台操作人由服务端配置决定,与前端填写手机号无关。
|
||||
管理端使用管理员邮箱和图片验证码登录;接口契约见 `../docs/auth-api(1).md`。后台操作人由服务端配置决定,与登录邮箱无关。
|
||||
|
||||
## 上传时读取 URDF 点位
|
||||
|
||||
@@ -78,7 +78,7 @@ npm run format:check
|
||||
|
||||
URDF 零件与接口的命名、识别和保存约定见 [命名规则](docs/part-naming.md)。新建或替换 URDF 时按主文件名识别类型及左右,通过现有 `basicFields` 保存,原始安装坐标保持不变。
|
||||
|
||||
选择可识别的 URDF 后零件分类与文件识别结果统一(如 `torso_0`、`arm_l`),只读展示并作为 `category` 保存;其他情况分类可编辑或留空。列表分类建议使用同一套匹配键,通过后端已有 category 参数精确筛选。历史未规范命名的已保存文件保留原分类,替换 URDF 后按新命名自动识别。
|
||||
选择可识别的 URDF 后零件分类与文件识别结果统一(如 `TORSO_0`、`ARM_L`),只读展示并作为 `category` 保存;其他情况分类可编辑或留空。列表分类建议使用同一套匹配键,通过后端已有 category 参数精确筛选。历史未规范命名的已保存文件保留原分类,替换 URDF 后按新命名自动识别。
|
||||
|
||||
## 坐标一致性回归(2026-10-14)
|
||||
|
||||
|
||||
@@ -437,15 +437,15 @@ const saved = await uploadAndSave(
|
||||
|
||||
## 7. 用户管理
|
||||
|
||||
保持现有行为和表结构。列表支持 `page`、`size`、`keyword`(手机号或昵称)、`userType`(NORMAL / ADMIN)、`status`(ACTIVE / DISABLED)。详情返回 `id`、`phone`、`nickname`、`status`、`userType`、`createdAt`、`updatedAt`。
|
||||
列表支持 `page`、`size`、`keyword`(邮箱或昵称)、`userType`(NORMAL / ADMIN)、`status`(ACTIVE / DISABLED)。详情返回 `id`、`email`、`nickname`、`status`、`userType`、`createdAt`、`updatedAt`。
|
||||
|
||||
POST / PUT 请求:
|
||||
|
||||
```json
|
||||
{ "phone": "13812345678", "nickname": "测试用户", "status": "ACTIVE", "userType": "NORMAL" }
|
||||
{ "email": "user@example.com", "nickname": "测试用户", "status": "ACTIVE", "userType": "NORMAL" }
|
||||
```
|
||||
|
||||
手机号需符合大陆手机号格式并保持唯一,昵称必填且最多 64 字符。创建省略状态和类型时默认为 ACTIVE / NORMAL;修改省略则保留原值。逻辑删除后列表及详情不再返回该用户,手机号仍被占用。用户管理只记录运行日志。
|
||||
邮箱需为有效邮箱且保持唯一(最多 254 字符),昵称必填且最多 64 字符。邮箱去除首尾空格并转小写后校验。创建省略状态和类型时默认为 ACTIVE / NORMAL;修改省略则保留原值。逻辑删除后列表及详情不再返回该用户,邮箱仍被占用。用户管理只记录运行日志。
|
||||
|
||||
## 8. 通用操作日志
|
||||
|
||||
@@ -519,17 +519,17 @@ POST / PUT 请求:
|
||||
| 409 | COMPONENT_CODE_DUPLICATE | 同一编码已保存,不要重复新增 |
|
||||
| 404 | COMPONENT_NOT_FOUND | 组件不存在或已删除 |
|
||||
| 404 | USER_NOT_FOUND / OPERATION_LOG_NOT_FOUND | 对应记录不存在 |
|
||||
| 409 | USER_PHONE_DUPLICATE | 手机号已占用,包含逻辑删除用户 |
|
||||
| 409 | USER_EMAIL_DUPLICATE | 邮箱已占用,包含逻辑删除用户 |
|
||||
| 500 | OSS_UPLOAD_SIGN_FAILED | 根据 requestId 排查签名配置或 OSS 调用 |
|
||||
|
||||
OSS 直传错误直接来自 OSS,不使用后台统一响应。后台保存成功才表示组件及资源引用已生效。
|
||||
|
||||
## 新增旋转轴 rotationAxis(2026-10-15)
|
||||
|
||||
组件新增、编辑请求以及详情、列表与匹配结果中的组件 DTO 增加可选顶层字段 `rotationAxis`。值为 `x`、`y`、`z`、`-x`、`-y`、`-z` 或 `null`;字母按小写保存。留空提交 `null`,表示固定连接;编辑时提交 `null` 也必须清除之前的轴。
|
||||
组件新增、编辑请求以及详情、列表与匹配结果中的组件 DTO 增加可选顶层字段 `rotationAxis`。值为 `X`、`Y`、`Z`、`-X`、`-Y`、`-Z` 或 `null`;请求按大写提交。留空提交 `null`,表示固定连接;编辑时提交 `null` 也必须清除之前的轴。
|
||||
|
||||
```json
|
||||
{ "rotationAxis": "z" }
|
||||
{ "rotationAxis": "Z" }
|
||||
```
|
||||
|
||||
后端需要保存字段,且在 `/admin-api/components` 的新增/编辑响应、详情响应和前台匹配返回的 `components[].component.rotationAxis` 中返回。此字段不放到 `urdfInfo`、`basicFields` 或 BOM 内,也不修改 URDF 原文、接口坐标或零件自由度。
|
||||
|
||||
@@ -8,47 +8,45 @@
|
||||
|
||||
例如:`头_0_兔头零自由度.urdf`、`臂_L_轻量三自由度.step`、`足_R_长连杆.stp`。
|
||||
|
||||
下划线分隔,部位和左右取前两段,其余内容是非空的模型特征描述。中文部位或对应英文均可识别;字母识别不区分大小写,但推荐按本表大写书写。原文件名、URDF 和网格不会被程序改写。`0` 表示不分左右;`L/R` 是零件的机械左右,不是屏幕左右。当前启用下表的 12 种分类。
|
||||
下划线分隔,部位和左右取前两段,其余内容是非空的模型特征描述。中文部位或大写英文部位均可识别;标准字母必须使用大写。原文件名、URDF 和网格不会被程序改写。`0` 表示不分左右;`L/R` 是零件的机械左右,不是屏幕左右。当前启用下表的 16 种分类;具有左右属性的部位允许 `L`、`R`、`0` 三种侧别。
|
||||
|
||||
| 部位 | Link 接口名 | 保存/匹配分类 |
|
||||
| ---- | -------------- | ------------- |
|
||||
| 躯干 | `LINK_TORSO_0` | `torso_0` |
|
||||
| 头 | `LINK_HEAD_0` | `head_0` |
|
||||
| 腰 | `LINK_WAIST_0` | `waist_0` |
|
||||
| 左臂 | `LINK_ARM_L` | `arm_l` |
|
||||
| 右臂 | `LINK_ARM_R` | `arm_r` |
|
||||
| 左手 | `LINK_HAND_L` | `hand_l` |
|
||||
| 右手 | `LINK_HAND_R` | `hand_r` |
|
||||
| 左足 | `LINK_LEG_L` | `leg_l` |
|
||||
| 右足 | `LINK_LEG_R` | `leg_r` |
|
||||
| 左脚 | `LINK_FOOT_L` | `foot_l` |
|
||||
| 右脚 | `LINK_FOOT_R` | `foot_r` |
|
||||
| 尾 | `LINK_TAIL_0` | `tail_0` |
|
||||
| 部位 | Link 接口名 | 保存/匹配分类 |
|
||||
| -------------------- | ----------------- | ------------- |
|
||||
| 躯干 | `LINK_TORSO_0` | `TORSO_0` |
|
||||
| 头 | `LINK_HEAD_0` | `HEAD_0` |
|
||||
| 腰 | `LINK_WAIST_0` | `WAIST_0` |
|
||||
| 臂(左/右/不分左右) | `LINK_ARM_L/R/0` | `ARM_L/R/0` |
|
||||
| 手(左/右/不分左右) | `LINK_HAND_L/R/0` | `HAND_L/R/0` |
|
||||
| 足(左/右/不分左右) | `LINK_LEG_L/R/0` | `LEG_L/R/0` |
|
||||
| 脚(左/右/不分左右) | `LINK_FOOT_L/R/0` | `FOOT_L/R/0` |
|
||||
| 尾 | `LINK_TAIL_0` | `TAIL_0` |
|
||||
|
||||
足对应 LEG,脚对应 FOOT,互不混用。旧的 PEDAL 分类不再作为足的新命名。
|
||||
|
||||
## 后台上传
|
||||
|
||||
STEP 必填,URDF、表单信息与 BOM 仍为选填。URDF 主文件或 STEP 文件符合规范时,自动生成只读分类,并保存 `basicFields` 中的 `partType` 与 `partSide`;比如 `leg` 与 `l`。仅上传 STEP 也会识别分类。
|
||||
STEP 必填,URDF、表单信息与 BOM 仍为选填。URDF 主文件或 STEP 文件符合规范时,自动生成只读分类,并保存 `basicFields` 中的 `partType` 与 `partSide`;比如 `LEG` 与 `L`。仅上传 STEP 也会识别分类。
|
||||
|
||||
优先读取 URDF 主文件名,未识别时读取 STEP 文件名。两者都识别但部位或左右不同,显示具体错误并阻止提交;特征描述可以不同。文件名未识别时,保留手填分类能力,不新增必填项。文件夹名、STL 名、robot name 不参与零件分类。
|
||||
|
||||
```json
|
||||
{
|
||||
"category": "leg_l",
|
||||
"category": "LEG_L",
|
||||
"basicFields": [
|
||||
{ "name": "partType", "value": "leg" },
|
||||
{ "name": "partSide", "value": "l" }
|
||||
{ "name": "partType", "value": "LEG" },
|
||||
{ "name": "partSide", "value": "L" }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
`urdfInfo.frames` 保留原始 joint、parent/child、xyz/rpy、axis、limit;child link 按本表识别后生成 `interfaceType`。URDF 根 link 在 `rootLink` 中保留,前台也能从实际文件识别根 link 接口。
|
||||
`urdfInfo.frames` 保留原始 joint、parent/child、xyz/rpy、axis、limit;child link 按本表识别后生成大写 `interfaceType`,并生成过滤 `#id` 后的 `interfaceName`。原始 `child` 不改写,以便和实际 URDF/joint 对齐。URDF 根 link 在 `rootLink` 中保留;如果根 link 符合本表命名规则,frames 末尾追加 `kind: "interface"` 的 `__root_interface__` 合成接口,供后端按真实根 Link 参与装配匹配。
|
||||
|
||||
## 前台装配
|
||||
|
||||
主 URDF 文件名确定零件分类,文件名未识别时使用接口返回的分类。同类、同侧接口匹配,如父 `LINK_LEG_L` 对子 `LINK_LEG_L`;不会把 LEG 接到 FOOT,也不会把 L 接到 R。后端明确给定节点配对时使用明确节点。
|
||||
主 URDF 文件名确定大写零件分类,文件名未识别时使用接口返回的分类。同类、同侧接口匹配,如父 `LINK#1_LEG_L` 对子 `LINK#2_LEG_L`;不会把 LEG 接到 FOOT,也不会把 L 接到 R。后端明确给定节点配对时使用实际 Link 名。
|
||||
|
||||
从实际 URDF 累积关节变换,令父子安装接口坐标系重合:`子零件变换 = 父接口变换 × 子接口变换的逆`。内部 joint / visual / mesh 的坐标、方向和单位保持原样,不添加自动翻转。旧缓存的 `urdfInfo.frames.interfaceType` 不覆盖文件中 Link 名的识别结果。多个同类节点无法唯一配对时提示并单独展示,不随机选取。
|
||||
|
||||
旧的 `LINK_head`、`Link-head`、省略 0、中文 Link 或 PEDAL 接口不再按新规范自动识别;模型资源仍可加载。机械需要在源文件中修改 Link 并同步 joint 的引用后重新上传;只改文件名不会改变文件内部接口。旧记录不会被批量修改。服务器的检索目录和 AI 分类也应将旧 `pedal_l/r` 同步为 `leg_l/r`。
|
||||
小写 Link、缺少部件或侧别、中文 Link、PEDAL 接口均不按新规范自动识别;模型资源仍可加载。重复接口使用 `LINK#id_...`,分类时过滤 `#id`,原始 Link 名保留在 URDF 信息中。服务器的检索目录和 AI 分类统一使用大写分类键。
|
||||
|
||||
接口 `joint/origin` 的坐标系方向、父子组件的 `+Z/+X` 约定以及导出检查清单,见 [URDF 组件接口坐标系导出规范](./urdf-interface-coordinate.md)。
|
||||
|
||||
@@ -15,8 +15,9 @@
|
||||
"kind": "joint",
|
||||
"type": "fixed",
|
||||
"parent": "BASE",
|
||||
"child": "LINK_head",
|
||||
"interfaceType": "head_0",
|
||||
"child": "LINK#1_HEAD_0",
|
||||
"interfaceName": "LINK_HEAD_0",
|
||||
"interfaceType": "HEAD_0",
|
||||
"originExplicit": true,
|
||||
"xyz": [0, 0.0434269852498788, 0],
|
||||
"rpy": [-1.5707963267949, -1.5707963267949, 0],
|
||||
@@ -29,11 +30,11 @@
|
||||
```
|
||||
|
||||
- `robotName` 是 robot/name;`rootLink` 根据文件内部 joint 关系确定。
|
||||
- `frames` 按文件顺序保留全部 joint。`parent` / `child` 是文件内节点引用,不表示与其他组件的装配关系。
|
||||
- `frames` 按文件顺序保留全部 joint;根 Link 符合 `LINK_<部位>_<左右>` 命名规则时,末尾追加一个 `kind: "interface"` 的合成根接口 frame。Joint frame 的 `parent` / `child` 是文件内节点引用,不表示与其他组件的装配关系;interface frame 的 `child` 是可装配的真实根 Link,`parent` 为 `null`。
|
||||
- `xyz` 为 joint/origin/xyz,单位米;`rpy` 为 joint/origin/rpy,单位弧度;保留源文件数值精度,不改变位置、轴向或添加安装偏移。
|
||||
- `originExplicit` 表示文件是否显式声明 joint/origin。`xyz`、`rpy`、`axis` 文件未定义则省略,不自行补零。
|
||||
- `limits` 按文件保留 lower、upper、effort、velocity;未定义为 `{}`。
|
||||
- `interfaceType` 是 child 名按约定规则识别出的零件匹配键,例如 LINK_head → head_0、LINK_arm_r → arm_r;无法识别为 null。它是名称分类,不是推断安装关系。
|
||||
- `interfaceType` 是 child 名按约定规则识别出的零件匹配键,例如 LINK#1_HEAD_0 → HEAD_0、LINK_ARM_R → ARM_R;无法识别为 null。`interfaceName` 是过滤 #id 后的标准 Link 名。它们是名称分类,不是推断安装关系。
|
||||
- 新选/替换 URDF 时重新解析并替换整个 `urdfInfo`。撤销替换时恢复已有详情值。仅改表单或 STEP 时完整保留详情返回的 JSON(包括后端额外字段或其他结构),不以预览解析覆盖。
|
||||
- 保存响应同时核对 `bomList` 和 `urdfInfo`。若数据缺失或改变,保留当前输入和已保存 ID,重试使用 PUT,避免重复新增。
|
||||
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
# URDF 组件接口坐标系导出规范
|
||||
|
||||
本文面向为组件库导出 URDF 的机械工程师,说明本项目如何识别接口,以及如何设置 `joint` 和 `Link` 坐标系,保证组件拼装后的方向正确。
|
||||
|
||||
## 一条必须遵守的规则
|
||||
|
||||
系统不会猜测模型正反面,也不会在拼装时自动旋转或翻转子组件。它使父、子两个接口的坐标系**完全重合**:原点重合,`+X`、`+Y`、`+Z` 三个方向也分别同向。
|
||||
|
||||
```text
|
||||
子组件世界位姿 = 父接口世界位姿 x 子接口相对组件根的位姿的逆
|
||||
```
|
||||
|
||||
因此,接口不是“只有一个安装方向的点”,而是一个完整的右手坐标系。导出错误的 `xyz` 或 `rpy`,都会直接导致拼装后的组件位置或方向错误。
|
||||
|
||||
## 父接口与子接口的方向关系
|
||||
|
||||
设一条连接为“父组件 -> 子组件”。安装面将两个模型分在两侧,坐标系的正确关系如下:
|
||||
|
||||
```text
|
||||
父模型实体 安装面 子模型实体
|
||||
位于 -Z 侧 [ 两个接口原点重合 ] 位于 +Z 侧
|
||||
+Z ->
|
||||
```
|
||||
|
||||
拼装后,两个接口的蓝色 `+Z` 箭头是同向的,并不相向:
|
||||
|
||||
- 父接口的 `+Z` 从父组件实体指向外部,也就是指向子组件。
|
||||
- 子接口的 `+Z` 从安装面指向子组件实体内部。
|
||||
- 两个接口的红色 `+X` 也必须同向;它决定绕 `+Z` 轴的默认旋转角度。
|
||||
|
||||
从各自模型外观看,父接口箭头“朝外”、子接口箭头“朝里”;从装配后的世界坐标看,它们是同一套坐标轴。若把子接口也设置成从子模型朝外,模型就会落到父组件一侧,通常会倒置或穿模。
|
||||
|
||||
## 坐标轴含义
|
||||
|
||||
本项目的预览标记含义如下:
|
||||
|
||||
| 标记 | 含义 | 导出时的要求 |
|
||||
| --------- | ---------------------- | ---------------------------------------------------------------------- |
|
||||
| 蓝色 `+Z` | 拼装方向 | 设置为从父安装面指向子组件的一致方向 |
|
||||
| 红色 `+X` | 默认旋转朝向 | 设置为装好后的机械基准方向,例如统一的前方、关键孔位方向或电缆出口方向 |
|
||||
| 绿色 `+Y` | 由右手系推导的辅助方向 | 正常预览隐藏,仅调试时显示 |
|
||||
|
||||
`+Y` 不是独立需要填写的方向。确定 `+Z` 和 `+X` 后,`+Y = +Z x +X`,三轴必须构成右手坐标系。不要为了“看起来对称”单独反转 `+Y`;那会形成镜像坐标系,不能用刚体变换正确拼装。
|
||||
|
||||
## 接口在 URDF 中如何定义
|
||||
|
||||
系统通过**接口 Link 的名称**识别接口,而不是通过 `joint` 名称、`axis`、网格名称或自定义 XML 属性识别。
|
||||
|
||||
同一条装配连接的两端必须使用相同的规范接口名。例如躯干为手臂提供的输出接口叫 `LINK_ARM_0` 时,待安装手臂的输入根接口也应叫 `LINK_ARM_0`。名称用于接口类型匹配,`joint/origin` 决定该接口的真实位置和方向。
|
||||
|
||||
接口 Link 名称必须符合下表之一:
|
||||
|
||||
| 类型 | 接口 Link 名 |
|
||||
| ---- | ------------------------------------------- |
|
||||
| 躯干 | `LINK_TORSO_0` |
|
||||
| 头 | `LINK_HEAD_0` |
|
||||
| 腰 | `LINK_WAIST_0` |
|
||||
| 臂 | `LINK_ARM_L`、`LINK_ARM_R`、`LINK_ARM_0` |
|
||||
| 手 | `LINK_HAND_L`、`LINK_HAND_R`、`LINK_HAND_0` |
|
||||
| 足 | `LINK_LEG_L`、`LINK_LEG_R`、`LINK_LEG_0` |
|
||||
| 脚 | `LINK_FOOT_L`、`LINK_FOOT_R`、`LINK_FOOT_0` |
|
||||
| 尾 | `LINK_TAIL_0` |
|
||||
|
||||
建议每个安装接口都使用一个没有 visual/collision 的虚拟 Link,并用 `fixed joint` 将它连接到实际结构。这样接口坐标系可以独立于网格和内部机构,最稳定、最容易检查。
|
||||
|
||||
### 父组件:定义一个向外的输出接口
|
||||
|
||||
下面例子在躯干右侧建立一个供 `ARM_0` 组件接入的接口。接口原点放在实际安装面中心,`rpy` 让局部 `+Z` 指向躯干右侧外部。
|
||||
|
||||
```xml
|
||||
<link name="LINK_ARM_0" />
|
||||
|
||||
<joint name="mount_arm_0" type="fixed">
|
||||
<parent link="torso_body" />
|
||||
<child link="LINK_ARM_0" />
|
||||
<origin xyz="0 -0.0505 0.0580" rpy="1.57079632679 0 0" />
|
||||
</joint>
|
||||
```
|
||||
|
||||
上例中,`rpy="1.57079632679 0 0"` 会使局部 `+Z` 指向父组件的 `-Y` 方向。数值必须来自 CAD 中定义好的安装坐标系;例子只用于说明,不应直接复制到别的安装面。
|
||||
|
||||
### 子组件:定义一个朝向组件内部的输入接口
|
||||
|
||||
如果手臂通过根部安装到躯干,推荐让 URDF 根 Link 就是输入接口 `LINK_ARM_0`。实际手臂结构作为它的子 Link,按设计位置延伸到接口局部 `+Z` 一侧:
|
||||
|
||||
```xml
|
||||
<link name="LINK_ARM_0" />
|
||||
|
||||
<link name="arm_body">
|
||||
<visual>
|
||||
<geometry><mesh filename="package://arm/meshes/arm_body.STL" /></geometry>
|
||||
</visual>
|
||||
<collision>
|
||||
<geometry><mesh filename="package://arm/meshes/arm_body.STL" /></geometry>
|
||||
</collision>
|
||||
</link>
|
||||
|
||||
<joint name="arm_root_structure" type="fixed">
|
||||
<parent link="LINK_ARM_0" />
|
||||
<child link="arm_body" />
|
||||
<origin xyz="0 0 0" rpy="0 0 0" />
|
||||
</joint>
|
||||
```
|
||||
|
||||
此时 `LINK_ARM_0` 是子组件的输入安装面;手臂本体位于它的局部 `+Z` 一侧。装配时该根接口与父组件的 `LINK_ARM_0` 完全重合,手臂自然位于躯干外侧。
|
||||
|
||||
如果现有模型必须保留带网格的根 Link,也可以使用它作为输入接口;但仍须保证其根坐标原点在安装面,且本体位于局部 `+Z` 一侧。根 Link 没有父 joint 可以再调整坐标系,根接口的方向必须在 CAD 导出坐标系中设置正确。
|
||||
|
||||
## `joint/origin` 的正确含义
|
||||
|
||||
对任意 joint:
|
||||
|
||||
```xml
|
||||
<joint name="mount_arm_0" type="fixed">
|
||||
<parent link="torso_body" />
|
||||
<child link="LINK_ARM_0" />
|
||||
<origin xyz="x y z" rpy="roll pitch yaw" />
|
||||
</joint>
|
||||
```
|
||||
|
||||
- `origin xyz`:child Link 原点相对 parent Link 原点的位置,单位为米。
|
||||
- `origin rpy`:child Link 坐标轴相对 parent Link 坐标轴的旋转,单位为弧度。
|
||||
- 该变换决定 child Link 的完整坐标系,不只是位置。
|
||||
- URDF 的 `rpy` 顺序是 roll、pitch、yaw;推荐由 CAD 安装坐标系直接导出,避免人工试填欧拉角。
|
||||
|
||||
常用方向参考如下。它们只说明 `+Z` 的去向,实际使用时还必须检查 `+X` 是否满足默认朝向要求:
|
||||
|
||||
| `rpy` | 局部 `+Z` 在父坐标中的方向 |
|
||||
| -------------------- | -------------------------- |
|
||||
| `0 0 0` | `+Z` |
|
||||
| `0 1.57079632679 0` | `+X` |
|
||||
| `0 -1.57079632679 0` | `-X` |
|
||||
| `1.57079632679 0 0` | `-Y` |
|
||||
| `-1.57079632679 0 0` | `+Y` |
|
||||
|
||||
不要只依据 `+Z` 填写 `rpy`。两个姿态即使 `+Z` 相同,也可能绕 `+Z` 相差 180 度,导致孔位、电机、前后方向或手臂弯折方向错误;红色 `+X` 箭头就是检查这个差异的依据。
|
||||
|
||||
## 不应当当作接口方向的数据
|
||||
|
||||
- `joint/axis` 是 revolute/continuous/prismatic 关节的运动轴,不是组件拼装方向。
|
||||
- `visual/origin` 和 `collision/origin` 只描述网格相对 Link 坐标系的位置,不定义接口坐标系。
|
||||
- 内部的 `J2`、`J3`、`J4` 等关节是机构运动链的一部分。除非其 child Link 有规范的 `LINK_*` 接口名,否则不参与组件拼装。
|
||||
- `joint` 的名称可以自定义;决定接口识别的是 child Link 名称。
|
||||
- 本项目当前不读取 URDF 自定义标签来决定安装方向。即使文件添加了自定义属性,也不会改变现有装配结果。
|
||||
|
||||
## 左右接口和不分左右组件
|
||||
|
||||
左右位置不是由程序自动镜像出来的。躯干、腰等父组件的左、右接口必须分别在 URDF 中给出正确的 `xyz` 和 `rpy`;同一个 `ARM_0` 子组件装到两侧后,会完整继承各自父接口的 `+X/+Y/+Z` 姿态。
|
||||
|
||||
因此,若左右手臂出现一个朝前、一个朝后,优先检查父组件两个 `LINK_ARM_*` 接口的红色 `+X` 是否符合设计。两个接口的蓝色 `+Z` 都朝外并不代表它们的默认旋转相同;绕 `+Z` 相差 180 度会直接传递给子组件。
|
||||
|
||||
若机械设计要求左右是镜像件,请在 CAD/URDF 中明确建立对应的左、右接口坐标系,或提供左/右模型;系统不会根据 Link 名中的 `L/R` 自动镜像网格。
|
||||
|
||||
## 导出前检查清单
|
||||
|
||||
1. 每个可装配位置均创建规范命名的 `LINK_*` 接口 Link;不要只给 joint 命名。
|
||||
2. 接口原点位于实际安装基准面、孔中心或轴线中心,不要放在模型质心或网格原点。
|
||||
3. 对一条父子连接,父接口本体在局部 `-Z` 侧,子接口本体在局部 `+Z` 侧。
|
||||
4. 为接口指定明确的 `+X` 机械基准,确保拼装后孔位、前后方向和默认机构姿态正确。
|
||||
5. 接口固定在结构上时使用 `type="fixed"`;内部运动关节仍按真实 `revolute`、`continuous` 或 `prismatic` 导出。
|
||||
6. URDF 以零位姿导出:手臂、腿等机构在默认状态应处于工程规定的直立或伸直姿态,不能依赖运行时关节角度校正。
|
||||
7. 上传后台后,在 URDF 预览中检查蓝色 `+Z` 和红色 `+X`。悬停接口可定位标记;绿色 `+Y` 仅供调试。
|
||||
8. 实际拼装两个组件后检查几何是否重叠。接口坐标系正确能保证定义的姿态正确,但不能替代几何碰撞校验。
|
||||
|
||||
## 常见错误与处理
|
||||
|
||||
| 现象 | 常见原因 | 应修改的位置 |
|
||||
| --------------------------------- | ----------------------------------------------------------- | ------------------------------------------------------- |
|
||||
| 子组件完全进入父组件 | 子接口 `+Z` 也朝子模型外侧,或接口原点不在安装面 | 子组件根接口的 CAD 坐标系,或根接口到结构的 fixed joint |
|
||||
| 子组件位于正确位置但朝前/朝后反了 | 父、子接口的 `+X` 未按同一机械基准定义,绕 `+Z` 相差 180 度 | 对应接口的 `origin rpy` |
|
||||
| 左右同一组件方向不同 | 左右父接口的 `rpy` 不同;程序如实继承完整坐标系 | 父组件左右接口的 CAD 坐标系与 `origin rpy` |
|
||||
| 修改 `axis` 后拼装方向没有变化 | `axis` 仅表示内部运动轴 | 改接口 Link 的坐标系,即 parent-to-child `origin` |
|
||||
| 管理后台展示 J2/J3/J4 | 内部 child Link 误用了 `LINK_*` 命名 | 改内部 Link 名;只有真实接口使用规范名 |
|
||||
|
||||
## 本项目边界
|
||||
|
||||
当前装配只执行坐标系对齐,不会自动翻转、自动镜像、自动避让,也不会以碰撞结果修正姿态。URDF 中的接口坐标系是装配姿态的唯一机械来源;碰撞检测属于独立能力,需要在装配结果产生后按网格或简化碰撞体另行校验。
|
||||
@@ -172,7 +172,7 @@
|
||||
## 按名称识别零件与接口类型(2026-10-12)
|
||||
|
||||
- 单元测试覆盖 24 个中英文名称、两种分隔符、12 个匹配键、左右组合限制、未知名称、接口前缀规则、坐标不变、basicFields 序列化与旧类型替换;66 项测试通过。
|
||||
- 浏览器导入机械新躯干模型的临时副本,仅主文件改为 `躯干-0-机械型号.urdf`:识别 `torso_0`;J1/J2/J3/J4 子节点分别识别 `arm_r` / `head_0` / `arm_l` / `waist_0`。点位数值保留原精度,J2 可正常高亮。
|
||||
- 浏览器导入机械新躯干模型的临时副本,仅主文件改为 `躯干-0-机械型号.urdf`:识别 `TORSO_0`;J1/J2/J3/J4 子节点分别识别 `ARM_R` / `HEAD_0` / `ARM_L` / `WAIST_0`。点位数值保留原精度,J2 可正常高亮。
|
||||
- 截图 `screenshots/part-name-identity.png` 与 `screenshots/interface-name-identity.png`。没有修改原机械文件,也没有保存后端测试记录。
|
||||
- `npm run build`、`npm run format:check` 通过。类型按已有 basicFields 契约提交;后端按 partType/partSide 查询候选零件尚需增加 API 支持。
|
||||
|
||||
@@ -180,7 +180,7 @@
|
||||
|
||||
- 右侧两个标签使用 lucide-react 的 FilePenLine(零件描述)和 Network(基本信息),主品牌 Logo 保持既有图片。
|
||||
- 分类只读,使用 URDF 主文件名识别出的规范键;取消上方重复类型面板和手动分类建议。提交时 category 与 partType/partSide 由同一识别结果生成,防止旧“结构件”等手填分类混入。
|
||||
- 浏览器选择实际 `躯干_0_宽躯躯干`:分类为 torso_0 且 readOnly;替换为 `头_0_卤蛋零自由度头` 后即时更新为 head_0,模型正常加载。截图 `screenshots/automatic-part-category.png`;未上传或保存后端记录。
|
||||
- 浏览器选择实际 `躯干_0_宽躯躯干`:分类为 TORSO_0 且 readOnly;替换为 `头_0_卤蛋零自由度头` 后即时更新为 HEAD_0,模型正常加载。截图 `screenshots/automatic-part-category.png`;未上传或保存后端记录。
|
||||
- 列表提供 12 种规范分类建议,仍通过已有 category 精确筛选参数请求后端,没有添加前端记录筛选或未支持的查询字段。
|
||||
- 构建、格式检查和 67 项测试通过。
|
||||
|
||||
@@ -196,7 +196,7 @@
|
||||
- 描述页仅保留自动分类、自由度、材质、功能、形状、大小、扭矩、质量(kg)和自由描述输入框。移除名称/编码/厂商/标签及自定义字段编辑器,删除无引用的编辑组件与样式。
|
||||
- 名称由当前 URDF 主文件名生成(去扩展名),替换文件后更新;保存时再次从文件名取值。组件编码分配与上传请求沿用原流程。
|
||||
- 自由度/功能/形状/大小/扭矩保存到已有 parameterFields 的同名条目,支持详情回填、修改和清空;material/massKg/description 使用现有字段。完整 PUT 保留历史隐藏数据,避免编辑新表单时丢失旧记录。
|
||||
- 70 项测试、TypeScript 和生产构建通过。新增测试覆盖参数保存/回填/清空、历史数据保留和文件名称派生。浏览器导入躯干文件自动识别 torso_0,验证九个显示字段、内部滚动和整页无溢出;未向真实后端新增测试组件。
|
||||
- 70 项测试、TypeScript 和生产构建通过。新增测试覆盖参数保存/回填/清空、历史数据保留和文件名称派生。浏览器导入躯干文件自动识别 TORSO_0,验证九个显示字段、内部滚动和整页无溢出;未向真实后端新增测试组件。
|
||||
- 页面截图:screenshots/part-description.png。
|
||||
|
||||
## BOM Excel 导入(2026-10-12)
|
||||
|
||||
Generated
+1029
-45
File diff suppressed because it is too large
Load Diff
@@ -14,6 +14,7 @@
|
||||
"format:check": "prettier --check ."
|
||||
},
|
||||
"dependencies": {
|
||||
"antd": "^5.27.6",
|
||||
"exceljs": "4.4.0",
|
||||
"lucide-react": "^0.468.0",
|
||||
"occt-import-js": "0.0.23",
|
||||
|
||||
@@ -1,24 +1,71 @@
|
||||
import { useState, type ReactNode } from 'react'
|
||||
import { useEffect, useState, type ReactNode } from 'react'
|
||||
import { Navigate, useLocation } from 'react-router-dom'
|
||||
import { authGateway } from '@/application/auth'
|
||||
import { readAuthSession, writeAuthSession } from '@/application/auth-session'
|
||||
import {
|
||||
authGateway,
|
||||
AuthError,
|
||||
clearAuthSession,
|
||||
onAuthInvalidated,
|
||||
readAuthSession,
|
||||
writeAuthSession,
|
||||
type AuthSession,
|
||||
} from '@/application/auth'
|
||||
import { AuthContext, useAuth } from './auth-context'
|
||||
|
||||
export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const [user, setUser] = useState(readAuthSession)
|
||||
const [session, setSession] = useState<AuthSession | null>(null)
|
||||
const [ready, setReady] = useState(false)
|
||||
useEffect(() => {
|
||||
let active = true
|
||||
const session = readAuthSession()
|
||||
if (!session) {
|
||||
setReady(true)
|
||||
return
|
||||
}
|
||||
void authGateway
|
||||
.currentUser(session.token)
|
||||
.then((current) => {
|
||||
if (!active) return
|
||||
const next = { ...session, user: current }
|
||||
writeAuthSession(next)
|
||||
setSession(next)
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
if (!active) return
|
||||
const invalid =
|
||||
error instanceof AuthError &&
|
||||
(error.status === 401 ||
|
||||
error.code === 'ADMIN_ACCESS_DENIED' ||
|
||||
error.code === 'ACCOUNT_DISABLED')
|
||||
if (invalid) {
|
||||
clearAuthSession()
|
||||
setSession(null)
|
||||
} else {
|
||||
setSession(session)
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (active) setReady(true)
|
||||
})
|
||||
return () => {
|
||||
active = false
|
||||
}
|
||||
}, [])
|
||||
useEffect(() => onAuthInvalidated(() => setSession(null)), [])
|
||||
return (
|
||||
<AuthContext.Provider
|
||||
value={{
|
||||
user,
|
||||
async signIn(phone, code) {
|
||||
const next = await authGateway.signIn(phone, code)
|
||||
user: session?.user ?? null,
|
||||
ready,
|
||||
async signIn(email, captchaCode, captchaAnswer) {
|
||||
const next = await authGateway.signIn(email, captchaCode, captchaAnswer)
|
||||
writeAuthSession(next)
|
||||
setUser(next)
|
||||
setSession(next)
|
||||
},
|
||||
async leave() {
|
||||
await authGateway.signOut()
|
||||
writeAuthSession(null)
|
||||
setUser(null)
|
||||
const session = readAuthSession()
|
||||
if (session) await authGateway.signOut(session.token)
|
||||
clearAuthSession()
|
||||
setSession(null)
|
||||
},
|
||||
}}
|
||||
>
|
||||
@@ -27,8 +74,9 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
)
|
||||
}
|
||||
export function RequireSession({ children }: { children: ReactNode }) {
|
||||
const { user } = useAuth()
|
||||
const { user, ready } = useAuth()
|
||||
const location = useLocation()
|
||||
if (!ready) return <div className="loading-page">正在验证登录状态…</div>
|
||||
return user ? (
|
||||
children
|
||||
) : (
|
||||
|
||||
@@ -155,7 +155,7 @@ export function Shell() {
|
||||
<>
|
||||
<span className="account-name">
|
||||
<UserRound size={16} />
|
||||
{user.name || `${user.phone.slice(0, 3)}****${user.phone.slice(-4)}`}
|
||||
{user.nickname || user.email}
|
||||
</span>
|
||||
<button className="icon-button" aria-label="退出登录" onClick={() => void exit()}>
|
||||
<LogOut size={17} />
|
||||
|
||||
@@ -3,7 +3,8 @@ import type { AuthUser } from '@/application/auth'
|
||||
|
||||
export interface AuthContextValue {
|
||||
user: AuthUser | null
|
||||
signIn: (phone: string, code: string) => Promise<void>
|
||||
ready: boolean
|
||||
signIn: (email: string, captchaCode: string, captchaAnswer: string) => Promise<void>
|
||||
leave: () => Promise<void>
|
||||
}
|
||||
export const AuthContext: Context<AuthContextValue | null> =
|
||||
|
||||
@@ -1,35 +1,2 @@
|
||||
import type { AuthUser } from './auth'
|
||||
|
||||
const SESSION_KEY = 'cadworld-management-session'
|
||||
export function readAuthSession(): AuthUser | null {
|
||||
try {
|
||||
const raw = sessionStorage.getItem(SESSION_KEY)
|
||||
if (!raw) return null
|
||||
const session = JSON.parse(raw)
|
||||
const user = session?.user
|
||||
if (
|
||||
session.version !== 1 ||
|
||||
session.mode !== 'temporary' ||
|
||||
!user ||
|
||||
typeof user.id !== 'string' ||
|
||||
!user.id.startsWith('temporary-') ||
|
||||
typeof user.phone !== 'string' ||
|
||||
!user.phone.trim() ||
|
||||
typeof user.name !== 'string'
|
||||
)
|
||||
return null
|
||||
return { id: user.id, phone: user.phone, name: user.name }
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
export function writeAuthSession(user: AuthUser | null) {
|
||||
try {
|
||||
sessionStorage.removeItem('cadworld-management-preview')
|
||||
if (user)
|
||||
sessionStorage.setItem(SESSION_KEY, JSON.stringify({ version: 1, mode: 'temporary', user }))
|
||||
else sessionStorage.removeItem(SESSION_KEY)
|
||||
} catch {
|
||||
/* In-memory login still works when browser storage is disabled. */
|
||||
}
|
||||
}
|
||||
export { clearAuthSession, onAuthInvalidated, readAuthSession, writeAuthSession } from './auth'
|
||||
export type { AuthSession } from './auth'
|
||||
|
||||
@@ -1,16 +1,177 @@
|
||||
import { temporaryAuthGateway } from './temporary-auth'
|
||||
import { apiUrl } from '../../../shared/api-origin.ts'
|
||||
import { requestId } from '@/domain/format'
|
||||
|
||||
export interface AuthUser {
|
||||
id: string
|
||||
phone: string
|
||||
name: string
|
||||
userCode: string
|
||||
nickname: string
|
||||
email: string
|
||||
}
|
||||
|
||||
export interface AuthSession {
|
||||
token: string
|
||||
tokenType: string
|
||||
expiresAt: number
|
||||
user: AuthUser
|
||||
}
|
||||
|
||||
export interface CaptchaChallenge {
|
||||
captchaCode: string
|
||||
image: string
|
||||
expiresIn: number
|
||||
}
|
||||
|
||||
export class AuthError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
public status: number,
|
||||
public code: string,
|
||||
public requestId?: string,
|
||||
) {
|
||||
super(`${message}${requestId ? `(请求编号:${requestId})` : ''}`)
|
||||
this.name = 'AuthError'
|
||||
}
|
||||
}
|
||||
|
||||
export interface AuthGateway {
|
||||
requestCode(phone: string): Promise<string>
|
||||
signIn(phone: string, code: string): Promise<AuthUser>
|
||||
signOut(): Promise<void>
|
||||
requestCaptcha(): Promise<CaptchaChallenge>
|
||||
signIn(email: string, captchaCode: string, captchaAnswer: string): Promise<AuthSession>
|
||||
currentUser(token: string): Promise<AuthUser>
|
||||
signOut(token: string): Promise<void>
|
||||
}
|
||||
export const authGateway: AuthGateway = temporaryAuthGateway
|
||||
|
||||
interface Envelope<T> {
|
||||
code: string
|
||||
message?: string
|
||||
data?: T
|
||||
requestId?: string
|
||||
}
|
||||
|
||||
async function readEnvelope<T>(response: Response): Promise<T> {
|
||||
const body = (await response.json().catch(() => ({}))) as Envelope<T>
|
||||
if (!response.ok || body.code !== 'OK') {
|
||||
throw new AuthError(
|
||||
body.message || `请求失败,HTTP ${response.status}`,
|
||||
response.status,
|
||||
body.code || 'HTTP_ERROR',
|
||||
body.requestId || response.headers.get('X-Request-Id') || undefined,
|
||||
)
|
||||
}
|
||||
return body.data as T
|
||||
}
|
||||
|
||||
async function authRequest<T>(path: string, options: RequestInit = {}, token?: string): Promise<T> {
|
||||
const headers = new Headers(options.headers)
|
||||
headers.set('X-Request-Id', requestId())
|
||||
if (options.body && !headers.has('Content-Type')) headers.set('Content-Type', 'application/json')
|
||||
if (token) headers.set('Authorization', `Bearer ${token}`)
|
||||
const response = await fetch(apiUrl(path), {
|
||||
...options,
|
||||
credentials: 'omit',
|
||||
headers,
|
||||
})
|
||||
return readEnvelope<T>(response)
|
||||
}
|
||||
|
||||
const realAuthGateway: AuthGateway = {
|
||||
requestCaptcha() {
|
||||
return authRequest<CaptchaChallenge>('/admin-api/auth/captcha', { cache: 'no-store' })
|
||||
},
|
||||
signIn(email, captchaCode, captchaAnswer) {
|
||||
const normalizedEmail = email.trim().toLowerCase()
|
||||
return authRequest<{ token: string; tokenType: string; expiresIn: number; user: AuthUser }>(
|
||||
'/admin-api/auth/login',
|
||||
{
|
||||
method: 'POST',
|
||||
cache: 'no-store',
|
||||
body: JSON.stringify({
|
||||
email: normalizedEmail,
|
||||
captchaCode,
|
||||
captchaAnswer: captchaAnswer.trim(),
|
||||
}),
|
||||
},
|
||||
).then((data) => ({
|
||||
token: data.token,
|
||||
tokenType: data.tokenType || 'Bearer',
|
||||
expiresAt: Date.now() + data.expiresIn * 1000,
|
||||
user: data.user,
|
||||
}))
|
||||
},
|
||||
currentUser(token) {
|
||||
return authRequest<AuthUser>('/admin-api/users/me', {}, token)
|
||||
},
|
||||
async signOut(token) {
|
||||
try {
|
||||
await authRequest<null>('/admin-api/auth/logout', { method: 'POST' }, token)
|
||||
} catch {
|
||||
// Local credentials are cleared by the provider even if the server is unavailable.
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
export const authGateway = realAuthGateway
|
||||
|
||||
const AUTH_STORAGE_KEY = 'cadworld-management-auth'
|
||||
const AUTH_INVALIDATED_EVENT = 'cadworld-management-auth-invalidated'
|
||||
let memorySession: AuthSession | null = null
|
||||
|
||||
export function readAuthSession(): AuthSession | null {
|
||||
try {
|
||||
const raw = localStorage.getItem(AUTH_STORAGE_KEY)
|
||||
if (!raw) return null
|
||||
let session: Partial<AuthSession>
|
||||
try {
|
||||
session = JSON.parse(raw) as Partial<AuthSession>
|
||||
} catch {
|
||||
clearAuthSession()
|
||||
return null
|
||||
}
|
||||
const user = session.user as Partial<AuthUser> | undefined
|
||||
if (
|
||||
typeof session.token !== 'string' ||
|
||||
!session.token ||
|
||||
typeof session.tokenType !== 'string' ||
|
||||
!session.tokenType ||
|
||||
typeof session.expiresAt !== 'number' ||
|
||||
session.expiresAt <= Date.now() ||
|
||||
!user ||
|
||||
typeof user.userCode !== 'string' ||
|
||||
typeof user.nickname !== 'string' ||
|
||||
typeof user.email !== 'string'
|
||||
) {
|
||||
clearAuthSession()
|
||||
return null
|
||||
}
|
||||
return {
|
||||
token: session.token,
|
||||
tokenType: session.tokenType,
|
||||
expiresAt: session.expiresAt,
|
||||
user: { userCode: user.userCode, nickname: user.nickname, email: user.email },
|
||||
}
|
||||
} catch {
|
||||
return memorySession && memorySession.expiresAt > Date.now() ? memorySession : null
|
||||
}
|
||||
}
|
||||
|
||||
export function writeAuthSession(session: AuthSession | null): void {
|
||||
memorySession = session
|
||||
try {
|
||||
if (session) localStorage.setItem(AUTH_STORAGE_KEY, JSON.stringify(session))
|
||||
else localStorage.removeItem(AUTH_STORAGE_KEY)
|
||||
} catch {
|
||||
// The in-memory context remains usable when browser storage is disabled.
|
||||
}
|
||||
}
|
||||
|
||||
export function clearAuthSession(): void {
|
||||
writeAuthSession(null)
|
||||
window.dispatchEvent(new Event(AUTH_INVALIDATED_EVENT))
|
||||
}
|
||||
|
||||
export function onAuthInvalidated(listener: () => void): () => void {
|
||||
window.addEventListener(AUTH_INVALIDATED_EVENT, listener)
|
||||
return () => window.removeEventListener(AUTH_INVALIDATED_EVENT, listener)
|
||||
}
|
||||
|
||||
export function safeReturnPath(path: unknown): string {
|
||||
return typeof path === 'string' &&
|
||||
/^\/(components|activity|users|assembly-test)(\/[^?#]*)?(\?[^#]*)?$/.test(path)
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
import { api, queryString, downloadFile, assetUrl, type Page } from '@/infrastructure/admin-api'
|
||||
import {
|
||||
componentForm,
|
||||
hasUrdfResources,
|
||||
partInformation,
|
||||
type ComponentDetail,
|
||||
type ComponentForm,
|
||||
type ComponentStatus,
|
||||
type ComponentSummary,
|
||||
} from '@/domain/component-catalog'
|
||||
export interface ComponentResources {
|
||||
@@ -41,6 +44,14 @@ export const componentGateway = {
|
||||
async remove(id: number) {
|
||||
await api(`/admin-api/components/${id}`, { method: 'DELETE' })
|
||||
},
|
||||
async setStatus(id: number, status: ComponentStatus) {
|
||||
const item = await componentGateway.detail(String(id))
|
||||
const form = componentForm(partInformation(item))
|
||||
return api<ComponentDetail>(`/admin-api/components/${item.id}`, {
|
||||
method: 'PUT',
|
||||
body: { ...form, status, version: item.version },
|
||||
})
|
||||
},
|
||||
step(item: ComponentDetail, signal?: AbortSignal) {
|
||||
return downloadFile(assetUrl(item.stepObjectKey), item.stepObjectKey.split('/').at(-1)!, signal)
|
||||
},
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
import type { AuthGateway } from './auth'
|
||||
|
||||
/** Frontend-only temporary login. It sends no SMS and grants no backend access. */
|
||||
export const temporaryAuthGateway: AuthGateway = {
|
||||
async requestCode(phone) {
|
||||
if (!phone.trim()) throw new Error('请输入手机号。')
|
||||
return '123456'
|
||||
},
|
||||
async signIn(phone, code) {
|
||||
const value = phone.trim()
|
||||
if (!value) throw new Error('请输入手机号。')
|
||||
if (!code.trim()) throw new Error('请输入验证码。')
|
||||
return { id: `temporary-${value}`, phone: value, name: '管理员' }
|
||||
},
|
||||
async signOut() {},
|
||||
}
|
||||
@@ -2,7 +2,7 @@ import { api, queryString, type Page } from '@/infrastructure/admin-api'
|
||||
import { validateUser, type ManagedUser, type UserInput, type UserStatus } from '@/domain/users'
|
||||
interface UserDto {
|
||||
id: number
|
||||
phone: string
|
||||
email: string
|
||||
nickname: string
|
||||
userType: 'NORMAL' | 'ADMIN'
|
||||
status: 'ACTIVE' | 'DISABLED'
|
||||
@@ -13,7 +13,7 @@ function fromDto(item: UserDto): ManagedUser {
|
||||
return {
|
||||
id: String(item.id),
|
||||
name: item.nickname,
|
||||
phone: item.phone,
|
||||
email: item.email,
|
||||
role: item.userType === 'ADMIN' ? 'admin' : 'viewer',
|
||||
status: item.status === 'ACTIVE' ? 'enabled' : 'disabled',
|
||||
createdAt: item.createdAt,
|
||||
@@ -24,7 +24,7 @@ function toDto(input: UserInput) {
|
||||
const valid = validateUser(input)
|
||||
return {
|
||||
nickname: valid.name,
|
||||
phone: valid.phone,
|
||||
email: valid.email,
|
||||
userType: valid.role === 'admin' ? 'ADMIN' : 'NORMAL',
|
||||
status: valid.status === 'enabled' ? 'ACTIVE' : 'DISABLED',
|
||||
}
|
||||
|
||||
@@ -7,15 +7,25 @@ import { disposeObject } from '@/infrastructure/urdf-loader'
|
||||
import { createPointHighlight } from '@/infrastructure/point-highlight'
|
||||
import { pointView } from '@/infrastructure/viewer-camera'
|
||||
import { createPreviewModel } from '@/infrastructure/preview-model'
|
||||
import {
|
||||
createInterfaceDirectionMarker,
|
||||
disposeInterfaceDirectionMarker,
|
||||
type InterfacePoint,
|
||||
} from '@/infrastructure/interface-direction'
|
||||
import { Notice } from './ui'
|
||||
|
||||
interface Props {
|
||||
model?: THREE.Object3D | null
|
||||
busy?: boolean
|
||||
error?: string
|
||||
warning?: string
|
||||
fileName?: string
|
||||
onImport?: () => void
|
||||
highlightPoint?: THREE.Object3D | null
|
||||
interfacePoints?: InterfacePoint[]
|
||||
highlightedInterfaceName?: string | null
|
||||
/** Developer-only diagnostic axis; hidden in the normal preview. */
|
||||
showInterfaceYAxis?: boolean
|
||||
}
|
||||
interface Runtime {
|
||||
renderer: THREE.WebGLRenderer
|
||||
@@ -247,6 +257,32 @@ export function ModelPreview(props: Props) {
|
||||
value.invalidate()
|
||||
}
|
||||
}, [props.model])
|
||||
useEffect(() => {
|
||||
const value = runtime.current
|
||||
if (!value || !props.model || !props.interfacePoints?.length) return
|
||||
const markers: THREE.Group[] = []
|
||||
for (const point of props.interfacePoints) {
|
||||
const highlighted = point.name === props.highlightedInterfaceName
|
||||
const marker = createInterfaceDirectionMarker(
|
||||
props.model,
|
||||
point.object,
|
||||
highlighted ? 1.35 : 1,
|
||||
{ showYAxis: props.showInterfaceYAxis },
|
||||
)
|
||||
if (!marker) continue
|
||||
marker.userData.interfaceName = point.name
|
||||
value.scene.add(marker)
|
||||
markers.push(marker)
|
||||
}
|
||||
value.invalidate()
|
||||
return () => {
|
||||
for (const marker of markers) {
|
||||
value.scene.remove(marker)
|
||||
disposeInterfaceDirectionMarker(marker)
|
||||
}
|
||||
value.invalidate()
|
||||
}
|
||||
}, [props.model, props.interfacePoints, props.highlightedInterfaceName, props.showInterfaceYAxis])
|
||||
useEffect(() => {
|
||||
const value = runtime.current
|
||||
if (!value || !props.model || !props.highlightPoint) return
|
||||
@@ -329,6 +365,11 @@ export function ModelPreview(props: Props) {
|
||||
<Notice variant="error">{props.error || rendererError}</Notice>
|
||||
</div>
|
||||
)}
|
||||
{props.warning && !props.error && !rendererError && (
|
||||
<div className="viewer-error">
|
||||
<Notice>{props.warning}</Notice>
|
||||
</div>
|
||||
)}
|
||||
<div className="viewer-caption">
|
||||
<span>
|
||||
{props.model
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Crosshair } from 'lucide-react'
|
||||
import type { FrameVector, UrdfFrames } from '@/domain/urdf-frames'
|
||||
import { isInterfaceFrame, type FrameVector, type UrdfFrames } from '@/domain/urdf-frames'
|
||||
import { interfaceIdentityFromLink } from '@/domain/part-naming'
|
||||
import { Loading, Notice } from './ui'
|
||||
|
||||
@@ -29,16 +29,52 @@ export function UrdfInstallationPoints({
|
||||
</div>
|
||||
)
|
||||
}
|
||||
if (!data.frames.length) return <Notice>该文件没有 joint 点位信息,系统不补充安装点。</Notice>
|
||||
const interfaces = data.frames.filter(isInterfaceFrame)
|
||||
if (!interfaces.length) {
|
||||
const identity = interfaceIdentityFromLink(data.rootLink)
|
||||
return identity ? (
|
||||
<div className="urdf-frames">
|
||||
<p className="urdf-frames-note">
|
||||
该文件没有 joint;根 Link 可作为组件接口,位置为组件根坐标系。
|
||||
</p>
|
||||
<article className="urdf-frame-card" aria-label={`根 Link 接口 ${data.rootLink}`}>
|
||||
<header>
|
||||
<h3>{data.rootLink}</h3>
|
||||
<span>root link</span>
|
||||
</header>
|
||||
<dl className="urdf-frame-identity">
|
||||
<div>
|
||||
<dt>文件内父节点</dt>
|
||||
<dd>无</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>文件内子节点</dt>
|
||||
<dd>{data.rootLink}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>接口匹配类型</dt>
|
||||
<dd>{identity.key}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
<FrameValue label="XYZ" unit="m" value="0 / 0 / 0(根坐标系)" />
|
||||
<FrameValue label="RPY" unit="rad" value="0 / 0 / 0(根坐标系)" />
|
||||
</article>
|
||||
</div>
|
||||
) : (
|
||||
<Notice>未识别到可装配接口。请检查接口 child Link 是否符合命名规则。</Notice>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<div className="urdf-frames">
|
||||
<p className="urdf-frames-note">
|
||||
{onPointHover
|
||||
? '悬停点位可高亮文件原始位置,并自动转动视角查看。'
|
||||
: '按文件顺序列出全部 joint / origin,仅供查看,不是安装配置。'}
|
||||
{' 接口类型按文件中的名称识别,位置与方向保持文件原值;预览只调整相机,不自动翻转模型。'}
|
||||
: '仅列出按 Link 命名识别的可装配接口;内部关节仍保留在 URDF 中。'}
|
||||
{
|
||||
' 蓝色 +Z 箭头表示约定的拼装方向,红色 +X 表示默认旋转朝向;绿色 +Y 仅在调试模式显示。预览不修改模型姿态。'
|
||||
}
|
||||
</p>
|
||||
{data.frames.map((frame) => {
|
||||
{interfaces.map((frame) => {
|
||||
const identity = interfaceIdentityFromLink(frame.child)
|
||||
return (
|
||||
<article
|
||||
@@ -53,12 +89,14 @@ export function UrdfInstallationPoints({
|
||||
>
|
||||
<header>
|
||||
<h3>{frame.name}</h3>
|
||||
{frame.type && <span>{frame.type}</span>}
|
||||
<span>{frame.kind === 'interface' ? 'interface' : frame.type || 'joint'}</span>
|
||||
</header>
|
||||
<dl className="urdf-frame-identity">
|
||||
<div>
|
||||
<dt title="URDF 原始 parent/link">文件内父节点</dt>
|
||||
<dd>{frame.parent || '文件未定义'}</dd>
|
||||
<dd>
|
||||
{frame.parent || (frame.kind === 'interface' ? '组件根坐标系' : '文件未定义')}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt title="URDF 原始 child/link">文件内子节点</dt>
|
||||
@@ -66,7 +104,7 @@ export function UrdfInstallationPoints({
|
||||
</div>
|
||||
<div>
|
||||
<dt>接口匹配类型</dt>
|
||||
<dd>{identity ? identity.key : '未按命名规则定义'}</dd>
|
||||
<dd>{frame.interfaceType || identity?.key || '未按命名规则定义'}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
<FrameValue label="XYZ" unit="m" value={vectorText(frame.xyz)} />
|
||||
|
||||
@@ -1,20 +1,45 @@
|
||||
import { useEffect, useId, useRef, type ReactNode } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { X, AlertCircle, LoaderCircle, Box, SearchX, ChevronRight } from 'lucide-react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import {
|
||||
Alert,
|
||||
Button as AntButton,
|
||||
Empty,
|
||||
Form,
|
||||
Modal as AntModal,
|
||||
Spin,
|
||||
type ButtonProps as AntButtonProps,
|
||||
} from 'antd'
|
||||
import { ChevronRight } from 'lucide-react'
|
||||
import { type ButtonHTMLAttributes, type ReactNode } from 'react'
|
||||
import { Link, useLocation } from 'react-router-dom'
|
||||
|
||||
type ButtonVariant = 'primary' | 'secondary' | 'danger' | 'ghost'
|
||||
type NativeButtonType = 'button' | 'submit' | 'reset'
|
||||
type ButtonProps = Omit<AntButtonProps, 'type' | 'htmlType' | 'variant'> &
|
||||
Omit<ButtonHTMLAttributes<HTMLButtonElement>, 'type'> & {
|
||||
type?: NativeButtonType
|
||||
variant?: ButtonVariant
|
||||
}
|
||||
const buttonTypes: Record<ButtonVariant, AntButtonProps['type']> = {
|
||||
primary: 'primary',
|
||||
secondary: 'default',
|
||||
danger: 'primary',
|
||||
ghost: 'text',
|
||||
}
|
||||
export function Button({
|
||||
children,
|
||||
variant = 'secondary',
|
||||
className = '',
|
||||
type = 'button',
|
||||
danger,
|
||||
...props
|
||||
}: React.ButtonHTMLAttributes<HTMLButtonElement> & {
|
||||
variant?: 'primary' | 'secondary' | 'danger' | 'ghost'
|
||||
}) {
|
||||
}: ButtonProps) {
|
||||
return (
|
||||
<button type="button" className={`button button-${variant} ${className}`} {...props}>
|
||||
<AntButton
|
||||
{...props}
|
||||
danger={danger ?? variant === 'danger'}
|
||||
htmlType={type}
|
||||
type={buttonTypes[variant]}
|
||||
>
|
||||
{children}
|
||||
</button>
|
||||
</AntButton>
|
||||
)
|
||||
}
|
||||
export function Notice({
|
||||
@@ -25,10 +50,12 @@ export function Notice({
|
||||
variant?: 'info' | 'error'
|
||||
}) {
|
||||
return (
|
||||
<div className={`notice notice-${variant}`} role={variant === 'error' ? 'alert' : 'note'}>
|
||||
<AlertCircle size={17} />
|
||||
<div>{children}</div>
|
||||
</div>
|
||||
<Alert
|
||||
className="app-notice"
|
||||
message={children}
|
||||
showIcon
|
||||
type={variant === 'error' ? 'error' : 'info'}
|
||||
/>
|
||||
)
|
||||
}
|
||||
export function Field({
|
||||
@@ -43,20 +70,17 @@ export function Field({
|
||||
children: ReactNode
|
||||
}) {
|
||||
return (
|
||||
<label className="field">
|
||||
<span>
|
||||
{label}
|
||||
{required && <b> *</b>}
|
||||
</span>
|
||||
{children}
|
||||
{hint && <small>{hint}</small>}
|
||||
</label>
|
||||
<Form component={false} layout="vertical">
|
||||
<Form.Item className="app-field" extra={hint} label={label} required={required}>
|
||||
{children}
|
||||
</Form.Item>
|
||||
</Form>
|
||||
)
|
||||
}
|
||||
export function Loading({ text = '正在加载…' }: { text?: string }) {
|
||||
return (
|
||||
<div className="loading">
|
||||
<LoaderCircle size={24} className="spin" />
|
||||
<div className="app-loading" role="status">
|
||||
<Spin size="large" />
|
||||
<span>{text}</span>
|
||||
</div>
|
||||
)
|
||||
@@ -65,7 +89,6 @@ export function EmptyState({
|
||||
title,
|
||||
description,
|
||||
action,
|
||||
filtered = false,
|
||||
}: {
|
||||
title: string
|
||||
description: string
|
||||
@@ -73,16 +96,17 @@ export function EmptyState({
|
||||
filtered?: boolean
|
||||
}) {
|
||||
return (
|
||||
<div className="empty-state">
|
||||
<div className="empty-art">
|
||||
<div className="empty-art-grid" />
|
||||
{filtered ? <SearchX strokeWidth={1.25} size={46} /> : <Box strokeWidth={1.25} size={46} />}
|
||||
<span className="empty-art-dot" />
|
||||
</div>
|
||||
<h3>{title}</h3>
|
||||
<p>{description}</p>
|
||||
<Empty
|
||||
className="app-empty-state"
|
||||
description={
|
||||
<span>
|
||||
<strong>{title}</strong>
|
||||
<small>{description}</small>
|
||||
</span>
|
||||
}
|
||||
>
|
||||
{action}
|
||||
</div>
|
||||
</Empty>
|
||||
)
|
||||
}
|
||||
export function PageHeading({
|
||||
@@ -108,9 +132,10 @@ export function PageHeading({
|
||||
)
|
||||
}
|
||||
export function Breadcrumb({ section, title }: { section: 'components'; title: string }) {
|
||||
const location = useLocation()
|
||||
return (
|
||||
<div className="breadcrumb">
|
||||
<Link to={`/${section}`}>组件库</Link>
|
||||
<Link to={`/${section}${location.search}`}>组件库</Link>
|
||||
<ChevronRight size={14} />
|
||||
<span>{title}</span>
|
||||
</div>
|
||||
@@ -122,7 +147,7 @@ export function Modal({
|
||||
children,
|
||||
onClose,
|
||||
footer,
|
||||
className = '',
|
||||
className,
|
||||
}: {
|
||||
title: string
|
||||
description?: string
|
||||
@@ -131,70 +156,17 @@ export function Modal({
|
||||
footer?: ReactNode
|
||||
className?: string
|
||||
}) {
|
||||
const id = useId(),
|
||||
ref = useRef<HTMLDivElement>(null),
|
||||
close = useRef(onClose)
|
||||
close.current = onClose
|
||||
useEffect(() => {
|
||||
const previous = document.activeElement as HTMLElement | null
|
||||
const overflow = document.body.style.overflow
|
||||
document.body.style.overflow = 'hidden'
|
||||
const focusable = () =>
|
||||
Array.from(
|
||||
ref.current?.querySelectorAll<HTMLElement>(
|
||||
'button:not(:disabled),input,select,textarea,a[href],[tabindex="0"]',
|
||||
) ?? [],
|
||||
)
|
||||
focusable()[0]?.focus()
|
||||
const onKey = (event: KeyboardEvent) => {
|
||||
if (event.key === 'Escape') close.current()
|
||||
if (event.key === 'Tab') {
|
||||
const items = focusable(),
|
||||
first = items[0],
|
||||
last = items.at(-1)
|
||||
if (event.shiftKey && document.activeElement === first) {
|
||||
event.preventDefault()
|
||||
last?.focus()
|
||||
} else if (!event.shiftKey && document.activeElement === last) {
|
||||
event.preventDefault()
|
||||
first?.focus()
|
||||
}
|
||||
}
|
||||
}
|
||||
document.addEventListener('keydown', onKey)
|
||||
return () => {
|
||||
document.body.style.overflow = overflow
|
||||
document.removeEventListener('keydown', onKey)
|
||||
previous?.focus()
|
||||
}
|
||||
}, [])
|
||||
return createPortal(
|
||||
<div
|
||||
className="modal-backdrop"
|
||||
onMouseDown={(event) => {
|
||||
if (event.target === event.currentTarget) onClose()
|
||||
}}
|
||||
return (
|
||||
<AntModal
|
||||
className={className}
|
||||
destroyOnHidden
|
||||
footer={footer ?? null}
|
||||
onCancel={onClose}
|
||||
open
|
||||
title={title}
|
||||
>
|
||||
<div
|
||||
className={`modal ${className}`}
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby={id}
|
||||
ref={ref}
|
||||
>
|
||||
<header>
|
||||
<div>
|
||||
<h2 id={id}>{title}</h2>
|
||||
{description && <p>{description}</p>}
|
||||
</div>
|
||||
<button className="icon-button" aria-label="关闭弹窗" onClick={onClose}>
|
||||
<X size={20} />
|
||||
</button>
|
||||
</header>
|
||||
{children && <div className="modal-body">{children}</div>}
|
||||
{footer && <footer>{footer}</footer>}
|
||||
</div>
|
||||
</div>,
|
||||
document.body,
|
||||
{description && <p className="app-modal-description">{description}</p>}
|
||||
{children}
|
||||
</AntModal>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ export interface CustomField {
|
||||
value: string
|
||||
}
|
||||
export interface ComponentForm {
|
||||
rotationAxis?: RotationAxis | null
|
||||
rotationAxis?: Uppercase<RotationAxis> | null
|
||||
componentName: string
|
||||
category: string
|
||||
description: string
|
||||
@@ -23,10 +23,12 @@ export interface ComponentForm {
|
||||
basicFields: CustomField[]
|
||||
parameterFields: CustomField[]
|
||||
}
|
||||
export type ComponentStatus = 'ENABLED' | 'DISABLED'
|
||||
export interface ComponentSummary {
|
||||
id: number
|
||||
componentCode: string
|
||||
componentName: string
|
||||
status: ComponentStatus
|
||||
category: string
|
||||
description: string
|
||||
degreesOfFreedom: number | null
|
||||
@@ -40,7 +42,8 @@ export interface ComponentSummary {
|
||||
createdAt: string
|
||||
updatedAt: string
|
||||
}
|
||||
export interface ComponentDetail extends ComponentSummary, ComponentForm {
|
||||
export interface ComponentDetail extends ComponentSummary, Omit<ComponentForm, 'rotationAxis'> {
|
||||
rotationAxis?: Uppercase<RotationAxis> | RotationAxis | null
|
||||
stepObjectKey: string
|
||||
urdfPrefix?: string | null
|
||||
urdfMainObjectKey?: string | null
|
||||
@@ -75,12 +78,12 @@ export interface PartInformation {
|
||||
}
|
||||
export const emptyPartInformation = (): PartInformation => ({
|
||||
name: '',
|
||||
rotationAxis: '',
|
||||
rotationAxis: 'z',
|
||||
category: '',
|
||||
description: '',
|
||||
material: '',
|
||||
weightKg: '',
|
||||
degreesOfFreedom: '',
|
||||
degreesOfFreedom: '1',
|
||||
function: '',
|
||||
shape: '',
|
||||
size: '',
|
||||
@@ -188,7 +191,9 @@ export function componentForm(info: PartInformation): ComponentForm {
|
||||
throw new Error('描述超过 65535 字节')
|
||||
return {
|
||||
componentName,
|
||||
rotationAxis: parseRotationAxis(info.rotationAxis),
|
||||
rotationAxis:
|
||||
(parseRotationAxis(info.rotationAxis)?.toUpperCase() as
|
||||
Uppercase<RotationAxis> | undefined) ?? null,
|
||||
category,
|
||||
description: info.description,
|
||||
material: info.material.trim(),
|
||||
|
||||
@@ -1 +1,2 @@
|
||||
export const validPhone = (phone: string) => /^1[3-9]\d{9}$/.test(phone)
|
||||
export const validEmail = (email: string) =>
|
||||
email.length <= 254 && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)
|
||||
|
||||
@@ -8,8 +8,15 @@ export {
|
||||
partIdentityFromFileName,
|
||||
partIdentityFromSources,
|
||||
interfaceIdentityFromLink,
|
||||
interfaceLinkInfoFromName,
|
||||
canonicalInterfaceLinkName,
|
||||
} from '../../../shared/part-naming'
|
||||
export type {
|
||||
PartType,
|
||||
PartSide,
|
||||
PartIdentity,
|
||||
InterfaceLinkInfo,
|
||||
} from '../../../shared/part-naming'
|
||||
export type { PartType, PartSide, PartIdentity } from '../../../shared/part-naming'
|
||||
export const PART_IDENTITY_FIELDS = ['partType', 'partSide'] as const
|
||||
|
||||
export function isPartIdentityField(field: CustomField): boolean {
|
||||
|
||||
@@ -1,15 +1,26 @@
|
||||
import { interfaceIdentityFromLink } from './part-naming'
|
||||
import { canonicalInterfaceLinkName, interfaceIdentityFromLink } from './part-naming'
|
||||
import { cloneJson, type JsonContainer } from './json'
|
||||
|
||||
/** Serialize the same raw frames shown in the tab, retaining omitted attributes. */
|
||||
/** Serialize frame metadata for the API while retaining omitted attributes. */
|
||||
export function urdfInfoFromFrames(data: UrdfFrames): JsonContainer {
|
||||
// URDF files keep the original Link names. The API receives canonical
|
||||
// interface names so numeric Link ids never become part of matching data.
|
||||
const backendLinkName = (name: string | null | undefined) =>
|
||||
name == null ? name : (canonicalInterfaceLinkName(name) ?? name)
|
||||
return cloneJson(
|
||||
{
|
||||
...data,
|
||||
frames: data.frames.map((frame) => ({
|
||||
...frame,
|
||||
interfaceType: interfaceIdentityFromLink(frame.child)?.key ?? null,
|
||||
})),
|
||||
rootLink: backendLinkName(data.rootLink),
|
||||
frames: data.frames.map((frame) => {
|
||||
const interfaceName = canonicalInterfaceLinkName(frame.child)
|
||||
return {
|
||||
...frame,
|
||||
parent: backendLinkName(frame.parent),
|
||||
child: backendLinkName(frame.child)!,
|
||||
interfaceType: interfaceIdentityFromLink(frame.child)?.key ?? null,
|
||||
interfaceName,
|
||||
}
|
||||
}),
|
||||
},
|
||||
'URDF 基本信息',
|
||||
)
|
||||
@@ -80,10 +91,14 @@ export function parseUrdfDocument(xml: string): XMLDocument {
|
||||
export type FrameVector = [number, number, number]
|
||||
export interface UrdfFrame {
|
||||
name: string
|
||||
kind: 'joint'
|
||||
kind: 'joint' | 'interface'
|
||||
type?: string
|
||||
parent?: string
|
||||
parent?: string | null
|
||||
child: string
|
||||
interfaceName?: string | null
|
||||
interfaceType?: string | null
|
||||
isRoot?: boolean
|
||||
synthetic?: boolean
|
||||
xyz?: FrameVector
|
||||
rpy?: FrameVector
|
||||
originExplicit: boolean
|
||||
@@ -95,6 +110,13 @@ export interface UrdfFrames {
|
||||
rootLink: string
|
||||
frames: UrdfFrame[]
|
||||
}
|
||||
/** A frame is an assembly interface when its metadata or child Link name identifies one. */
|
||||
export function isInterfaceFrame(frame: UrdfFrame): boolean {
|
||||
return Boolean(
|
||||
(typeof frame.interfaceType === 'string' && frame.interfaceType.trim()) ||
|
||||
interfaceIdentityFromLink(frame.child),
|
||||
)
|
||||
}
|
||||
function vector(value: string | null | undefined, label: string): FrameVector | undefined {
|
||||
if (value == null) return undefined
|
||||
const parts = value.trim().split(/\s+/).map(Number)
|
||||
@@ -102,7 +124,7 @@ function vector(value: string | null | undefined, label: string): FrameVector |
|
||||
throw new Error(`URDF ${label} 必须是三个有效数值。`)
|
||||
return parts as FrameVector
|
||||
}
|
||||
/** Read declared frames only. A joint/link name does not imply a mounting role. */
|
||||
/** Read URDF joints and add an explicit synthetic frame for a named root interface. */
|
||||
export function readUrdfFrames(xml: string): UrdfFrames {
|
||||
const document = parseUrdfDocument(xml)
|
||||
const nodes = [...document.documentElement.children]
|
||||
@@ -140,5 +162,22 @@ export function readUrdfFrames(xml: string): UrdfFrames {
|
||||
}
|
||||
frames.push(frame)
|
||||
}
|
||||
const rootInterface = interfaceIdentityFromLink(rootLink)
|
||||
if (rootInterface) {
|
||||
frames.push({
|
||||
name: '__root_interface__',
|
||||
kind: 'interface',
|
||||
parent: null,
|
||||
child: rootLink,
|
||||
interfaceName: canonicalInterfaceLinkName(rootLink),
|
||||
interfaceType: rootInterface.key,
|
||||
isRoot: true,
|
||||
synthetic: true,
|
||||
xyz: [0, 0, 0],
|
||||
rpy: [0, 0, 0],
|
||||
originExplicit: false,
|
||||
limits: {},
|
||||
})
|
||||
}
|
||||
return { robotName: document.documentElement.getAttribute('name') || '', rootLink, frames }
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { validPhone } from './identity'
|
||||
import { validEmail } from './identity'
|
||||
|
||||
export const userRoles = { admin: '管理员', viewer: '普通用户' } as const
|
||||
export const userStatuses = { enabled: '启用', disabled: '停用' } as const
|
||||
@@ -7,19 +7,19 @@ export type UserStatus = keyof typeof userStatuses
|
||||
export interface ManagedUser {
|
||||
id: string
|
||||
name: string
|
||||
phone: string
|
||||
email: string
|
||||
role: UserRole
|
||||
status: UserStatus
|
||||
createdAt: string
|
||||
updatedAt: string
|
||||
}
|
||||
export type UserInput = Pick<ManagedUser, 'name' | 'phone' | 'role' | 'status'>
|
||||
export type UserInput = Pick<ManagedUser, 'name' | 'email' | 'role' | 'status'>
|
||||
export function validateUser(input: UserInput): UserInput {
|
||||
const name = input.name.trim(),
|
||||
phone = input.phone.trim()
|
||||
email = input.email.trim().toLowerCase()
|
||||
if (!name || name.length > 64) throw new Error('姓名须为 1–64 个字符。')
|
||||
if (!validPhone(phone)) throw new Error('请输入正确的 11 位手机号。')
|
||||
if (!email || !validEmail(email)) throw new Error('请输入有效的邮箱地址(最多 254 个字符)。')
|
||||
if (!Object.hasOwn(userRoles, input.role)) throw new Error('请选择有效的用户角色。')
|
||||
if (!Object.hasOwn(userStatuses, input.status)) throw new Error('请选择有效的账号状态。')
|
||||
return { name, phone, role: input.role, status: input.status }
|
||||
return { name, email, role: input.role, status: input.status }
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { requestId } from '@/domain/format'
|
||||
import { apiUrl } from '../../../shared/api-origin.ts'
|
||||
import { objectStorageUrl, resourceDownloadUrl } from '../../../shared/object-storage.ts'
|
||||
import { clearAuthSession, readAuthSession } from '@/application/auth'
|
||||
|
||||
export const API_ROOT = '/admin-api'
|
||||
export interface Page<T> {
|
||||
@@ -37,6 +38,7 @@ export function queryString(
|
||||
}
|
||||
async function failure(response: Response): Promise<never> {
|
||||
const body = await response.json().catch(() => ({}))
|
||||
invalidateSession(response.status, body.code)
|
||||
throw new ApiError(
|
||||
body.message || `请求失败,HTTP ${response.status}`,
|
||||
response.status,
|
||||
@@ -44,11 +46,22 @@ async function failure(response: Response): Promise<never> {
|
||||
body.requestId || response.headers.get('X-Request-Id') || undefined,
|
||||
)
|
||||
}
|
||||
function invalidateSession(status: number, code?: string) {
|
||||
if (
|
||||
status === 401 ||
|
||||
code === 'UNAUTHORIZED' ||
|
||||
code === 'ADMIN_ACCESS_DENIED' ||
|
||||
code === 'ACCOUNT_DISABLED'
|
||||
)
|
||||
clearAuthSession()
|
||||
}
|
||||
export async function api<T>(
|
||||
path: string,
|
||||
options: { method?: string; body?: unknown; signal?: AbortSignal; timeout?: number } = {},
|
||||
): Promise<T> {
|
||||
const headers = new Headers({ 'X-Request-Id': requestId() })
|
||||
const session = readAuthSession()
|
||||
if (session) headers.set('Authorization', `${session.tokenType} ${session.token}`)
|
||||
let body: string | undefined
|
||||
if (options.body !== undefined) {
|
||||
headers.set('Content-Type', 'application/json')
|
||||
@@ -60,7 +73,7 @@ export async function api<T>(
|
||||
])
|
||||
const response = await fetch(proxyUrl(path), {
|
||||
method: options.method ?? 'GET',
|
||||
credentials: 'include',
|
||||
credentials: 'omit',
|
||||
body,
|
||||
headers,
|
||||
signal,
|
||||
@@ -69,6 +82,7 @@ export async function api<T>(
|
||||
const envelope = await response.json().catch(() => {
|
||||
throw new ApiError('服务端返回了无法识别的响应', response.status, 'INVALID_RESPONSE')
|
||||
})
|
||||
if (envelope.code !== 'OK') invalidateSession(response.status, envelope.code)
|
||||
if (envelope.code !== 'OK')
|
||||
throw new ApiError(
|
||||
envelope.message || '操作失败',
|
||||
@@ -83,8 +97,16 @@ export function validateUploadSize(file: File): void {
|
||||
if (file.size > MAX_UPLOAD_BYTES) throw new Error(`文件“${file.name}”超过单文件 100 MiB 上限`)
|
||||
}
|
||||
export async function downloadFile(url: string, path: string, signal?: AbortSignal): Promise<File> {
|
||||
const response = await fetch(resourceDownloadUrl(url), {
|
||||
const source = new URL(url, window.location.origin)
|
||||
const privateAdminResource =
|
||||
source.pathname === API_ROOT || source.pathname.startsWith(`${API_ROOT}/`)
|
||||
const session = privateAdminResource ? readAuthSession() : null
|
||||
const headers = session
|
||||
? new Headers({ Authorization: `${session.tokenType} ${session.token}` })
|
||||
: undefined
|
||||
const response = await fetch(privateAdminResource ? proxyUrl(url) : resourceDownloadUrl(url), {
|
||||
credentials: 'omit',
|
||||
headers,
|
||||
signal: AbortSignal.any([AbortSignal.timeout(150000), ...(signal ? [signal] : [])]),
|
||||
})
|
||||
if (!response.ok) return failure(response)
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
import * as THREE from 'three'
|
||||
|
||||
export interface InterfacePoint {
|
||||
name: string
|
||||
object: THREE.Object3D
|
||||
}
|
||||
|
||||
/** Build a scene-overlay marker for an interface Link's world coordinate frame. */
|
||||
export function createInterfaceDirectionMarker(
|
||||
model: THREE.Object3D,
|
||||
point: THREE.Object3D,
|
||||
sizeScale = 1,
|
||||
options: { showYAxis?: boolean } = {},
|
||||
): THREE.Group | null {
|
||||
let owner: THREE.Object3D | null = point
|
||||
while (owner && owner !== model) owner = owner.parent
|
||||
if (!owner) return null
|
||||
|
||||
model.updateWorldMatrix(true, true)
|
||||
point.updateWorldMatrix(true, false)
|
||||
const bounds = new THREE.Box3().setFromObject(model)
|
||||
const modelSize = bounds.isEmpty() ? 0.1 : bounds.getSize(new THREE.Vector3()).length()
|
||||
const scale = THREE.MathUtils.clamp(modelSize * 0.15, 0.012, 0.12) * sizeScale
|
||||
const group = new THREE.Group()
|
||||
group.name = `interface-direction/${point.name}`
|
||||
point.getWorldPosition(group.position)
|
||||
point.getWorldQuaternion(group.quaternion)
|
||||
|
||||
const addAxis = (
|
||||
direction: THREE.Vector3,
|
||||
color: number,
|
||||
length: number,
|
||||
headLength: number,
|
||||
headWidth: number,
|
||||
name: string,
|
||||
) => {
|
||||
const arrow = new THREE.ArrowHelper(
|
||||
direction,
|
||||
new THREE.Vector3(),
|
||||
length,
|
||||
color,
|
||||
headLength,
|
||||
headWidth,
|
||||
)
|
||||
arrow.name = name
|
||||
for (const object of [arrow.line, arrow.cone]) {
|
||||
const material = object.material
|
||||
for (const item of Array.isArray(material) ? material : [material]) {
|
||||
item.depthTest = false
|
||||
item.depthWrite = false
|
||||
}
|
||||
}
|
||||
arrow.renderOrder = 1001
|
||||
arrow.line.renderOrder = 1001
|
||||
arrow.cone.renderOrder = 1001
|
||||
group.add(arrow)
|
||||
}
|
||||
|
||||
const mainLength = scale
|
||||
const sideLength = scale * 0.58
|
||||
addAxis(
|
||||
new THREE.Vector3(0, 0, 1),
|
||||
0x42a5ff,
|
||||
mainLength,
|
||||
scale * 0.25,
|
||||
scale * 0.13,
|
||||
'+Z 拼装方向',
|
||||
)
|
||||
addAxis(
|
||||
new THREE.Vector3(1, 0, 0),
|
||||
0xff5b57,
|
||||
sideLength,
|
||||
scale * 0.18,
|
||||
scale * 0.095,
|
||||
'+X 朝向参考',
|
||||
)
|
||||
if (options.showYAxis) {
|
||||
addAxis(
|
||||
new THREE.Vector3(0, 1, 0),
|
||||
0x59d98e,
|
||||
sideLength,
|
||||
scale * 0.18,
|
||||
scale * 0.095,
|
||||
'+Y 朝向参考',
|
||||
)
|
||||
}
|
||||
|
||||
const origin = new THREE.Mesh(
|
||||
new THREE.SphereGeometry(scale * 0.085, 12, 8),
|
||||
new THREE.MeshBasicMaterial({
|
||||
color: 0xffffff,
|
||||
depthTest: false,
|
||||
depthWrite: false,
|
||||
toneMapped: false,
|
||||
}),
|
||||
)
|
||||
origin.name = 'interface-origin'
|
||||
origin.renderOrder = 1002
|
||||
group.add(origin)
|
||||
return group
|
||||
}
|
||||
|
||||
/** Release geometry and materials owned by a direction marker. */
|
||||
export function disposeInterfaceDirectionMarker(root: THREE.Object3D): void {
|
||||
const geometries = new Set<THREE.BufferGeometry>()
|
||||
const materials = new Set<THREE.Material>()
|
||||
root.traverse((object) => {
|
||||
const drawable = object as THREE.Mesh | THREE.Line
|
||||
if (drawable.geometry) geometries.add(drawable.geometry)
|
||||
const material = drawable.material
|
||||
if (material)
|
||||
for (const item of Array.isArray(material) ? material : [material]) materials.add(item)
|
||||
})
|
||||
geometries.forEach((geometry) => geometry.dispose())
|
||||
materials.forEach((material) => material.dispose())
|
||||
root.clear()
|
||||
}
|
||||
@@ -13,6 +13,7 @@ export interface LoadedUrdf {
|
||||
root: URDFRobot
|
||||
links: Array<{ name: string; visuals: number }>
|
||||
joints: Array<{ name: string; type: string; parent: string; child: string }>
|
||||
warnings: string[]
|
||||
dispose: () => void
|
||||
}
|
||||
export function disposeObject(root: THREE.Object3D): void {
|
||||
@@ -59,6 +60,7 @@ export async function loadUrdfFiles(files: File[]): Promise<LoadedUrdf> {
|
||||
}
|
||||
const manager = new THREE.LoadingManager(),
|
||||
loader = new URDFLoader(manager)
|
||||
const warnings: string[] = []
|
||||
manager.setURLModifier(resourceUrl)
|
||||
const jobs: Promise<void>[] = []
|
||||
let textureFailure = ''
|
||||
@@ -127,8 +129,11 @@ export async function loadUrdfFiles(files: File[]): Promise<LoadedUrdf> {
|
||||
material.dispose()
|
||||
}
|
||||
} catch (error) {
|
||||
done(new THREE.Group(), error instanceof Error ? error : new Error('模型解析失败'))
|
||||
throw error
|
||||
const reason = error instanceof Error ? error.message : '模型解析失败'
|
||||
// A broken mesh must not prevent the rest of the URDF, or the original
|
||||
// files, from being used. URDFLoader will simply omit this visual.
|
||||
warnings.push(`${path.split('/').at(-1) || path}:${reason}`)
|
||||
done(new THREE.Group(), new Error(reason))
|
||||
} finally {
|
||||
manager.itemEnd(path)
|
||||
}
|
||||
@@ -164,6 +169,7 @@ export async function loadUrdfFiles(files: File[]): Promise<LoadedUrdf> {
|
||||
parent: node.querySelector('parent')!.getAttribute('link')!,
|
||||
child: node.querySelector('child')!.getAttribute('link')!,
|
||||
})),
|
||||
warnings,
|
||||
dispose: () => {
|
||||
disposeObject(ownedRoot)
|
||||
ownedRoot.clear()
|
||||
|
||||
+28
-5
@@ -1,6 +1,7 @@
|
||||
import React from 'react'
|
||||
import ReactDOM from 'react-dom/client'
|
||||
import { RouterProvider } from 'react-router-dom'
|
||||
import { ConfigProvider, theme } from 'antd'
|
||||
import { router } from './app/router'
|
||||
import { Notifications } from './app/Notifications'
|
||||
import './styles/app.css'
|
||||
@@ -8,10 +9,32 @@ import { AuthProvider } from './app/AuthProvider'
|
||||
|
||||
ReactDOM.createRoot(document.getElementById('root')!).render(
|
||||
<React.StrictMode>
|
||||
<AuthProvider>
|
||||
<Notifications>
|
||||
<RouterProvider router={router} />
|
||||
</Notifications>
|
||||
</AuthProvider>
|
||||
<ConfigProvider
|
||||
theme={{
|
||||
algorithm: theme.darkAlgorithm,
|
||||
token: {
|
||||
colorPrimary: '#4da3ff',
|
||||
colorSuccess: '#38c172',
|
||||
colorError: '#ff7272',
|
||||
colorWarning: '#f0a43b',
|
||||
colorBgBase: '#050505',
|
||||
colorBgContainer: '#101010',
|
||||
colorBgElevated: '#1b1b1b',
|
||||
colorBorder: '#2a2a2a',
|
||||
colorText: '#f2f2f2',
|
||||
colorTextSecondary: '#bdbdbd',
|
||||
borderRadius: 6,
|
||||
controlHeight: 36,
|
||||
fontFamily:
|
||||
"Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', sans-serif",
|
||||
},
|
||||
}}
|
||||
>
|
||||
<AuthProvider>
|
||||
<Notifications>
|
||||
<RouterProvider router={router} />
|
||||
</Notifications>
|
||||
</AuthProvider>
|
||||
</ConfigProvider>
|
||||
</React.StrictMode>,
|
||||
)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { ArrowLeft, ArrowRight, RefreshCw, ScrollText } from 'lucide-react'
|
||||
import { Input, Pagination, Select, Table, Tag, Tooltip, type TableColumnsType } from 'antd'
|
||||
import { RefreshCw, ScrollText } from 'lucide-react'
|
||||
import { activityGateway, logActions, type OperationLog } from '@/application/activity-gateway'
|
||||
import { errorMessage } from '@/domain/format'
|
||||
import { Button, Field, Loading, Modal, Notice, PageHeading } from '@/components/ui'
|
||||
@@ -102,7 +103,73 @@ export function ActivityPage() {
|
||||
setDetailBusy(false)
|
||||
}
|
||||
}
|
||||
const pages = Math.max(1, Math.ceil(total / 15))
|
||||
const columns: TableColumnsType<OperationLog> = [
|
||||
{
|
||||
title: '操作时间',
|
||||
dataIndex: 'operatedAt',
|
||||
key: 'operatedAt',
|
||||
width: 165,
|
||||
render: (value: string) => <span className="activity-time">{formatTime(value)}</span>,
|
||||
},
|
||||
{
|
||||
title: '操作人',
|
||||
key: 'operator',
|
||||
width: 126,
|
||||
render: (_, entry) => (
|
||||
<span>
|
||||
{entry.operatorName}
|
||||
<small> #{entry.operatorId}</small>
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '所属模块',
|
||||
dataIndex: 'module',
|
||||
key: 'module',
|
||||
width: 100,
|
||||
render: (value: string) => (value === 'COMPONENT' ? '组件库' : value),
|
||||
},
|
||||
{
|
||||
title: '操作类型',
|
||||
dataIndex: 'action',
|
||||
key: 'action',
|
||||
width: 125,
|
||||
render: (value: string) => logActions[value as keyof typeof logActions] ?? value,
|
||||
},
|
||||
{
|
||||
title: '目标',
|
||||
key: 'target',
|
||||
width: 270,
|
||||
render: (_, entry) => (
|
||||
<span className="activity-detail" title={entry.targetId}>
|
||||
{entry.targetName || entry.targetCode || entry.targetId || '—'}
|
||||
{entry.targetCode && <small>{entry.targetCode}</small>}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '结果',
|
||||
dataIndex: 'success',
|
||||
key: 'success',
|
||||
width: 82,
|
||||
render: (value: boolean) => (
|
||||
<Tag color={value ? 'success' : 'error'}>{value ? '成功' : '失败'}</Tag>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
key: 'actions',
|
||||
width: 90,
|
||||
align: 'right',
|
||||
render: (_, entry) => (
|
||||
<Tooltip title="查看操作详情">
|
||||
<Button disabled={detailBusy} onClick={() => void openDetail(entry.id)}>
|
||||
详情
|
||||
</Button>
|
||||
</Tooltip>
|
||||
),
|
||||
},
|
||||
]
|
||||
return (
|
||||
<>
|
||||
<PageHeading title="操作日志" description="查询后端返回的操作记录。">
|
||||
@@ -114,7 +181,7 @@ export function ActivityPage() {
|
||||
<section className="library-panel activity-panel">
|
||||
<div className="library-toolbar activity-toolbar log-filters">
|
||||
<Field label="所属模块">
|
||||
<input
|
||||
<Input
|
||||
aria-label="筛选操作模块"
|
||||
value={module}
|
||||
placeholder="全部模块"
|
||||
@@ -122,7 +189,7 @@ export function ActivityPage() {
|
||||
/>
|
||||
</Field>
|
||||
<Field label="操作类型">
|
||||
<input
|
||||
<Input
|
||||
aria-label="筛选操作类型"
|
||||
value={action}
|
||||
placeholder="全部操作"
|
||||
@@ -130,46 +197,47 @@ export function ActivityPage() {
|
||||
/>
|
||||
</Field>
|
||||
<Field label="目标名称或编码">
|
||||
<input
|
||||
<Input
|
||||
value={keyword}
|
||||
placeholder="关键词"
|
||||
onChange={(event) => setKeyword(event.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="目标类型">
|
||||
<input
|
||||
<Input
|
||||
value={targetType}
|
||||
placeholder="例如 COMPONENT"
|
||||
onChange={(event) => setTargetType(event.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="目标 ID">
|
||||
<input
|
||||
<Input
|
||||
value={targetId}
|
||||
placeholder="精确匹配"
|
||||
onChange={(event) => setTargetId(event.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="目标编码">
|
||||
<input
|
||||
<Input
|
||||
value={targetCode}
|
||||
placeholder="精确匹配"
|
||||
onChange={(event) => setTargetCode(event.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="操作结果">
|
||||
<select
|
||||
<Select
|
||||
aria-label="筛选操作结果"
|
||||
value={success}
|
||||
onChange={(event) => setSuccess(event.target.value)}
|
||||
>
|
||||
<option value="">全部结果</option>
|
||||
<option value="true">成功</option>
|
||||
<option value="false">失败</option>
|
||||
</select>
|
||||
options={[
|
||||
{ value: '', label: '全部结果' },
|
||||
{ value: 'true', label: '成功' },
|
||||
{ value: 'false', label: '失败' },
|
||||
]}
|
||||
onChange={setSuccess}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="操作人 ID">
|
||||
<input
|
||||
<Input
|
||||
type="number"
|
||||
min="0"
|
||||
step="1"
|
||||
@@ -179,14 +247,14 @@ export function ActivityPage() {
|
||||
/>
|
||||
</Field>
|
||||
<Field label="开始时间">
|
||||
<input
|
||||
<Input
|
||||
type="datetime-local"
|
||||
value={from}
|
||||
onChange={(event) => setFrom(event.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="结束时间">
|
||||
<input
|
||||
<Input
|
||||
type="datetime-local"
|
||||
value={to}
|
||||
onChange={(event) => setTo(event.target.value)}
|
||||
@@ -209,72 +277,25 @@ export function ActivityPage() {
|
||||
<p>当前查询条件下,后端没有返回操作记录。</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="table-scroll">
|
||||
<table className="resource-table activity-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>操作时间</th>
|
||||
<th>操作人</th>
|
||||
<th>所属模块</th>
|
||||
<th>操作类型</th>
|
||||
<th>目标</th>
|
||||
<th>结果</th>
|
||||
<th>操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{entries.map((entry) => (
|
||||
<tr key={entry.id}>
|
||||
<td className="activity-time">{formatTime(entry.operatedAt)}</td>
|
||||
<td>
|
||||
{entry.operatorName}
|
||||
<small> #{entry.operatorId}</small>
|
||||
</td>
|
||||
<td>{entry.module === 'COMPONENT' ? '组件库' : entry.module}</td>
|
||||
<td>{logActions[entry.action as keyof typeof logActions] ?? entry.action}</td>
|
||||
<td className="activity-detail" title={entry.targetId}>
|
||||
{entry.targetName || entry.targetCode || entry.targetId || '—'}
|
||||
{entry.targetCode && <small>{entry.targetCode}</small>}
|
||||
</td>
|
||||
<td>
|
||||
<span
|
||||
className={`user-status user-status-${entry.success ? 'enabled' : 'disabled'}`}
|
||||
>
|
||||
{entry.success ? '成功' : '失败'}
|
||||
</span>
|
||||
</td>
|
||||
<td>
|
||||
<Button disabled={detailBusy} onClick={() => void openDetail(entry.id)}>
|
||||
详情
|
||||
</Button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<Table
|
||||
className="activity-table"
|
||||
columns={columns}
|
||||
dataSource={entries}
|
||||
pagination={false}
|
||||
rowKey="id"
|
||||
scroll={{ x: 960 }}
|
||||
/>
|
||||
)}
|
||||
<div className="table-footer">
|
||||
<span>共 {total} 条记录</span>
|
||||
<div className="pagination">
|
||||
<button
|
||||
aria-label="上一页"
|
||||
disabled={page === 1 || loading}
|
||||
onClick={() => setPage(page - 1)}
|
||||
>
|
||||
<ArrowLeft size={15} />
|
||||
</button>
|
||||
<span>
|
||||
{page} <small>/ {pages}</small>
|
||||
</span>
|
||||
<button
|
||||
aria-label="下一页"
|
||||
disabled={page >= pages || loading}
|
||||
onClick={() => setPage(page + 1)}
|
||||
>
|
||||
<ArrowRight size={15} />
|
||||
</button>
|
||||
</div>
|
||||
<div className="table-footer ant-pagination-footer">
|
||||
<Pagination
|
||||
current={page}
|
||||
disabled={loading}
|
||||
pageSize={15}
|
||||
showSizeChanger={false}
|
||||
showTotal={(value) => `共 ${value} 条记录`}
|
||||
total={total}
|
||||
onChange={setPage}
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
{detail && (
|
||||
|
||||
@@ -1,19 +1,16 @@
|
||||
import { useDeferredValue, useEffect, useState } from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import { Link, useNavigate, useSearchParams } from 'react-router-dom'
|
||||
import {
|
||||
Box,
|
||||
FileBox,
|
||||
FolderOpen,
|
||||
Search,
|
||||
Upload,
|
||||
LayoutGrid,
|
||||
List,
|
||||
Pencil,
|
||||
Trash2,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
RefreshCw,
|
||||
} from 'lucide-react'
|
||||
Input,
|
||||
Pagination,
|
||||
Select,
|
||||
Space,
|
||||
Switch,
|
||||
Table,
|
||||
Tooltip,
|
||||
type TableColumnsType,
|
||||
} from 'antd'
|
||||
import { Box, FileBox, FolderOpen, Search, Upload, Pencil, Trash2, RefreshCw } from 'lucide-react'
|
||||
import { componentGateway } from '@/application/component-gateway'
|
||||
import type { ComponentSummary } from '@/domain/component-catalog'
|
||||
import { PART_CATEGORY_OPTIONS } from '@/domain/part-naming'
|
||||
@@ -23,18 +20,59 @@ import { Button, EmptyState, Modal, PageHeading, Loading, Notice } from '@/compo
|
||||
|
||||
export function ComponentCatalogPage() {
|
||||
const notify = useNotify()
|
||||
const navigate = useNavigate()
|
||||
const [searchParams, setSearchParams] = useSearchParams()
|
||||
const [records, setRecords] = useState<ComponentSummary[]>([]),
|
||||
[total, setTotal] = useState(0)
|
||||
const [loading, setLoading] = useState(true),
|
||||
[error, setError] = useState(''),
|
||||
[revision, setRevision] = useState(0)
|
||||
const [query, setQuery] = useState(''),
|
||||
search = useDeferredValue(query)
|
||||
const [category, setCategory] = useState('')
|
||||
const [view, setView] = useState('list'),
|
||||
[page, setPage] = useState(1)
|
||||
const query = searchParams.get('keyword') || ''
|
||||
const search = useDeferredValue(query)
|
||||
const category = searchParams.get('category') || ''
|
||||
const parsedPage = Number.parseInt(searchParams.get('page') || '1', 10)
|
||||
const page = Number.isFinite(parsedPage) && parsedPage > 0 ? parsedPage : 1
|
||||
const [deleting, setDeleting] = useState<number | null>(null),
|
||||
[busy, setBusy] = useState(false)
|
||||
[busy, setBusy] = useState(false),
|
||||
[statusPendingIds, setStatusPendingIds] = useState<Set<number>>(() => new Set())
|
||||
function updateListParams(changes: { keyword?: string; category?: string; page?: number }) {
|
||||
setSearchParams(
|
||||
(current) => {
|
||||
const next = new URLSearchParams(current)
|
||||
if ('keyword' in changes) {
|
||||
if (changes.keyword) next.set('keyword', changes.keyword)
|
||||
else next.delete('keyword')
|
||||
}
|
||||
if ('category' in changes) {
|
||||
if (changes.category) next.set('category', changes.category)
|
||||
else next.delete('category')
|
||||
}
|
||||
if ('page' in changes) {
|
||||
if (changes.page && changes.page > 1) next.set('page', String(changes.page))
|
||||
else next.delete('page')
|
||||
}
|
||||
next.delete('view')
|
||||
return next
|
||||
},
|
||||
{ replace: true },
|
||||
)
|
||||
}
|
||||
useEffect(() => {
|
||||
if (!searchParams.has('view')) return
|
||||
setSearchParams(
|
||||
(current) => {
|
||||
const next = new URLSearchParams(current)
|
||||
next.delete('view')
|
||||
return next
|
||||
},
|
||||
{ replace: true },
|
||||
)
|
||||
}, [searchParams, setSearchParams])
|
||||
const editorSearch = searchParams.toString()
|
||||
const editorLocation = (path: string) => ({
|
||||
pathname: path,
|
||||
search: editorSearch ? `?${editorSearch}` : '',
|
||||
})
|
||||
useEffect(() => {
|
||||
const controller = new AbortController()
|
||||
const timer = setTimeout(async () => {
|
||||
@@ -49,7 +87,7 @@ export function ComponentCatalogPage() {
|
||||
setRecords(result.items)
|
||||
setTotal(result.total)
|
||||
if (page > Math.max(1, Math.ceil(result.total / 10)))
|
||||
setPage(Math.max(1, Math.ceil(result.total / 10)))
|
||||
updateListParams({ page: Math.max(1, Math.ceil(result.total / 10)) })
|
||||
} catch (value) {
|
||||
if (!controller.signal.aborted) setError(errorMessage(value))
|
||||
} finally {
|
||||
@@ -61,9 +99,7 @@ export function ComponentCatalogPage() {
|
||||
controller.abort()
|
||||
}
|
||||
}, [page, search, category, revision])
|
||||
const pages = Math.max(1, Math.ceil(total / 10)),
|
||||
current = page,
|
||||
visible = records
|
||||
const visible = records
|
||||
async function confirmDelete() {
|
||||
if (!deleting) return
|
||||
setBusy(true)
|
||||
@@ -78,6 +114,134 @@ export function ComponentCatalogPage() {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
async function toggleStatus(item: ComponentSummary) {
|
||||
if (statusPendingIds.has(item.id)) return
|
||||
const status = item.status === 'ENABLED' ? 'DISABLED' : 'ENABLED'
|
||||
setStatusPendingIds((ids) => new Set(ids).add(item.id))
|
||||
try {
|
||||
await componentGateway.setStatus(item.id, status)
|
||||
setRecords((items) =>
|
||||
items.map((record) => (record.id === item.id ? { ...record, status } : record)),
|
||||
)
|
||||
notify(
|
||||
`组件「${item.componentName || item.componentCode}」已${status === 'ENABLED' ? '启用' : '禁用'}`,
|
||||
)
|
||||
} catch (error) {
|
||||
notify(errorMessage(error), 'error')
|
||||
} finally {
|
||||
setStatusPendingIds((ids) => {
|
||||
const next = new Set(ids)
|
||||
next.delete(item.id)
|
||||
return next
|
||||
})
|
||||
}
|
||||
}
|
||||
const columns: TableColumnsType<ComponentSummary> = [
|
||||
{
|
||||
title: '组件名称',
|
||||
key: 'name',
|
||||
width: 285,
|
||||
render: (_, item) => (
|
||||
<Link className="resource-name" to={editorLocation(`/components/${item.id}`)}>
|
||||
<span className="resource-thumb">
|
||||
<Box size={21} />
|
||||
</span>
|
||||
<span>
|
||||
<strong>{item.componentName || item.componentCode}</strong>
|
||||
<small>{item.description || '—'}</small>
|
||||
</span>
|
||||
</Link>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '组件编码',
|
||||
dataIndex: 'componentCode',
|
||||
key: 'componentCode',
|
||||
width: 190,
|
||||
render: (value: string) => <span className="catalog-part-number">{value}</span>,
|
||||
},
|
||||
{
|
||||
title: '零件分类',
|
||||
dataIndex: 'category',
|
||||
key: 'category',
|
||||
width: 130,
|
||||
render: (value: string) => <strong className="cell-label">{value || '—'}</strong>,
|
||||
},
|
||||
{
|
||||
title: '模型资源',
|
||||
key: 'resources',
|
||||
width: 150,
|
||||
render: (_, item) => (
|
||||
<div className="catalog-resource-tags">
|
||||
<span>
|
||||
<FileBox size={13} />
|
||||
STEP
|
||||
</span>
|
||||
{item.urdfUrl && (
|
||||
<span>
|
||||
<FolderOpen size={13} />
|
||||
URDF
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '状态',
|
||||
key: 'status',
|
||||
width: 135,
|
||||
render: (_, item) => {
|
||||
const pending = statusPendingIds.has(item.id)
|
||||
const enabled = item.status === 'ENABLED'
|
||||
return (
|
||||
<div className="component-status-control">
|
||||
<Switch
|
||||
aria-label={`${enabled ? '禁用' : '启用'}组件 ${item.componentName || item.componentCode}`}
|
||||
checked={enabled}
|
||||
loading={pending}
|
||||
onChange={() => void toggleStatus(item)}
|
||||
/>
|
||||
<span className={enabled ? 'is-enabled' : ''}>
|
||||
{pending ? '更新中…' : enabled ? '启用' : '禁用'}
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
title: '更新时间',
|
||||
dataIndex: 'updatedAt',
|
||||
key: 'updatedAt',
|
||||
width: 160,
|
||||
render: (value: string) => <span className="date-cell">{formatDate(value)}</span>,
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
key: 'actions',
|
||||
width: 108,
|
||||
align: 'right',
|
||||
render: (_, item) => (
|
||||
<Space size={2}>
|
||||
<Tooltip title="编辑组件">
|
||||
<Button
|
||||
aria-label={`编辑 ${item.componentName || item.componentCode}`}
|
||||
icon={<Pencil size={16} />}
|
||||
variant="ghost"
|
||||
onClick={() => navigate(editorLocation(`/components/${item.id}`))}
|
||||
/>
|
||||
</Tooltip>
|
||||
<Tooltip title="删除组件">
|
||||
<Button
|
||||
aria-label={`删除 ${item.componentName || item.componentCode}`}
|
||||
icon={<Trash2 size={16} />}
|
||||
variant="ghost"
|
||||
onClick={() => setDeleting(item.id)}
|
||||
/>
|
||||
</Tooltip>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
]
|
||||
return (
|
||||
<>
|
||||
<PageHeading title="组件库" description="统一管理零件信息、STEP 模型与 URDF 资源。">
|
||||
@@ -85,63 +249,41 @@ export function ComponentCatalogPage() {
|
||||
<RefreshCw size={15} className={loading ? 'spin' : ''} />
|
||||
刷新
|
||||
</Button>
|
||||
<Link to="/components/new" className="button button-primary">
|
||||
<Button variant="primary" onClick={() => navigate(editorLocation('/components/new'))}>
|
||||
<Upload size={16} />
|
||||
上传组件
|
||||
</Link>
|
||||
</Button>
|
||||
</PageHeading>
|
||||
<section className="library-panel component-catalog-panel">
|
||||
<div className="library-toolbar">
|
||||
<div className="search-field">
|
||||
<Search size={17} />
|
||||
<input
|
||||
data-search
|
||||
aria-label="搜索组件"
|
||||
placeholder="搜索组件名称或编码…"
|
||||
value={query}
|
||||
onChange={(event) => {
|
||||
setQuery(event.target.value)
|
||||
setPage(1)
|
||||
}}
|
||||
/>
|
||||
<kbd>⌘ K</kbd>
|
||||
</div>
|
||||
<Input
|
||||
allowClear
|
||||
className="catalog-search"
|
||||
data-search
|
||||
aria-label="搜索组件"
|
||||
prefix={<Search size={17} />}
|
||||
placeholder="搜索组件名称或编码…"
|
||||
suffix={<kbd>⌘ K</kbd>}
|
||||
value={query}
|
||||
onChange={(event) => {
|
||||
updateListParams({ keyword: event.target.value, page: 1 })
|
||||
}}
|
||||
/>
|
||||
<div className="filter-tools">
|
||||
<div className="catalog-category-filter">
|
||||
<input
|
||||
aria-label="零件分类筛选"
|
||||
list="catalog-part-categories"
|
||||
placeholder="输入分类名称(精确匹配)"
|
||||
value={category}
|
||||
onChange={(event) => {
|
||||
setCategory(event.target.value)
|
||||
setPage(1)
|
||||
}}
|
||||
/>
|
||||
<datalist id="catalog-part-categories">
|
||||
{PART_CATEGORY_OPTIONS.map((option) => (
|
||||
<option key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</option>
|
||||
))}
|
||||
</datalist>
|
||||
</div>
|
||||
<div className="view-switch" role="group" aria-label="视图切换">
|
||||
<button
|
||||
aria-label="列表视图"
|
||||
aria-pressed={view === 'list'}
|
||||
onClick={() => setView('list')}
|
||||
>
|
||||
<List size={17} />
|
||||
</button>
|
||||
<button
|
||||
aria-label="卡片视图"
|
||||
aria-pressed={view === 'grid'}
|
||||
onClick={() => setView('grid')}
|
||||
>
|
||||
<LayoutGrid size={17} />
|
||||
</button>
|
||||
</div>
|
||||
<Select
|
||||
allowClear
|
||||
aria-label="零件分类筛选"
|
||||
className="catalog-category-filter"
|
||||
optionFilterProp="label"
|
||||
options={PART_CATEGORY_OPTIONS.map((option) => ({
|
||||
value: option.value,
|
||||
label: option.label,
|
||||
}))}
|
||||
placeholder="筛选零件分类"
|
||||
showSearch
|
||||
value={category || undefined}
|
||||
onChange={(value) => updateListParams({ category: value || '', page: 1 })}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{loading ? (
|
||||
@@ -164,141 +306,42 @@ export function ComponentCatalogPage() {
|
||||
search || category ? (
|
||||
<Button
|
||||
onClick={() => {
|
||||
setQuery('')
|
||||
setCategory('')
|
||||
setPage(1)
|
||||
updateListParams({ keyword: '', category: '', page: 1 })
|
||||
}}
|
||||
>
|
||||
清除筛选
|
||||
</Button>
|
||||
) : (
|
||||
<Link className="button button-primary" to="/components/new">
|
||||
<Button
|
||||
variant="primary"
|
||||
onClick={() => navigate(editorLocation('/components/new'))}
|
||||
>
|
||||
<Upload size={16} />
|
||||
上传组件
|
||||
</Link>
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
/>
|
||||
) : view === 'list' ? (
|
||||
<div className="table-scroll">
|
||||
<table className="resource-table catalog-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>组件名称</th>
|
||||
<th>组件编码</th>
|
||||
<th>零件分类</th>
|
||||
<th>模型资源</th>
|
||||
<th>更新时间</th>
|
||||
<th className="action-cell">操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{visible.map((item) => (
|
||||
<tr key={item.id}>
|
||||
<td>
|
||||
<Link className="resource-name" to={`/components/${item.id}`}>
|
||||
<span className="resource-thumb">
|
||||
<Box size={21} />
|
||||
</span>
|
||||
<span>
|
||||
<strong>{item.componentName || item.componentCode}</strong>
|
||||
<small>{item.description || '—'}</small>
|
||||
</span>
|
||||
</Link>
|
||||
</td>
|
||||
<td>
|
||||
<span className="catalog-part-number">{item.componentCode}</span>
|
||||
</td>
|
||||
<td>
|
||||
<strong className="cell-label">{item.category || '—'}</strong>
|
||||
</td>
|
||||
<td>
|
||||
<div className="catalog-resource-tags">
|
||||
<span>
|
||||
<FileBox size={13} />
|
||||
STEP
|
||||
</span>
|
||||
{item.urdfUrl && (
|
||||
<span>
|
||||
<FolderOpen size={13} />
|
||||
URDF
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</td>
|
||||
<td className="date-cell">{formatDate(item.updatedAt)}</td>
|
||||
<td className="action-cell">
|
||||
<Link
|
||||
className="icon-button"
|
||||
aria-label={`编辑 ${item.componentName}`}
|
||||
to={`/components/${item.id}`}
|
||||
>
|
||||
<Pencil size={16} />
|
||||
</Link>
|
||||
<button
|
||||
className="icon-button danger-icon"
|
||||
aria-label={`删除 ${item.componentName}`}
|
||||
onClick={() => setDeleting(item.id)}
|
||||
>
|
||||
<Trash2 size={16} />
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
) : (
|
||||
<div className="resource-grid">
|
||||
{visible.map((item) => (
|
||||
<Link className="resource-card" key={item.id} to={`/components/${item.id}`}>
|
||||
<div className="resource-card-preview">
|
||||
<Box size={50} strokeWidth={1.1} />
|
||||
</div>
|
||||
<div className="resource-card-content">
|
||||
<h3>{item.componentName || item.componentCode}</h3>
|
||||
<p>
|
||||
{item.componentCode}
|
||||
{item.category ? ` · ${item.category}` : ''}
|
||||
</p>
|
||||
<div className="catalog-resource-tags">
|
||||
<span>
|
||||
<FileBox size={13} />
|
||||
STEP
|
||||
</span>
|
||||
{item.urdfUrl && (
|
||||
<span>
|
||||
<FolderOpen size={13} />
|
||||
URDF
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
<Table
|
||||
className="catalog-table"
|
||||
columns={columns}
|
||||
dataSource={visible}
|
||||
pagination={false}
|
||||
rowKey="id"
|
||||
scroll={{ x: 1150 }}
|
||||
/>
|
||||
)}
|
||||
<div className="table-footer">
|
||||
<span>共 {error || loading ? '—' : total} 个组件</span>
|
||||
<div className="pagination">
|
||||
<button
|
||||
aria-label="上一页"
|
||||
disabled={current === 1 || loading}
|
||||
onClick={() => setPage(current - 1)}
|
||||
>
|
||||
<ChevronLeft size={16} />
|
||||
</button>
|
||||
<span>
|
||||
{current} <small>/ {pages}</small>
|
||||
</span>
|
||||
<button
|
||||
aria-label="下一页"
|
||||
disabled={current >= pages || loading}
|
||||
onClick={() => setPage(current + 1)}
|
||||
>
|
||||
<ChevronRight size={16} />
|
||||
</button>
|
||||
</div>
|
||||
<div className="table-footer ant-pagination-footer">
|
||||
<Pagination
|
||||
current={page}
|
||||
disabled={loading}
|
||||
pageSize={10}
|
||||
showSizeChanger={false}
|
||||
showTotal={(value) => `共 ${value} 个组件`}
|
||||
total={total}
|
||||
onChange={(nextPage) => updateListParams({ page: nextPage })}
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
{deleting && (
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { ROTATION_AXES, parseRotationAxis } from '../../../shared/rotation-axis'
|
||||
import { useEffect, useRef, useState, type FormEvent } from 'react'
|
||||
import { Link, useNavigate, useParams } from 'react-router-dom'
|
||||
import { Input } from 'antd'
|
||||
import { Link, useLocation, useNavigate, useParams } from 'react-router-dom'
|
||||
import {
|
||||
ArrowLeft,
|
||||
Save,
|
||||
@@ -31,7 +32,12 @@ import { loadLocalStepModel, type LoadedStep } from '@/infrastructure/step-loade
|
||||
import { loadUrdfFiles, type LoadedUrdf } from '@/infrastructure/urdf-loader'
|
||||
import { ApiError } from '@/infrastructure/admin-api'
|
||||
import { ModelPreview } from '@/components/ModelPreview'
|
||||
import { readUrdfFrames, urdfInfoFromFrames, type UrdfFrames } from '@/domain/urdf-frames'
|
||||
import {
|
||||
isInterfaceFrame,
|
||||
readUrdfFrames,
|
||||
urdfInfoFromFrames,
|
||||
type UrdfFrames,
|
||||
} from '@/domain/urdf-frames'
|
||||
import { UrdfInstallationPoints } from '@/components/UrdfInstallationPoints'
|
||||
import { BomEditor } from '@/components/BomEditor'
|
||||
import { cloneJson, sameJson } from '@/domain/json'
|
||||
@@ -48,6 +54,7 @@ export function ComponentUploadPage() {
|
||||
function ComponentUploadForm() {
|
||||
const { id } = useParams(),
|
||||
navigate = useNavigate(),
|
||||
location = useLocation(),
|
||||
notify = useNotify()
|
||||
const [existing, setExisting] = useState<ComponentDetail>()
|
||||
const [info, setInfo] = useState<PartInformation>(emptyPartInformation)
|
||||
@@ -69,6 +76,7 @@ function ComponentUploadForm() {
|
||||
const [urdfFrames, setUrdfFrames] = useState<UrdfFrames | null>(null)
|
||||
const [framesError, setFramesError] = useState('')
|
||||
const [previewErrors, setPreviewErrors] = useState({ step: '', urdf: '' })
|
||||
const [previewWarnings, setPreviewWarnings] = useState({ step: '', urdf: '' })
|
||||
const [error, setError] = useState(''),
|
||||
[saving, setSaving] = useState(false),
|
||||
[restoring, setRestoring] = useState(Boolean(id))
|
||||
@@ -172,6 +180,7 @@ function ComponentUploadForm() {
|
||||
setHoveredPoint(null)
|
||||
setFramesError('')
|
||||
setPreviewErrors((value) => ({ ...value, urdf: '' }))
|
||||
setPreviewWarnings((value) => ({ ...value, urdf: '' }))
|
||||
urdfOwner.current?.dispose()
|
||||
urdfOwner.current = null
|
||||
setUrdfModel(null)
|
||||
@@ -200,7 +209,11 @@ function ComponentUploadForm() {
|
||||
try {
|
||||
const frames = readUrdfFrames(xml)
|
||||
setUrdfFrames(frames)
|
||||
if (changed) setInfo((current) => ({ ...current, urdfInfo: urdfInfoFromFrames(frames) }))
|
||||
if (changed)
|
||||
setInfo((current) => ({
|
||||
...current,
|
||||
urdfInfo: urdfInfoFromFrames(frames),
|
||||
}))
|
||||
} catch (value) {
|
||||
setFramesError(errorMessage(value))
|
||||
}
|
||||
@@ -211,6 +224,7 @@ function ComponentUploadForm() {
|
||||
}
|
||||
urdfOwner.current = model
|
||||
setUrdfModel(model)
|
||||
setPreviewWarnings((value) => ({ ...value, urdf: model.warnings.join(';') }))
|
||||
} catch (value) {
|
||||
if (token === urdfGeneration.current)
|
||||
setPreviewErrors((current) => ({ ...current, urdf: errorMessage(value) }))
|
||||
@@ -225,6 +239,7 @@ function ComponentUploadForm() {
|
||||
const busy = kind === 'step' ? setStepBusy : setUrdfBusy
|
||||
busy(true)
|
||||
setPreviewErrors((value) => ({ ...value, [kind]: '' }))
|
||||
setPreviewWarnings((value) => ({ ...value, [kind]: '' }))
|
||||
try {
|
||||
const files =
|
||||
kind === 'step'
|
||||
@@ -275,7 +290,7 @@ function ComponentUploadForm() {
|
||||
const resources = await uploadSession.current.upload(step, urdf, existing?.id, setProgress)
|
||||
const saved = await componentGateway.save(form, resources, existing)
|
||||
const mismatched = [
|
||||
...(form.rotationAxis !== parseRotationAxis(saved.rotationAxis)
|
||||
...(parseRotationAxis(form.rotationAxis) !== parseRotationAxis(saved.rotationAxis)
|
||||
? ['旋转轴(rotationAxis)']
|
||||
: []),
|
||||
...(!sameJson(form.bomList, saved.bomList ?? []) ? ['BOM 清单(bomList)'] : []),
|
||||
@@ -297,7 +312,7 @@ function ComponentUploadForm() {
|
||||
}
|
||||
guard.allowLeave()
|
||||
notify('组件已保存')
|
||||
navigate('/components')
|
||||
navigate(`/components${location.search}`)
|
||||
} catch (value) {
|
||||
setError(errorMessage(value))
|
||||
if (existing && value instanceof ApiError && value.code === 'COMPONENT_REVISION_CONFLICT') {
|
||||
@@ -317,13 +332,21 @@ function ComponentUploadForm() {
|
||||
<>
|
||||
<Notice variant="error">{error || '找不到这个组件。'}</Notice>
|
||||
<Button onClick={() => setLoadRevision((value) => value + 1)}>重新加载</Button>{' '}
|
||||
<Link to="/components">返回组件库</Link>
|
||||
<Link to={`/components${location.search}`}>返回组件库</Link>
|
||||
</>
|
||||
)
|
||||
const folder =
|
||||
urdf[0]?.webkitRelativePath.split('/')[0] ||
|
||||
(hasUrdfResources(existing) ? 'URDF 资源文件夹' : undefined)
|
||||
const model = preview === 'step' ? stepModel : urdfModel
|
||||
const interfaceFrames = urdfFrames?.frames.filter(isInterfaceFrame) ?? []
|
||||
const interfacePoints =
|
||||
preview === 'urdf' && urdfModel
|
||||
? interfaceFrames.flatMap((frame) => {
|
||||
const object = urdfModel.root.links[frame.child]
|
||||
return object ? [{ name: frame.name, object }] : []
|
||||
})
|
||||
: []
|
||||
const stepName = step?.name || existing?.stepObjectKey.split('/').at(-1)
|
||||
const urdfMainName =
|
||||
urdf.find((file) => /\.urdf$/i.test(file.name))?.name ||
|
||||
@@ -343,7 +366,11 @@ function ComponentUploadForm() {
|
||||
<Breadcrumb section="components" title={id ? '编辑组件' : '上传组件'} />
|
||||
<div className="editor-heading component-upload-heading">
|
||||
<div>
|
||||
<Link className="back-button" to="/components" aria-label="返回组件库">
|
||||
<Link
|
||||
className="back-button"
|
||||
to={`/components${location.search}`}
|
||||
aria-label="返回组件库"
|
||||
>
|
||||
<ArrowLeft size={19} />
|
||||
</Link>
|
||||
<div>
|
||||
@@ -485,9 +512,13 @@ function ComponentUploadForm() {
|
||||
model={model?.root}
|
||||
highlightPoint={
|
||||
preview === 'urdf' && informationTab === 'frames' && hoveredPoint
|
||||
? urdfModel?.root.joints[hoveredPoint]
|
||||
? urdfModel?.root.links[
|
||||
urdfFrames?.frames.find((frame) => frame.name === hoveredPoint)?.child || ''
|
||||
] || urdfModel?.root.joints[hoveredPoint]
|
||||
: null
|
||||
}
|
||||
interfacePoints={interfacePoints}
|
||||
highlightedInterfaceName={hoveredPoint}
|
||||
busy={preview === 'step' ? stepBusy : urdfBusy}
|
||||
fileName={
|
||||
preview === 'step'
|
||||
@@ -496,6 +527,7 @@ function ComponentUploadForm() {
|
||||
existing?.urdfMainObjectKey?.split('/').at(-1)
|
||||
}
|
||||
error={previewErrors[preview]}
|
||||
warning={previewWarnings[preview]}
|
||||
onImport={() =>
|
||||
sourceSection.current?.scrollIntoView({ behavior: 'smooth', block: 'center' })
|
||||
}
|
||||
@@ -604,7 +636,7 @@ function ComponentUploadForm() {
|
||||
>
|
||||
<div className="part-form-body">
|
||||
<Field label="名称" hint="选填;选择 URDF 后可按文件名自动填入,也可自行修改">
|
||||
<input
|
||||
<Input
|
||||
value={info.name}
|
||||
maxLength={128}
|
||||
placeholder="填写零件名称"
|
||||
@@ -612,7 +644,7 @@ function ComponentUploadForm() {
|
||||
/>
|
||||
</Field>
|
||||
<Field label="零件分类" hint={categoryHint}>
|
||||
<input
|
||||
<Input
|
||||
readOnly={Boolean(partIdentity)}
|
||||
maxLength={64}
|
||||
value={partIdentity?.key || info.category}
|
||||
@@ -639,7 +671,7 @@ function ComponentUploadForm() {
|
||||
</Field>
|
||||
<div className="part-form-row">
|
||||
<Field label="自由度">
|
||||
<input
|
||||
<Input
|
||||
type="number"
|
||||
min="0"
|
||||
max="2147483647"
|
||||
@@ -650,7 +682,7 @@ function ComponentUploadForm() {
|
||||
/>
|
||||
</Field>
|
||||
<Field label="材质">
|
||||
<input
|
||||
<Input
|
||||
value={info.material}
|
||||
maxLength={128}
|
||||
placeholder="例如:铝合金"
|
||||
@@ -660,7 +692,7 @@ function ComponentUploadForm() {
|
||||
</div>
|
||||
<div className="part-form-row">
|
||||
<Field label="功能">
|
||||
<input
|
||||
<Input
|
||||
value={info.function}
|
||||
maxLength={512}
|
||||
placeholder="填写零件功能"
|
||||
@@ -668,7 +700,7 @@ function ComponentUploadForm() {
|
||||
/>
|
||||
</Field>
|
||||
<Field label="形状">
|
||||
<input
|
||||
<Input
|
||||
value={info.shape}
|
||||
maxLength={128}
|
||||
placeholder="填写零件形状"
|
||||
@@ -678,7 +710,7 @@ function ComponentUploadForm() {
|
||||
</div>
|
||||
<div className="part-form-row">
|
||||
<Field label="大小">
|
||||
<input
|
||||
<Input
|
||||
value={info.size}
|
||||
maxLength={128}
|
||||
placeholder="填写尺寸及单位"
|
||||
@@ -686,7 +718,7 @@ function ComponentUploadForm() {
|
||||
/>
|
||||
</Field>
|
||||
<Field label="扭矩(N·m)">
|
||||
<input
|
||||
<Input
|
||||
type="number"
|
||||
min="0"
|
||||
step="0.01"
|
||||
@@ -697,7 +729,7 @@ function ComponentUploadForm() {
|
||||
</Field>
|
||||
</div>
|
||||
<Field label="质量(kg)">
|
||||
<input
|
||||
<Input
|
||||
type="number"
|
||||
min="0"
|
||||
step="0.01"
|
||||
@@ -707,7 +739,7 @@ function ComponentUploadForm() {
|
||||
/>
|
||||
</Field>
|
||||
<Field label="描述">
|
||||
<textarea
|
||||
<Input.TextArea
|
||||
value={info.description}
|
||||
maxLength={65535}
|
||||
rows={4}
|
||||
|
||||
@@ -1,61 +1,97 @@
|
||||
import { useEffect, useState, type FormEvent } from 'react'
|
||||
import { useLocation, useNavigate } from 'react-router-dom'
|
||||
import { ArrowRight, LoaderCircle, ShieldCheck } from 'lucide-react'
|
||||
import { ArrowRight, LoaderCircle, RefreshCw, ShieldCheck } from 'lucide-react'
|
||||
import { useAuth } from '@/app/auth-context'
|
||||
import { authGateway, safeReturnPath } from '@/application/auth'
|
||||
import { authGateway, safeReturnPath, type CaptchaChallenge } from '@/application/auth'
|
||||
import { errorMessage } from '@/domain/format'
|
||||
import { Button } from '@/components/ui'
|
||||
|
||||
function authErrorMessage(error: unknown): string {
|
||||
const code = error && typeof error === 'object' && 'code' in error ? error.code : ''
|
||||
switch (code) {
|
||||
case 'CAPTCHA_INVALID':
|
||||
return '验证码错误或已过期,请刷新图片后重试。'
|
||||
case 'ADMIN_ACCESS_DENIED':
|
||||
return '该账号没有管理后台权限。'
|
||||
case 'ACCOUNT_DISABLED':
|
||||
return '该管理员账号已被禁用。'
|
||||
case 'INVALID_REQUEST':
|
||||
return '请检查邮箱和验证码是否填写正确。'
|
||||
case 'DATABASE_UNAVAILABLE':
|
||||
return '服务暂时不可用,请稍后重试。'
|
||||
default:
|
||||
return errorMessage(error)
|
||||
}
|
||||
}
|
||||
|
||||
export function LoginPage() {
|
||||
const { user, signIn } = useAuth()
|
||||
const navigate = useNavigate(),
|
||||
location = useLocation()
|
||||
const returnTo = safeReturnPath((location.state as { from?: string } | null)?.from)
|
||||
const [phone, setPhone] = useState(''),
|
||||
[code, setCode] = useState('')
|
||||
const [phoneError, setPhoneError] = useState(''),
|
||||
[codeError, setCodeError] = useState('')
|
||||
const [message, setMessage] = useState(''),
|
||||
[sending, setSending] = useState(false),
|
||||
const [email, setEmail] = useState(''),
|
||||
[captchaAnswer, setCaptchaAnswer] = useState('')
|
||||
const [challenge, setChallenge] = useState<CaptchaChallenge | null>(null)
|
||||
const [loadingCaptcha, setLoadingCaptcha] = useState(false),
|
||||
[submitting, setSubmitting] = useState(false)
|
||||
const [emailError, setEmailError] = useState(''),
|
||||
[captchaError, setCaptchaError] = useState('')
|
||||
const [message, setMessage] = useState('')
|
||||
|
||||
useEffect(() => {
|
||||
if (user) navigate(returnTo, { replace: true })
|
||||
}, [user, returnTo, navigate])
|
||||
function checkPhone() {
|
||||
const valid = Boolean(phone.trim())
|
||||
setPhoneError(valid ? '' : '请输入手机号')
|
||||
return valid
|
||||
}
|
||||
async function sendCode() {
|
||||
if (!checkPhone() || sending) return
|
||||
setSending(true)
|
||||
setMessage('')
|
||||
|
||||
async function refreshCaptcha(preserveMessage = false, force = false) {
|
||||
if (loadingCaptcha || (submitting && !force)) return
|
||||
setLoadingCaptcha(true)
|
||||
if (!preserveMessage) setMessage('')
|
||||
setCaptchaError('')
|
||||
setCaptchaAnswer('')
|
||||
try {
|
||||
setCode(await authGateway.requestCode(phone))
|
||||
setCodeError('')
|
||||
setChallenge(await authGateway.requestCaptcha())
|
||||
} catch (error) {
|
||||
setMessage(errorMessage(error))
|
||||
setChallenge(null)
|
||||
setMessage(authErrorMessage(error))
|
||||
} finally {
|
||||
setSending(false)
|
||||
setLoadingCaptcha(false)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
void refreshCaptcha()
|
||||
// The challenge is intentionally fetched once when the page opens.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [])
|
||||
|
||||
function validate() {
|
||||
const normalizedEmail = email.trim()
|
||||
const validEmail =
|
||||
/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(normalizedEmail) && normalizedEmail.length <= 254
|
||||
const validAnswer = Boolean(captchaAnswer.trim()) && captchaAnswer.trim().length <= 32
|
||||
setEmailError(validEmail ? '' : '请输入有效的管理员邮箱(最多 254 个字符)')
|
||||
setCaptchaError(validAnswer ? '' : '请输入图片验证码')
|
||||
return validEmail && validAnswer && Boolean(challenge)
|
||||
}
|
||||
|
||||
async function submit(event: FormEvent) {
|
||||
event.preventDefault()
|
||||
const phoneValid = checkPhone(),
|
||||
codeValid = Boolean(code.trim())
|
||||
setCodeError(codeValid ? '' : '请输入验证码')
|
||||
if (!phoneValid || !codeValid || submitting) return
|
||||
if (!validate() || submitting || !challenge) return
|
||||
const currentChallenge = challenge
|
||||
setSubmitting(true)
|
||||
setMessage('')
|
||||
setChallenge(null)
|
||||
try {
|
||||
await signIn(phone, code)
|
||||
await signIn(email, currentChallenge.captchaCode, captchaAnswer)
|
||||
navigate(returnTo, { replace: true })
|
||||
} catch (error) {
|
||||
setMessage(errorMessage(error))
|
||||
setMessage(authErrorMessage(error))
|
||||
await refreshCaptcha(true, true)
|
||||
} finally {
|
||||
setSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="login-page">
|
||||
<section className="login-brand-panel" aria-label="CAD World 管理平台">
|
||||
@@ -90,71 +126,87 @@ export function LoginPage() {
|
||||
<ShieldCheck size={23} strokeWidth={1.5} />
|
||||
</div>
|
||||
<h2>登录管理控制台</h2>
|
||||
<p className="login-description">使用手机号和短信验证码登录</p>
|
||||
<p className="login-description">使用管理员邮箱和图片验证码登录</p>
|
||||
<form onSubmit={(event) => void submit(event)} noValidate>
|
||||
<label className="login-label" htmlFor="login-phone">
|
||||
手机号
|
||||
<label className="login-label" htmlFor="login-email">
|
||||
管理员邮箱
|
||||
</label>
|
||||
<div className={`login-phone-field ${phoneError ? 'invalid' : ''}`}>
|
||||
<span>+86</span>
|
||||
<div className={`login-email-field ${emailError ? 'invalid' : ''}`}>
|
||||
<input
|
||||
id="login-phone"
|
||||
type="tel"
|
||||
inputMode="tel"
|
||||
autoComplete="tel-national"
|
||||
placeholder="请输入手机号"
|
||||
maxLength={11}
|
||||
disabled={sending || submitting}
|
||||
value={phone}
|
||||
aria-invalid={!!phoneError}
|
||||
aria-describedby={phoneError ? 'phone-error' : undefined}
|
||||
id="login-email"
|
||||
type="email"
|
||||
inputMode="email"
|
||||
autoComplete="email"
|
||||
placeholder="请输入管理员邮箱"
|
||||
maxLength={254}
|
||||
disabled={submitting}
|
||||
value={email}
|
||||
aria-invalid={!!emailError}
|
||||
aria-describedby={emailError ? 'email-error' : undefined}
|
||||
onChange={(event) => {
|
||||
setPhone(event.target.value.replace(/\D/g, ''))
|
||||
setPhoneError('')
|
||||
setEmail(event.target.value)
|
||||
setEmailError('')
|
||||
setMessage('')
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
{phoneError && (
|
||||
<p className="field-error" id="phone-error">
|
||||
{phoneError}
|
||||
{emailError && (
|
||||
<p className="field-error" id="email-error" role="alert">
|
||||
{emailError}
|
||||
</p>
|
||||
)}
|
||||
<label className="login-label" htmlFor="login-code">
|
||||
验证码
|
||||
<label className="login-label" htmlFor="login-captcha-answer">
|
||||
图片验证码
|
||||
</label>
|
||||
<div className={`login-code-field ${codeError ? 'invalid' : ''}`}>
|
||||
<div className={`login-code-field ${captchaError ? 'invalid' : ''}`}>
|
||||
<input
|
||||
id="login-code"
|
||||
inputMode="numeric"
|
||||
autoComplete="one-time-code"
|
||||
placeholder="请输入验证码"
|
||||
maxLength={6}
|
||||
id="login-captcha-answer"
|
||||
inputMode="text"
|
||||
autoComplete="off"
|
||||
placeholder="请输入图片中的验证码"
|
||||
maxLength={32}
|
||||
disabled={submitting}
|
||||
value={code}
|
||||
aria-invalid={!!codeError}
|
||||
aria-describedby={codeError ? 'code-error' : undefined}
|
||||
value={captchaAnswer}
|
||||
aria-invalid={!!captchaError}
|
||||
aria-describedby={captchaError ? 'captcha-error' : undefined}
|
||||
onChange={(event) => {
|
||||
setCode(event.target.value.replace(/\D/g, ''))
|
||||
setCodeError('')
|
||||
setCaptchaAnswer(event.target.value)
|
||||
setCaptchaError('')
|
||||
setMessage('')
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
{captchaError && (
|
||||
<p className="field-error" id="captcha-error" role="alert">
|
||||
{captchaError}
|
||||
</p>
|
||||
)}
|
||||
<div className="captcha-row">
|
||||
<button
|
||||
type="button"
|
||||
disabled={sending || submitting}
|
||||
onClick={() => void sendCode()}
|
||||
className="captcha-image-button"
|
||||
aria-label="刷新图片验证码"
|
||||
onClick={() => void refreshCaptcha()}
|
||||
disabled={loadingCaptcha || submitting}
|
||||
>
|
||||
{sending ? '填写中…' : '获取验证码'}
|
||||
{challenge?.image ? (
|
||||
<img src={challenge.image} alt="图片验证码,点击刷新" />
|
||||
) : (
|
||||
<span>{loadingCaptcha ? '加载中…' : '验证码加载失败'}</span>
|
||||
)}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="captcha-refresh-button"
|
||||
aria-label="刷新图片验证码"
|
||||
onClick={() => void refreshCaptcha()}
|
||||
disabled={loadingCaptcha || submitting}
|
||||
>
|
||||
<RefreshCw size={16} className={loadingCaptcha ? 'spin' : ''} />
|
||||
</button>
|
||||
</div>
|
||||
{codeError && (
|
||||
<p className="field-error" id="code-error">
|
||||
{codeError}
|
||||
</p>
|
||||
)}
|
||||
{message && (
|
||||
<p className="login-message" role="status">
|
||||
<p className="login-message" role="alert">
|
||||
{message}
|
||||
</p>
|
||||
)}
|
||||
@@ -162,7 +214,7 @@ export function LoginPage() {
|
||||
type="submit"
|
||||
variant="primary"
|
||||
className="login-submit"
|
||||
disabled={submitting || sending}
|
||||
disabled={submitting || loadingCaptcha || !challenge}
|
||||
>
|
||||
{submitting ? <LoaderCircle size={17} className="spin" /> : null}
|
||||
{submitting ? '正在登录…' : '登录'}
|
||||
|
||||
+164
-170
@@ -1,8 +1,6 @@
|
||||
import { useDeferredValue, useEffect, useId, useState, type FormEvent } from 'react'
|
||||
import { Input, Pagination, Select, Space, Table, Tag, Tooltip, type TableColumnsType } from 'antd'
|
||||
import {
|
||||
ArrowLeft,
|
||||
ArrowRight,
|
||||
ChevronDown,
|
||||
LoaderCircle,
|
||||
Pencil,
|
||||
Plus,
|
||||
@@ -28,7 +26,7 @@ import { Button, Field, Loading, Modal, Notice, PageHeading } from '@/components
|
||||
|
||||
const newUser = (): UserInput => ({
|
||||
name: '',
|
||||
phone: '',
|
||||
email: '',
|
||||
role: 'viewer',
|
||||
status: 'enabled',
|
||||
})
|
||||
@@ -83,9 +81,7 @@ export function UsersPage() {
|
||||
useEffect(() => {
|
||||
setPage(1)
|
||||
}, [search, role, status])
|
||||
const pages = Math.max(1, Math.ceil(total / 10)),
|
||||
currentPage = page,
|
||||
visible = users
|
||||
const visible = users
|
||||
const enabled = counts.enabled
|
||||
async function deleteUser() {
|
||||
if (!removing) return
|
||||
@@ -117,7 +113,7 @@ export function UsersPage() {
|
||||
input: item
|
||||
? {
|
||||
name: item.name,
|
||||
phone: item.phone,
|
||||
email: item.email,
|
||||
role: item.role,
|
||||
status: item.status,
|
||||
}
|
||||
@@ -164,6 +160,93 @@ export function UsersPage() {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
const columns: TableColumnsType<ManagedUser> = [
|
||||
{
|
||||
title: '用户',
|
||||
key: 'user',
|
||||
width: 190,
|
||||
render: (_, item) => (
|
||||
<div className="user-cell">
|
||||
<span className="user-list-avatar">
|
||||
<UserRound size={17} />
|
||||
</span>
|
||||
<strong>{item.name}</strong>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{ title: '邮箱', dataIndex: 'email', key: 'email', width: 220, className: 'user-email' },
|
||||
{
|
||||
title: '角色',
|
||||
dataIndex: 'role',
|
||||
key: 'role',
|
||||
width: 110,
|
||||
render: (value: UserRole) => (
|
||||
<span className={`user-role user-role-${value}`}>{userRoles[value]}</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '状态',
|
||||
dataIndex: 'status',
|
||||
key: 'status',
|
||||
width: 105,
|
||||
render: (value: UserStatus) => (
|
||||
<Tag color={value === 'enabled' ? 'success' : 'default'}>{userStatuses[value]}</Tag>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '创建时间',
|
||||
dataIndex: 'createdAt',
|
||||
key: 'createdAt',
|
||||
width: 160,
|
||||
render: (value: string) => <span className="date-cell">{formatDate(value)}</span>,
|
||||
},
|
||||
{
|
||||
title: '更新时间',
|
||||
dataIndex: 'updatedAt',
|
||||
key: 'updatedAt',
|
||||
width: 160,
|
||||
render: (value: string) => <span className="date-cell">{formatDate(value)}</span>,
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
key: 'actions',
|
||||
width: 170,
|
||||
align: 'right',
|
||||
render: (_, item) => (
|
||||
<Space size={2}>
|
||||
<Tooltip title="编辑用户">
|
||||
<Button
|
||||
aria-label={`编辑用户 ${item.name}`}
|
||||
icon={<Pencil size={16} />}
|
||||
variant="ghost"
|
||||
onClick={() => void openEditor(item)}
|
||||
/>
|
||||
</Tooltip>
|
||||
<Tooltip title="删除用户">
|
||||
<Button
|
||||
aria-label={`删除用户 ${item.name}`}
|
||||
icon={<Trash2 size={16} />}
|
||||
variant="ghost"
|
||||
onClick={() => {
|
||||
setFormError('')
|
||||
setRemoving(item)
|
||||
}}
|
||||
/>
|
||||
</Tooltip>
|
||||
<Button
|
||||
danger={item.status === 'enabled'}
|
||||
size="small"
|
||||
onClick={() => {
|
||||
setFormError('')
|
||||
setChanging(item)
|
||||
}}
|
||||
>
|
||||
{item.status === 'enabled' ? '停用' : '启用'}
|
||||
</Button>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
]
|
||||
return (
|
||||
<>
|
||||
<PageHeading title="用户管理" description="管理用户信息、角色与账号状态。">
|
||||
@@ -212,44 +295,38 @@ export function UsersPage() {
|
||||
</div>
|
||||
<section className="library-panel users-panel">
|
||||
<div className="library-toolbar activity-toolbar">
|
||||
<div className="search-field">
|
||||
<Search size={16} />
|
||||
<input
|
||||
data-search
|
||||
aria-label="搜索用户"
|
||||
placeholder="搜索用户昵称或手机号"
|
||||
value={query}
|
||||
onChange={(event) => setQuery(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<Input
|
||||
allowClear
|
||||
className="catalog-search"
|
||||
data-search
|
||||
aria-label="搜索用户"
|
||||
prefix={<Search size={16} />}
|
||||
placeholder="搜索用户昵称或邮箱"
|
||||
value={query}
|
||||
onChange={(event) => setQuery(event.target.value)}
|
||||
/>
|
||||
<div className="filter-tools">
|
||||
<div className="select-wrap">
|
||||
<select
|
||||
aria-label="筛选用户角色"
|
||||
value={role}
|
||||
onChange={(event) => setRole(event.target.value)}
|
||||
>
|
||||
<option value="all">全部角色</option>
|
||||
{Object.entries(userRoles).map(([value, label]) => (
|
||||
<option value={value} key={value}>
|
||||
{label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<ChevronDown size={14} />
|
||||
</div>
|
||||
<div className="select-wrap">
|
||||
<select
|
||||
aria-label="筛选用户状态"
|
||||
value={status}
|
||||
onChange={(event) => setStatus(event.target.value)}
|
||||
>
|
||||
<option value="all">全部状态</option>
|
||||
<option value="enabled">启用</option>
|
||||
<option value="disabled">停用</option>
|
||||
</select>
|
||||
<ChevronDown size={14} />
|
||||
</div>
|
||||
<Select
|
||||
aria-label="筛选用户角色"
|
||||
className="catalog-category-filter"
|
||||
options={[
|
||||
{ value: 'all', label: '全部角色' },
|
||||
...Object.entries(userRoles).map(([value, label]) => ({ value, label })),
|
||||
]}
|
||||
value={role}
|
||||
onChange={setRole}
|
||||
/>
|
||||
<Select
|
||||
aria-label="筛选用户状态"
|
||||
className="catalog-category-filter"
|
||||
options={[
|
||||
{ value: 'all', label: '全部状态' },
|
||||
{ value: 'enabled', label: '启用' },
|
||||
{ value: 'disabled', label: '停用' },
|
||||
]}
|
||||
value={status}
|
||||
onChange={setStatus}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{loading ? (
|
||||
@@ -278,104 +355,25 @@ export function UsersPage() {
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="table-scroll">
|
||||
<table className="resource-table users-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>用户</th>
|
||||
<th>手机号</th>
|
||||
<th>角色</th>
|
||||
<th>状态</th>
|
||||
<th>创建时间</th>
|
||||
<th>更新时间</th>
|
||||
<th className="action-cell">操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{visible.map((item) => (
|
||||
<tr key={item.id}>
|
||||
<td>
|
||||
<div className="user-cell">
|
||||
<span className="user-list-avatar">
|
||||
<UserRound size={17} />
|
||||
</span>
|
||||
<div>
|
||||
<strong>{item.name}</strong>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
<td className="user-phone">{item.phone}</td>
|
||||
<td>
|
||||
<span className={`user-role user-role-${item.role}`}>
|
||||
{userRoles[item.role === 'admin' ? 'admin' : 'viewer']}
|
||||
</span>
|
||||
</td>
|
||||
<td>
|
||||
<span className={`user-status user-status-${item.status}`}>
|
||||
<i />
|
||||
{userStatuses[item.status]}
|
||||
</span>
|
||||
</td>
|
||||
<td className="date-cell">{formatDate(item.createdAt)}</td>
|
||||
<td className="date-cell">{formatDate(item.updatedAt)}</td>
|
||||
<td className="action-cell">
|
||||
<div className="user-row-actions">
|
||||
<button
|
||||
className="icon-button"
|
||||
aria-label={`编辑用户 ${item.name}`}
|
||||
onClick={() => openEditor(item)}
|
||||
>
|
||||
<Pencil size={16} />
|
||||
</button>
|
||||
<button
|
||||
className="icon-button"
|
||||
aria-label={`删除用户 ${item.name}`}
|
||||
onClick={() => {
|
||||
setFormError('')
|
||||
setRemoving(item)
|
||||
}}
|
||||
>
|
||||
<Trash2 size={16} />
|
||||
</button>
|
||||
<button
|
||||
className={`user-status-button ${item.status === 'enabled' ? 'user-stop-button' : ''}`}
|
||||
aria-label={`${item.status === 'enabled' ? '停用' : '启用'}用户 ${item.name}`}
|
||||
onClick={() => {
|
||||
setFormError('')
|
||||
setChanging(item)
|
||||
}}
|
||||
>
|
||||
{item.status === 'enabled' ? '停用' : '启用'}
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<Table
|
||||
className="users-table"
|
||||
columns={columns}
|
||||
dataSource={visible}
|
||||
pagination={false}
|
||||
rowKey="id"
|
||||
scroll={{ x: 1120 }}
|
||||
/>
|
||||
)}
|
||||
<div className="table-footer">
|
||||
<span>共 {total} 位用户</span>
|
||||
<div className="pagination">
|
||||
<button
|
||||
aria-label="上一页"
|
||||
disabled={currentPage === 1}
|
||||
onClick={() => setPage(currentPage - 1)}
|
||||
>
|
||||
<ArrowLeft size={15} />
|
||||
</button>
|
||||
<span>
|
||||
{currentPage} <small>/ {pages}</small>
|
||||
</span>
|
||||
<button
|
||||
aria-label="下一页"
|
||||
disabled={currentPage >= pages}
|
||||
onClick={() => setPage(currentPage + 1)}
|
||||
>
|
||||
<ArrowRight size={15} />
|
||||
</button>
|
||||
</div>
|
||||
<div className="table-footer ant-pagination-footer">
|
||||
<Pagination
|
||||
current={page}
|
||||
disabled={loading}
|
||||
pageSize={10}
|
||||
showSizeChanger={false}
|
||||
showTotal={(value) => `共 ${value} 位用户`}
|
||||
total={total}
|
||||
onChange={setPage}
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
{editor && (
|
||||
@@ -400,7 +398,7 @@ export function UsersPage() {
|
||||
{formError && <Notice variant="error">{formError}</Notice>}
|
||||
<div className="user-form-grid">
|
||||
<Field label="姓名" required>
|
||||
<input
|
||||
<Input
|
||||
value={editor.input.name}
|
||||
maxLength={64}
|
||||
autoComplete="off"
|
||||
@@ -409,40 +407,36 @@ export function UsersPage() {
|
||||
onChange={(event) => update({ name: event.target.value })}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="手机号" required>
|
||||
<input
|
||||
type="tel"
|
||||
inputMode="tel"
|
||||
value={editor.input.phone}
|
||||
maxLength={11}
|
||||
autoComplete="off"
|
||||
<Field label="邮箱" required>
|
||||
<Input
|
||||
type="email"
|
||||
inputMode="email"
|
||||
value={editor.input.email}
|
||||
maxLength={254}
|
||||
autoComplete="email"
|
||||
disabled={busy}
|
||||
placeholder="请输入 11 位手机号"
|
||||
onChange={(event) => update({ phone: event.target.value.replace(/\D/g, '') })}
|
||||
placeholder="请输入邮箱地址"
|
||||
onChange={(event) => update({ email: event.target.value })}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="角色" required>
|
||||
<select
|
||||
value={editor.input.role}
|
||||
<Select
|
||||
disabled={busy}
|
||||
onChange={(event) => update({ role: event.target.value as UserRole })}
|
||||
>
|
||||
{Object.entries(userRoles).map(([value, label]) => (
|
||||
<option value={value} key={value}>
|
||||
{label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
options={Object.entries(userRoles).map(([value, label]) => ({ value, label }))}
|
||||
value={editor.input.role}
|
||||
onChange={(value) => update({ role: value as UserRole })}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="账号状态" required>
|
||||
<select
|
||||
value={editor.input.status}
|
||||
<Select
|
||||
disabled={busy}
|
||||
onChange={(event) => update({ status: event.target.value as UserStatus })}
|
||||
>
|
||||
<option value="enabled">启用</option>
|
||||
<option value="disabled">停用</option>
|
||||
</select>
|
||||
options={[
|
||||
{ value: 'enabled', label: '启用' },
|
||||
{ value: 'disabled', label: '停用' },
|
||||
]}
|
||||
value={editor.input.status}
|
||||
onChange={(value) => update({ status: value as UserStatus })}
|
||||
/>
|
||||
</Field>
|
||||
</div>
|
||||
</form>
|
||||
@@ -451,7 +445,7 @@ export function UsersPage() {
|
||||
{removing && (
|
||||
<Modal
|
||||
title="删除用户"
|
||||
description={`确认删除「${removing.name}」?删除后手机号仍被占用,不能重新注册。`}
|
||||
description={`确认删除「${removing.name}」?删除后邮箱仍被占用,不能重新注册。`}
|
||||
onClose={() => {
|
||||
if (!busy) setRemoving(null)
|
||||
}}
|
||||
|
||||
+354
-20
@@ -768,6 +768,13 @@ h1 {
|
||||
color: var(--text-secondary);
|
||||
font-size: 13px;
|
||||
}
|
||||
.loading-page {
|
||||
min-height: 100dvh;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
color: var(--text-secondary);
|
||||
font-size: 13px;
|
||||
}
|
||||
.spin {
|
||||
animation: spin 1s linear infinite;
|
||||
}
|
||||
@@ -1609,7 +1616,7 @@ h1 {
|
||||
justify-items: start;
|
||||
}
|
||||
|
||||
/* Phone and SMS login. The visual is built with CSS, without remote assets. */
|
||||
/* Administrator email and image CAPTCHA login. */
|
||||
.login-page {
|
||||
min-height: 100dvh;
|
||||
display: grid;
|
||||
@@ -1762,7 +1769,7 @@ h1 {
|
||||
.login-label:not(:first-child) {
|
||||
margin-top: 25px;
|
||||
}
|
||||
.login-phone-field,
|
||||
.login-email-field,
|
||||
.login-code-field {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -1771,17 +1778,11 @@ h1 {
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 7px;
|
||||
}
|
||||
.login-phone-field:focus-within,
|
||||
.login-email-field:focus-within,
|
||||
.login-code-field:focus-within {
|
||||
border-color: var(--accent);
|
||||
box-shadow: 0 0 0 3px rgba(77, 163, 255, 0.08);
|
||||
}
|
||||
.login-phone-field > span {
|
||||
border-right: 1px solid var(--border);
|
||||
color: var(--text-secondary);
|
||||
padding: 0 14px;
|
||||
font-size: 13px;
|
||||
}
|
||||
.login-card input {
|
||||
min-width: 0;
|
||||
width: 100%;
|
||||
@@ -1800,17 +1801,50 @@ h1 {
|
||||
.login-card input::placeholder {
|
||||
color: var(--text-tertiary);
|
||||
}
|
||||
.login-code-field button {
|
||||
border: 0;
|
||||
border-left: 1px solid var(--border);
|
||||
background: transparent;
|
||||
color: var(--accent);
|
||||
padding: 0 14px;
|
||||
font-size: 12px;
|
||||
white-space: nowrap;
|
||||
.captcha-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
margin-top: 12px;
|
||||
}
|
||||
.login-code-field button:disabled {
|
||||
opacity: 0.55;
|
||||
.captcha-image-button {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
height: 60px;
|
||||
padding: 0;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
overflow: hidden;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 7px;
|
||||
color: var(--text-tertiary);
|
||||
background: var(--panel);
|
||||
}
|
||||
.captcha-image-button:hover:not(:disabled),
|
||||
.captcha-refresh-button:hover:not(:disabled) {
|
||||
border-color: var(--accent);
|
||||
}
|
||||
.captcha-image-button img {
|
||||
display: block;
|
||||
width: 180px;
|
||||
height: 60px;
|
||||
object-fit: contain;
|
||||
}
|
||||
.captcha-refresh-button {
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
flex: 0 0 44px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 7px;
|
||||
background: var(--panel);
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
.captcha-image-button:disabled,
|
||||
.captcha-refresh-button:disabled {
|
||||
cursor: wait;
|
||||
opacity: 0.65;
|
||||
}
|
||||
.login-card .invalid {
|
||||
border-color: var(--danger);
|
||||
@@ -1967,7 +2001,7 @@ h1 {
|
||||
text-overflow: ellipsis;
|
||||
margin-top: 5px;
|
||||
}
|
||||
.user-phone {
|
||||
.user-email {
|
||||
font-size: 12px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
white-space: nowrap;
|
||||
@@ -2136,6 +2170,56 @@ h1 {
|
||||
color: var(--text-secondary);
|
||||
background: var(--panel-muted);
|
||||
}
|
||||
.component-status-control {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
min-width: 76px;
|
||||
font-size: 11px;
|
||||
color: var(--text-tertiary);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.component-status-control > span.is-enabled {
|
||||
color: var(--success);
|
||||
}
|
||||
.component-status-switch {
|
||||
width: 34px;
|
||||
height: 20px;
|
||||
padding: 2px;
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: 10px;
|
||||
background: var(--panel-muted);
|
||||
transition:
|
||||
background-color 160ms ease,
|
||||
border-color 160ms ease;
|
||||
}
|
||||
.component-status-switch > span {
|
||||
display: block;
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
border-radius: 50%;
|
||||
background: var(--text-tertiary);
|
||||
transition:
|
||||
transform 160ms ease,
|
||||
background-color 160ms ease;
|
||||
}
|
||||
.component-status-switch:hover:not(:disabled) {
|
||||
border-color: var(--text-secondary);
|
||||
}
|
||||
.component-status-switch.is-enabled {
|
||||
border-color: var(--success);
|
||||
background: color-mix(in srgb, var(--success) 22%, var(--panel));
|
||||
}
|
||||
.component-status-switch.is-enabled > span {
|
||||
transform: translateX(14px);
|
||||
background: var(--success);
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.component-status-switch,
|
||||
.component-status-switch > span {
|
||||
transition: none;
|
||||
}
|
||||
}
|
||||
.component-upload-heading {
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
@@ -2864,3 +2948,253 @@ h1 {
|
||||
overflow-wrap: anywhere;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
/* Ant Design controls inherit the console's compact dark visual language. */
|
||||
.ant-btn {
|
||||
min-height: 35px;
|
||||
border-radius: 6px;
|
||||
font-size: 12px;
|
||||
font-weight: 550;
|
||||
box-shadow: none;
|
||||
}
|
||||
.ant-btn-default {
|
||||
background: var(--panel);
|
||||
}
|
||||
.ant-btn-default:not(:disabled):hover {
|
||||
background: var(--surface-hover);
|
||||
border-color: var(--border-strong);
|
||||
}
|
||||
.ant-btn-text:not(:disabled):hover {
|
||||
background: var(--surface-hover);
|
||||
}
|
||||
.ant-btn-dangerous.ant-btn-primary {
|
||||
color: #101010;
|
||||
}
|
||||
.ant-btn:focus-visible,
|
||||
.ant-input:focus-visible,
|
||||
.ant-select-focused .ant-select-selector,
|
||||
.ant-switch:focus-visible,
|
||||
.ant-pagination-item:focus-visible {
|
||||
outline: 3px solid var(--accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.app-field {
|
||||
min-width: 0;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
.app-field .ant-form-item-label {
|
||||
padding-bottom: 8px;
|
||||
}
|
||||
.app-field .ant-form-item-label > label {
|
||||
color: var(--text-primary);
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
}
|
||||
.app-field .ant-form-item-extra {
|
||||
color: var(--text-tertiary);
|
||||
font-size: 10px;
|
||||
line-height: 1.9;
|
||||
}
|
||||
.app-field :is(.ant-input, .ant-input-affix-wrapper, .ant-input-number, .ant-select) {
|
||||
width: 100%;
|
||||
}
|
||||
.app-field input:not(.ant-input),
|
||||
.app-field textarea:not(.ant-input),
|
||||
.app-field select:not(.ant-select-selection-search-input) {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
padding: 10px 11px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 5px;
|
||||
background: var(--panel);
|
||||
color: var(--text-primary);
|
||||
font-size: 12px;
|
||||
line-height: 1.4;
|
||||
}
|
||||
.app-field textarea:not(.ant-input) {
|
||||
min-height: 65px;
|
||||
resize: vertical;
|
||||
}
|
||||
.app-field input:not(.ant-input)::placeholder,
|
||||
.app-field textarea:not(.ant-input)::placeholder {
|
||||
color: var(--text-tertiary);
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.catalog-search {
|
||||
width: min(350px, 100%);
|
||||
}
|
||||
.catalog-search .ant-input {
|
||||
font-size: 12px;
|
||||
}
|
||||
.catalog-search kbd {
|
||||
padding: 2px 4px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 3px;
|
||||
background: var(--panel);
|
||||
color: var(--text-tertiary);
|
||||
font-size: 10px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.catalog-category-filter {
|
||||
width: 160px;
|
||||
}
|
||||
.ant-segmented {
|
||||
padding: 3px;
|
||||
}
|
||||
.ant-segmented .ant-segmented-item {
|
||||
min-height: 27px;
|
||||
font-size: 12px;
|
||||
}
|
||||
.component-status-control .ant-switch {
|
||||
min-width: 34px;
|
||||
}
|
||||
|
||||
.library-panel > :is(.catalog-table, .users-table, .activity-table) {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow: auto;
|
||||
overscroll-behavior: contain;
|
||||
}
|
||||
.catalog-table .ant-table,
|
||||
.users-table .ant-table,
|
||||
.activity-table .ant-table {
|
||||
background: var(--panel);
|
||||
color: var(--text-primary);
|
||||
font-size: 12px;
|
||||
}
|
||||
.catalog-table .ant-table-thead > tr > th,
|
||||
.users-table .ant-table-thead > tr > th,
|
||||
.activity-table .ant-table-thead > tr > th {
|
||||
padding: 13px 18px;
|
||||
background: var(--bg-subtle);
|
||||
color: var(--text-secondary);
|
||||
border-bottom: 1px solid var(--border);
|
||||
font-size: 11px;
|
||||
font-weight: 450;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.catalog-table .ant-table-tbody > tr > td,
|
||||
.users-table .ant-table-tbody > tr > td,
|
||||
.activity-table .ant-table-tbody > tr > td {
|
||||
padding: 18px;
|
||||
border-bottom-color: var(--border);
|
||||
background: var(--panel);
|
||||
color: var(--text-primary);
|
||||
vertical-align: middle;
|
||||
}
|
||||
.catalog-table .ant-table-tbody > tr.ant-table-row:hover > td,
|
||||
.users-table .ant-table-tbody > tr.ant-table-row:hover > td,
|
||||
.activity-table .ant-table-tbody > tr.ant-table-row:hover > td {
|
||||
background: var(--surface-hover);
|
||||
}
|
||||
.catalog-table .ant-table-cell,
|
||||
.users-table .ant-table-cell,
|
||||
.activity-table .ant-table-cell {
|
||||
border-bottom-color: var(--border);
|
||||
}
|
||||
.activity-table .ant-table-tbody > tr > td {
|
||||
white-space: nowrap;
|
||||
}
|
||||
.activity-table .ant-tag,
|
||||
.users-table .ant-tag {
|
||||
min-width: 48px;
|
||||
margin-inline-end: 0;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.ant-pagination-footer {
|
||||
justify-content: flex-end;
|
||||
min-height: 64px;
|
||||
}
|
||||
.ant-pagination-footer .ant-pagination {
|
||||
margin: 0;
|
||||
}
|
||||
.ant-pagination-total-text {
|
||||
margin-inline-end: 14px;
|
||||
color: var(--text-tertiary);
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.app-loading {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 12px;
|
||||
padding: 80px;
|
||||
}
|
||||
.app-loading > span {
|
||||
color: var(--text-secondary);
|
||||
font-size: 13px;
|
||||
}
|
||||
.app-empty-state {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
padding: 44px 24px;
|
||||
}
|
||||
.app-empty-state .ant-empty-description > span {
|
||||
display: grid;
|
||||
gap: 10px;
|
||||
}
|
||||
.app-empty-state .ant-empty-description strong {
|
||||
color: var(--text-primary);
|
||||
font-size: 16px;
|
||||
font-weight: 550;
|
||||
}
|
||||
.app-empty-state .ant-empty-description small {
|
||||
color: var(--text-secondary);
|
||||
font-size: 12px;
|
||||
line-height: 1.8;
|
||||
}
|
||||
.app-notice {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
.app-modal-description {
|
||||
margin: 0 0 18px;
|
||||
color: var(--text-secondary);
|
||||
font-size: 12px;
|
||||
line-height: 1.8;
|
||||
}
|
||||
.ant-modal .ant-modal-content {
|
||||
padding: 24px;
|
||||
border: 1px solid var(--border);
|
||||
box-shadow: 0 20px 100px rgba(0, 0, 0, 0.45);
|
||||
}
|
||||
.ant-modal .ant-modal-header {
|
||||
margin-bottom: 20px;
|
||||
background: transparent;
|
||||
}
|
||||
.ant-modal .ant-modal-title {
|
||||
color: var(--text-primary);
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.ant-modal .ant-modal-footer {
|
||||
margin-top: 22px;
|
||||
}
|
||||
|
||||
@media (max-width: 1080px) {
|
||||
.catalog-search {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
@media (max-width: 600px) {
|
||||
.ant-pagination-footer {
|
||||
justify-content: center;
|
||||
min-height: 60px;
|
||||
}
|
||||
.ant-pagination-footer .ant-pagination {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
justify-content: center;
|
||||
}
|
||||
.log-filters .app-field {
|
||||
flex-basis: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import { componentForm, emptyPartInformation } from '@/domain/component-catalog'
|
||||
import { activityGateway } from '@/application/activity-gateway'
|
||||
import { userGateway } from '@/application/user-gateway'
|
||||
import { api, assetUrl, proxyUrl } from '@/infrastructure/admin-api'
|
||||
import { clearAuthSession, readAuthSession, writeAuthSession } from '@/application/auth'
|
||||
import type { ComponentDetail } from '@/domain/component-catalog'
|
||||
afterEach(() => vi.unstubAllGlobals())
|
||||
it('downloads STEP, URDF and meshes directly from storage without API cookies', async () => {
|
||||
@@ -62,6 +63,33 @@ it('sends only document-supported search and paging fields', async () => {
|
||||
category: '安装板',
|
||||
})
|
||||
})
|
||||
it('updates a component status through the existing component editor endpoint', async () => {
|
||||
const item = {
|
||||
...componentForm({ ...emptyPartInformation(), name: '安装板', category: '自由分类' }),
|
||||
id: 123,
|
||||
componentCode: 'CW-123',
|
||||
status: 'ENABLED',
|
||||
stepUrl: '/admin-api/component-assets/step/part.step',
|
||||
version: 1,
|
||||
createdAt: '',
|
||||
updatedAt: '',
|
||||
}
|
||||
const fetcher = vi
|
||||
.fn<typeof fetch>()
|
||||
.mockResolvedValueOnce(ok(item))
|
||||
.mockResolvedValueOnce(ok({ ...item, status: 'DISABLED', version: 2 }))
|
||||
vi.stubGlobal('fetch', fetcher)
|
||||
await componentGateway.setStatus(123, 'DISABLED')
|
||||
expect(fetcher.mock.calls[0][0]).toBe('/admin-api/components/123')
|
||||
const [url, options] = fetcher.mock.calls[1] as unknown as [string, RequestInit]
|
||||
expect(url).toBe('/admin-api/components/123')
|
||||
expect(options.method).toBe('PUT')
|
||||
expect(JSON.parse(options.body as string)).toEqual({
|
||||
...componentForm({ ...emptyPartInformation(), name: '安装板', category: '自由分类' }),
|
||||
status: 'DISABLED',
|
||||
version: 1,
|
||||
})
|
||||
})
|
||||
it('preserves revision conflict codes and backend request IDs', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
@@ -78,6 +106,31 @@ it('preserves revision conflict codes and backend request IDs', async () => {
|
||||
requestId: 'conflict-1',
|
||||
})
|
||||
})
|
||||
it('sends admin Bearer tokens without cookies and clears expired sessions on 401', async () => {
|
||||
const session = {
|
||||
token: 'admin-token',
|
||||
tokenType: 'Bearer',
|
||||
expiresAt: Date.now() + 60000,
|
||||
user: { userCode: 'A', nickname: '管理员', email: 'admin@example.com' },
|
||||
}
|
||||
writeAuthSession(session)
|
||||
const fetcher = vi.fn<typeof fetch>(async () => ok({ items: [] }))
|
||||
vi.stubGlobal('fetch', fetcher)
|
||||
await api('/admin-api/components')
|
||||
const options = fetcher.mock.calls[0][1] as RequestInit
|
||||
expect(options.credentials).toBe('omit')
|
||||
expect(new Headers(options.headers).get('Authorization')).toBe('Bearer admin-token')
|
||||
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn<typeof fetch>(async () =>
|
||||
Response.json({ code: 'UNAUTHORIZED', message: '登录失效' }, { status: 401 }),
|
||||
),
|
||||
)
|
||||
await expect(api('/admin-api/components')).rejects.toMatchObject({ status: 401 })
|
||||
expect(readAuthSession()).toBeNull()
|
||||
clearAuthSession()
|
||||
})
|
||||
it('keeps API routing separate and encodes object keys for direct storage downloads', () => {
|
||||
expect(proxyUrl('http://127.0.0.1:8992/admin-api/component-assets/a/b')).toBe(
|
||||
'/admin-api/component-assets/a/b',
|
||||
@@ -105,12 +158,12 @@ it('passes generic module and target filters without assuming component-only IDs
|
||||
expect(url.searchParams.get('success')).toBe('false')
|
||||
expect(url.searchParams.get('module')).toBe('FUTURE')
|
||||
})
|
||||
it('maps user fields to nickname/type/status without unsupported local fields', async () => {
|
||||
it('maps user fields to nickname/email/type/status without unsupported local fields', async () => {
|
||||
const fetcher = vi.fn<typeof fetch>(async () =>
|
||||
ok({
|
||||
id: 1,
|
||||
nickname: '小王',
|
||||
phone: '13812345678',
|
||||
email: 'xiaowang@example.com',
|
||||
userType: 'NORMAL',
|
||||
status: 'ACTIVE',
|
||||
createdAt: '',
|
||||
@@ -120,15 +173,40 @@ it('maps user fields to nickname/type/status without unsupported local fields',
|
||||
vi.stubGlobal('fetch', fetcher)
|
||||
await userGateway.createUser({
|
||||
name: '小王',
|
||||
phone: '13812345678',
|
||||
email: ' Xiaowang@Example.com ',
|
||||
role: 'viewer',
|
||||
status: 'enabled',
|
||||
})
|
||||
const options = fetcher.mock.calls[0][1] as unknown as RequestInit
|
||||
expect(JSON.parse(options.body as string)).toEqual({
|
||||
nickname: '小王',
|
||||
phone: '13812345678',
|
||||
email: 'xiaowang@example.com',
|
||||
userType: 'NORMAL',
|
||||
status: 'ACTIVE',
|
||||
})
|
||||
})
|
||||
|
||||
it('loads and updates user email through the detail and edit endpoints', async () => {
|
||||
const fetcher = vi.fn<typeof fetch>(async () =>
|
||||
ok({
|
||||
id: 42,
|
||||
nickname: '小王',
|
||||
email: 'xiaowang@example.com',
|
||||
userType: 'NORMAL',
|
||||
status: 'ACTIVE',
|
||||
createdAt: '',
|
||||
updatedAt: '',
|
||||
}),
|
||||
)
|
||||
vi.stubGlobal('fetch', fetcher)
|
||||
|
||||
const user = await userGateway.detail('42')
|
||||
expect(user.email).toBe('xiaowang@example.com')
|
||||
await userGateway.updateUser(user.id, { ...user, email: 'new@example.com' })
|
||||
|
||||
const options = fetcher.mock.calls[1][1] as unknown as RequestInit
|
||||
expect(options.method).toBe('PUT')
|
||||
expect(JSON.parse(options.body as string)).toMatchObject({
|
||||
email: 'new@example.com',
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
import { afterEach, expect, it, vi } from 'vitest'
|
||||
import { api, proxyUrl, downloadFile } from '@/infrastructure/admin-api'
|
||||
import { writeAuthSession } from '@/application/auth'
|
||||
import { apiOrigin } from '../../shared/api-origin.ts'
|
||||
|
||||
afterEach(() => vi.unstubAllGlobals())
|
||||
afterEach(() => {
|
||||
writeAuthSession(null)
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
it('selects business API by host and downloads models directly from storage', async () => {
|
||||
vi.stubGlobal('window', { location: { origin: 'https://cadworld-admin.robotquan.com' } })
|
||||
@@ -14,16 +18,27 @@ it('selects business API by host and downloads models directly from storage', as
|
||||
expect(fetcher.mock.calls[0][0]).toBe(
|
||||
'https://cadworld-api.robotquan.com/admin-api/components?page=1&size=10',
|
||||
)
|
||||
expect(fetcher.mock.calls[0][1]?.credentials).toBe('include')
|
||||
expect(fetcher.mock.calls[0][1]?.credentials).toBe('omit')
|
||||
expect(proxyUrl('http://127.0.0.1:8992/admin-api/component-assets/CW/a.STL?v=2')).toBe(
|
||||
'https://cadworld-api.robotquan.com/admin-api/component-assets/CW/a.STL?v=2',
|
||||
)
|
||||
expect(proxyUrl('https://bucket.example/file?signature=x')).toBe(
|
||||
'https://bucket.example/file?signature=x',
|
||||
)
|
||||
writeAuthSession({
|
||||
token: 'admin-token',
|
||||
tokenType: 'Bearer',
|
||||
expiresAt: Date.now() + 60000,
|
||||
user: { userCode: 'A', nickname: '管理员', email: 'admin@example.com' },
|
||||
})
|
||||
await downloadFile('/admin-api/component-assets/CW/a.STL', 'a.STL')
|
||||
expect(fetcher.mock.calls[1][0]).toBe('https://linkerbot.oss-cn-beijing.aliyuncs.com/CW/a.STL')
|
||||
expect(fetcher.mock.calls[1][0]).toBe(
|
||||
'https://cadworld-api.robotquan.com/admin-api/component-assets/CW/a.STL',
|
||||
)
|
||||
expect(fetcher.mock.calls[1][1]?.credentials).toBe('omit')
|
||||
expect(new Headers(fetcher.mock.calls[1][1]?.headers).get('Authorization')).toBe(
|
||||
'Bearer admin-token',
|
||||
)
|
||||
})
|
||||
|
||||
it('selects development API for dev websites and keeps local development proxies', () => {
|
||||
|
||||
@@ -1,24 +1,35 @@
|
||||
import { beforeEach, expect, it } from 'vitest'
|
||||
import { readAuthSession, writeAuthSession } from '@/application/auth-session'
|
||||
import {
|
||||
clearAuthSession,
|
||||
readAuthSession,
|
||||
writeAuthSession,
|
||||
type AuthSession,
|
||||
} from '@/application/auth'
|
||||
|
||||
beforeEach(() => sessionStorage.clear())
|
||||
it('restores temporary login on refresh and clears it on logout', () => {
|
||||
const user = { id: 'temporary-13800000000', phone: '13800000000', name: '管理员' }
|
||||
writeAuthSession(user)
|
||||
expect(readAuthSession()).toEqual(user)
|
||||
writeAuthSession(null)
|
||||
beforeEach(() => localStorage.clear())
|
||||
|
||||
const session: AuthSession = {
|
||||
token: 'token-1',
|
||||
tokenType: 'Bearer',
|
||||
expiresAt: Date.now() + 86400000,
|
||||
user: { userCode: 'A', nickname: '管理员', email: 'admin@example.com' },
|
||||
}
|
||||
|
||||
it('restores a valid token session on refresh and clears it on logout', () => {
|
||||
writeAuthSession(session)
|
||||
expect(readAuthSession()).toEqual(session)
|
||||
clearAuthSession()
|
||||
expect(readAuthSession()).toBeNull()
|
||||
})
|
||||
it('ignores old preview flags, corrupt storage and unrelated sessions', () => {
|
||||
sessionStorage.setItem('cadworld-management-preview', 'true')
|
||||
|
||||
it('clears expired and corrupt storage', () => {
|
||||
writeAuthSession({ ...session, expiresAt: Date.now() - 1 })
|
||||
expect(readAuthSession()).toBeNull()
|
||||
localStorage.setItem('cadworld-management-auth', 'not-json')
|
||||
expect(readAuthSession()).toBeNull()
|
||||
localStorage.setItem(
|
||||
'cadworld-management-auth',
|
||||
JSON.stringify({ token: 'x', tokenType: 'Bearer', expiresAt: Date.now() + 1000 }),
|
||||
)
|
||||
expect(readAuthSession()).toBeNull()
|
||||
for (const payload of [
|
||||
'not-json',
|
||||
'null',
|
||||
'{}',
|
||||
JSON.stringify({ version: 1, mode: 'temporary', user: { id: 'bad', phone: '', name: '' } }),
|
||||
]) {
|
||||
sessionStorage.setItem('cadworld-management-session', payload)
|
||||
expect(readAuthSession()).toBeNull()
|
||||
}
|
||||
})
|
||||
|
||||
@@ -1,15 +1,56 @@
|
||||
import { expect, it } from 'vitest'
|
||||
import { afterEach, expect, it, vi } from 'vitest'
|
||||
import { authGateway, safeReturnPath } from '@/application/auth'
|
||||
it('retains requested temporary login without calling SMS APIs', async () => {
|
||||
expect(await authGateway.requestCode('123')).toBe('123456')
|
||||
expect(await authGateway.signIn('123', '9')).toEqual({
|
||||
id: 'temporary-123',
|
||||
phone: '123',
|
||||
name: '管理员',
|
||||
|
||||
afterEach(() => vi.unstubAllGlobals())
|
||||
|
||||
it('requests a CAPTCHA without Authorization and normalizes the login email', async () => {
|
||||
const fetcher = vi.fn<typeof fetch>(async (input, options) => {
|
||||
if (String(input).endsWith('/captcha'))
|
||||
return Response.json({
|
||||
code: 'OK',
|
||||
data: { captchaCode: 'challenge', image: 'data:image/png;base64,x', expiresIn: 120 },
|
||||
})
|
||||
expect(new Headers(options?.headers).get('Authorization')).toBeNull()
|
||||
expect(JSON.parse(options?.body as string)).toEqual({
|
||||
email: 'admin@example.com',
|
||||
captchaCode: 'challenge',
|
||||
captchaAnswer: 'ABCDE',
|
||||
})
|
||||
return Response.json({
|
||||
code: 'OK',
|
||||
data: {
|
||||
token: 'token-1',
|
||||
tokenType: 'Bearer',
|
||||
expiresIn: 86400,
|
||||
user: { userCode: 'A', nickname: '管理员', email: 'admin@example.com' },
|
||||
},
|
||||
})
|
||||
})
|
||||
await expect(authGateway.signIn(' ', '1')).rejects.toThrow('手机号')
|
||||
await expect(authGateway.signIn('123', ' ')).rejects.toThrow('验证码')
|
||||
vi.stubGlobal('fetch', fetcher)
|
||||
const challenge = await authGateway.requestCaptcha()
|
||||
const session = await authGateway.signIn(' ADMIN@EXAMPLE.COM ', challenge.captchaCode, ' ABCDE ')
|
||||
expect(session.user.nickname).toBe('管理员')
|
||||
expect(session.token).toBe('token-1')
|
||||
expect(session.expiresAt).toBeGreaterThan(Date.now())
|
||||
})
|
||||
|
||||
it('preserves admin authentication error codes', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn<typeof fetch>(async () =>
|
||||
Response.json(
|
||||
{ code: 'ADMIN_ACCESS_DENIED', message: '无权限', requestId: 'req-1' },
|
||||
{ status: 403 },
|
||||
),
|
||||
),
|
||||
)
|
||||
await expect(authGateway.requestCaptcha()).rejects.toMatchObject({
|
||||
code: 'ADMIN_ACCESS_DENIED',
|
||||
status: 403,
|
||||
requestId: 'req-1',
|
||||
})
|
||||
})
|
||||
|
||||
it('returns only to current internal routes', () => {
|
||||
expect(safeReturnPath('/users')).toBe('/users')
|
||||
expect(safeReturnPath('/assembly-test')).toBe('/assembly-test')
|
||||
|
||||
@@ -91,7 +91,7 @@ describe('BOM persistence contract', () => {
|
||||
const form = componentForm({
|
||||
...emptyPartInformation(),
|
||||
name: '躯干',
|
||||
category: 'torso_0',
|
||||
category: 'TORSO_0',
|
||||
bomList: [item],
|
||||
urdfInfo: {},
|
||||
})
|
||||
|
||||
@@ -25,12 +25,12 @@ describe('new component form contract', () => {
|
||||
it('submits the latest flat fields and both JSON containers without obsolete metadata', () => {
|
||||
expect(componentForm({ ...info(), weightKg: '0' })).toEqual({
|
||||
componentName: '安装板',
|
||||
rotationAxis: null,
|
||||
rotationAxis: 'Z',
|
||||
category: '自由分类',
|
||||
description: '',
|
||||
material: '',
|
||||
massKg: 0,
|
||||
degreesOfFreedom: null,
|
||||
degreesOfFreedom: 1,
|
||||
functionDescription: '',
|
||||
shape: '',
|
||||
size: '',
|
||||
@@ -63,7 +63,7 @@ describe('new component form contract', () => {
|
||||
torque: '20.123456',
|
||||
weightKg: '1.25',
|
||||
description: '自由填写的描述',
|
||||
basicFields: [{ name: 'partType', value: 'head' }],
|
||||
basicFields: [{ name: 'partType', value: 'HEAD' }],
|
||||
parameterFields: [{ name: '旧参数', value: '原值' }],
|
||||
})
|
||||
expect(form).toMatchObject({
|
||||
@@ -116,7 +116,7 @@ describe('new component form contract', () => {
|
||||
componentName: '',
|
||||
category: '',
|
||||
massKg: null,
|
||||
degreesOfFreedom: null,
|
||||
degreesOfFreedom: 1,
|
||||
torqueNm: null,
|
||||
urdfInfo: null,
|
||||
bomList: [],
|
||||
@@ -222,11 +222,13 @@ describe('paired source rules', () => {
|
||||
|
||||
it('rotationAxis saves at the top level, restores on edit and supports clearing without requiring URDF', () => {
|
||||
const form = componentForm({ ...emptyPartInformation(), rotationAxis: ' Z ' })
|
||||
expect(form.rotationAxis).toBe('z')
|
||||
expect(form.rotationAxis).toBe('Z')
|
||||
expect(form.urdfInfo).toBeNull()
|
||||
const restored = partInformation(form as ComponentDetail)
|
||||
expect(restored.rotationAxis).toBe('z')
|
||||
expect(restored.rotationAxis).toBe('Z')
|
||||
expect(componentForm({ ...restored, rotationAxis: '' }).rotationAxis).toBeNull()
|
||||
expect(componentForm({ ...restored, rotationAxis: '-X' }).rotationAxis).toBe('-x')
|
||||
expect(componentForm({ ...restored, rotationAxis: '-X' }).rotationAxis).toBe('-X')
|
||||
for (const axis of ['x', 'y', 'z', '-x', '-y', '-z'])
|
||||
expect(componentForm({ ...restored, rotationAxis: axis }).rotationAxis).toBe(axis.toUpperCase())
|
||||
expect(() => componentForm({ ...restored, rotationAxis: 'xyz' })).toThrow('旋转轴')
|
||||
})
|
||||
|
||||
@@ -29,6 +29,7 @@ const detail = (): ComponentDetail => ({
|
||||
...componentForm(emptyPartInformation()),
|
||||
id: 123,
|
||||
componentCode: 'CW-123',
|
||||
status: 'ENABLED',
|
||||
stepObjectKey: 'step/part.step',
|
||||
stepUrl: '/admin-api/component-assets/step/part.step',
|
||||
version: 1,
|
||||
@@ -154,12 +155,12 @@ it('submits the new STEP-only filename category without requiring URDF or option
|
||||
expect(view.host.textContent).toContain('足 · 左,由模型文件名自动识别')
|
||||
await submit(view.host)
|
||||
expect(save.mock.calls[0][0]).toMatchObject({
|
||||
category: 'leg_l',
|
||||
category: 'LEG_L',
|
||||
componentName: '',
|
||||
urdfInfo: null,
|
||||
basicFields: [
|
||||
{ name: 'partType', value: 'leg' },
|
||||
{ name: 'partSide', value: 'l' },
|
||||
{ name: 'partType', value: 'LEG' },
|
||||
{ name: 'partSide', value: 'L' },
|
||||
],
|
||||
})
|
||||
} finally {
|
||||
@@ -205,7 +206,7 @@ it('reports a backend that drops rotationAxis instead of falsely claiming the ax
|
||||
select.dispatchEvent(new Event('change', { bubbles: true }))
|
||||
})
|
||||
await submit(view.host)
|
||||
expect(save.mock.calls[0][0].rotationAxis).toBe('z')
|
||||
expect(save.mock.calls[0][0].rotationAxis).toBe('Z')
|
||||
expect(view.host.textContent).toContain('后端未返回一致的 旋转轴(rotationAxis)')
|
||||
expect(view.host.querySelector<HTMLSelectElement>('select[aria-label="旋转轴"]')!.value).toBe(
|
||||
'z',
|
||||
@@ -214,3 +215,23 @@ it('reports a backend that drops rotationAxis instead of falsely claiming the ax
|
||||
await view.close()
|
||||
}
|
||||
})
|
||||
|
||||
it('submits uppercase Z and accepts the same uppercase axis returned by the backend', async () => {
|
||||
const existing = { ...detail(), rotationAxis: 'Z' as const }
|
||||
vi.spyOn(componentGateway, 'detail').mockResolvedValue(existing)
|
||||
vi.spyOn(componentGateway, 'step').mockResolvedValue(step())
|
||||
vi.spyOn(ComponentUploadSession.prototype, 'upload').mockResolvedValue({})
|
||||
const save = vi.spyOn(componentGateway, 'save').mockResolvedValue(existing)
|
||||
const view = await renderEditor('/components/123')
|
||||
try {
|
||||
expect(view.host.querySelector<HTMLSelectElement>('select[aria-label="旋转轴"]')!.value).toBe(
|
||||
'z',
|
||||
)
|
||||
await submit(view.host)
|
||||
expect(save.mock.calls[0][0].rotationAxis).toBe('Z')
|
||||
expect(view.host.textContent).toContain('组件已保存')
|
||||
expect(view.host.textContent).not.toContain('后端未返回一致的')
|
||||
} finally {
|
||||
await view.close()
|
||||
}
|
||||
})
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import { expect, it } from 'vitest'
|
||||
import * as THREE from 'three'
|
||||
import {
|
||||
createInterfaceDirectionMarker,
|
||||
disposeInterfaceDirectionMarker,
|
||||
} from '@/infrastructure/interface-direction'
|
||||
|
||||
it('uses the interface Link world transform for marker position and axes', () => {
|
||||
const model = new THREE.Group()
|
||||
const parent = new THREE.Group()
|
||||
parent.position.set(1, 2, 3)
|
||||
parent.rotation.z = Math.PI / 2
|
||||
const point = new THREE.Object3D()
|
||||
point.position.set(2, 0, 0)
|
||||
parent.add(point)
|
||||
model.add(parent)
|
||||
model.updateMatrixWorld(true)
|
||||
const before = model.toJSON()
|
||||
const marker = createInterfaceDirectionMarker(model, point)
|
||||
expect(marker).not.toBeNull()
|
||||
expect(marker!.getObjectByName('+Y 朝向参考')).toBeUndefined()
|
||||
expect(marker!.position.x).toBeCloseTo(1)
|
||||
expect(marker!.position.y).toBeCloseTo(4)
|
||||
expect(marker!.position.z).toBeCloseTo(3)
|
||||
const z = new THREE.Vector3(0, 0, 1).applyQuaternion(marker!.quaternion)
|
||||
const x = new THREE.Vector3(1, 0, 0).applyQuaternion(marker!.quaternion)
|
||||
expect(z.toArray()).toEqual([0, 0, 1])
|
||||
expect(x.x).toBeCloseTo(0)
|
||||
expect(x.y).toBeCloseTo(1)
|
||||
expect(model.toJSON()).toEqual(before)
|
||||
disposeInterfaceDirectionMarker(marker!)
|
||||
expect(marker!.children).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('shows the Y axis only when diagnostic display is enabled', () => {
|
||||
const model = new THREE.Group()
|
||||
const point = new THREE.Object3D()
|
||||
model.add(point)
|
||||
|
||||
const marker = createInterfaceDirectionMarker(model, point, 1, { showYAxis: true })
|
||||
expect(marker?.getObjectByName('+Y 朝向参考')).toBeDefined()
|
||||
disposeInterfaceDirectionMarker(marker!)
|
||||
})
|
||||
|
||||
it('rejects an interface point from another model', () => {
|
||||
const model = new THREE.Group()
|
||||
const other = new THREE.Object3D()
|
||||
expect(createInterfaceDirectionMarker(model, other)).toBeNull()
|
||||
})
|
||||
@@ -4,6 +4,8 @@ import {
|
||||
PART_CATEGORY_OPTIONS,
|
||||
partIdentityFromSources,
|
||||
interfaceIdentityFromLink,
|
||||
interfaceLinkInfoFromName,
|
||||
canonicalInterfaceLinkName,
|
||||
partIdentityFromFileName,
|
||||
withPartIdentity,
|
||||
applyPartIdentity,
|
||||
@@ -11,11 +13,11 @@ import {
|
||||
import { readUrdfFrames } from '@/domain/urdf-frames'
|
||||
import { componentForm, emptyPartInformation } from '@/domain/component-catalog'
|
||||
|
||||
it('uses the same twelve categories for STEP, STP, URDF and declared English links', () => {
|
||||
it('uses the same sixteen categories for STEP, STP, URDF and declared English links', () => {
|
||||
const keys = new Set<string>()
|
||||
for (const entry of PART_TYPES) {
|
||||
for (const side of entry.bilateral ? ['L', 'R'] : ['0']) {
|
||||
const key = `${entry.type}_${side.toLowerCase()}`
|
||||
for (const side of entry.bilateral ? ['L', 'R', '0'] : ['0']) {
|
||||
const key = `${entry.type}_${side}`
|
||||
for (const type of [entry.label, entry.type.toUpperCase()]) {
|
||||
for (const extension of ['URDF', 'step', 'stp']) {
|
||||
expect(partIdentityFromFileName(`${type}_${side}_机械-型号_任意.${extension}`)?.key).toBe(
|
||||
@@ -27,45 +29,50 @@ it('uses the same twelve categories for STEP, STP, URDF and declared English lin
|
||||
keys.add(key)
|
||||
}
|
||||
}
|
||||
expect(keys.size).toBe(12)
|
||||
expect(keys.size).toBe(16)
|
||||
expect(PART_CATEGORY_OPTIONS.map((item) => item.value).sort()).toEqual([...keys].sort())
|
||||
expect(partIdentityFromFileName('头_0_兔头零自由度.urdf')?.key).toBe('head_0')
|
||||
expect(partIdentityFromFileName('头_0_兔头零自由度.urdf')?.key).toBe('HEAD_0')
|
||||
expect(interfaceIdentityFromLink(' LINK_HEAD_0 ')?.key).toBe('HEAD_0')
|
||||
expect(interfaceIdentityFromLink(' LINK_HEAD_0 ')?.key).toBe('HEAD_0')
|
||||
})
|
||||
it('does not guess old or incomplete names, invalid sides, or mesh filenames', () => {
|
||||
for (const name of [
|
||||
'head.urdf',
|
||||
'head_0.urdf',
|
||||
'head_0_.urdf',
|
||||
'head_0_ .urdf',
|
||||
'HEAD_0.urdf',
|
||||
'HEAD_0_.urdf',
|
||||
'HEAD_0_ .urdf',
|
||||
'arm_0_X.urdf',
|
||||
'head_L_X.urdf',
|
||||
'head_左_X.urdf',
|
||||
'型号_head_0.urdf',
|
||||
'head_0_X.stl',
|
||||
'型号_HEAD_0.urdf',
|
||||
'HEAD_0_X.stl',
|
||||
'头-0-兔头.urdf',
|
||||
'pedal_L_X.urdf',
|
||||
])
|
||||
expect(partIdentityFromFileName(name)).toBeNull()
|
||||
expect(partIdentityFromFileName('足_R_head_L.urdf')?.key).toBe('leg_r')
|
||||
expect(partIdentityFromFileName('脚_R_head_L.urdf')?.key).toBe('foot_r')
|
||||
expect(partIdentityFromFileName('足_R_head_L.urdf')?.key).toBe('LEG_R')
|
||||
expect(partIdentityFromFileName('足_0_虫足基础.urdf')?.key).toBe('LEG_0')
|
||||
expect(partIdentityFromFileName('脚_0_虫脚基础.urdf')?.key).toBe('FOOT_0')
|
||||
expect(partIdentityFromFileName('脚_R_head_L.urdf')?.key).toBe('FOOT_R')
|
||||
for (const name of [
|
||||
'BASE',
|
||||
'J1',
|
||||
'LINK1.1',
|
||||
'LINK_ARM',
|
||||
'LINK_HEAD',
|
||||
'Link-head',
|
||||
'LINK_HEAD_R',
|
||||
'LINK_ARM_0',
|
||||
'Link-head',
|
||||
'LINK_足_R',
|
||||
'LINK_PEDAL_L',
|
||||
'LINK_ARM_R_extra',
|
||||
])
|
||||
expect(interfaceIdentityFromLink(name)).toBeNull()
|
||||
expect(interfaceIdentityFromLink('LINK_LEG_0')?.key).toBe('LEG_0')
|
||||
expect(interfaceIdentityFromLink('LINK_FOOT_0')?.key).toBe('FOOT_0')
|
||||
})
|
||||
it('classifies STEP-only uploads and rejects conflicting source identities', () => {
|
||||
expect(partIdentityFromSources(undefined, '足_L_型号.step')?.key).toBe('leg_l')
|
||||
expect(partIdentityFromSources('头_0_兔头.urdf', '头_0_兔头精确模型.stp')?.key).toBe('head_0')
|
||||
expect(partIdentityFromSources(undefined, '足_L_型号.step')?.key).toBe('LEG_L')
|
||||
expect(partIdentityFromSources('头_0_兔头.urdf', '头_0_兔头精确模型.stp')?.key).toBe('HEAD_0')
|
||||
expect(() => partIdentityFromSources('足_L_型号.urdf', '脚_L_型号.step')).toThrow('不一致')
|
||||
expect(() => partIdentityFromSources('臂_L_型号.urdf', '臂_R_型号.step')).toThrow('不一致')
|
||||
})
|
||||
@@ -73,16 +80,31 @@ it('reads interface names without changing joint origins or inferring a pair', (
|
||||
const xml =
|
||||
'<robot><link name="BASE"/><link name="LINK_HEAD_0"/><joint name="J2" type="fixed"><parent link="BASE"/><child link="LINK_HEAD_0"/><origin xyz="0 0.0434269852498788 0" rpy="-1.5707963267949 -1.5707963267949 0"/></joint></robot>'
|
||||
const before = readUrdfFrames(xml)
|
||||
expect(interfaceIdentityFromLink(before.frames[0].child)?.key).toBe('head_0')
|
||||
expect(interfaceIdentityFromLink(before.frames[0].child)?.key).toBe('HEAD_0')
|
||||
expect(readUrdfFrames(xml)).toEqual(before)
|
||||
expect(before.frames[0].xyz?.[1]).toBe(0.0434269852498788)
|
||||
})
|
||||
|
||||
it('accepts only uppercase declared links and ignores numeric duplicate ids for classification', () => {
|
||||
expect(interfaceIdentityFromLink('LINK#1_LEG_L')?.key).toBe('LEG_L')
|
||||
expect(interfaceIdentityFromLink('LINK#233_LEG_L')?.key).toBe('LEG_L')
|
||||
expect(interfaceLinkInfoFromName('LINK#233_LEG_L')).toMatchObject({
|
||||
rawName: 'LINK#233_LEG_L',
|
||||
canonicalName: 'LINK_LEG_L',
|
||||
instanceId: '233',
|
||||
key: 'LEG_L',
|
||||
})
|
||||
expect(canonicalInterfaceLinkName('LINK#233_LEG_L')).toBe('LINK_LEG_L')
|
||||
expect(interfaceIdentityFromLink(' LINK#1_LEG_L ')?.key).toBe('LEG_L')
|
||||
for (const name of ['LINK_head_0', 'link#1_LEG_L', 'LINK#A_LEG_L', 'LINK#0_LEG_L', 'LINK_LEG_l'])
|
||||
expect(interfaceIdentityFromLink(name)).toBeNull()
|
||||
})
|
||||
it('persists recognized type and side through existing basicFields and replaces stale identity', () => {
|
||||
const part = partIdentityFromFileName('手_R_型号.urdf')!
|
||||
const original = [
|
||||
{ name: '供应商型号', value: 'A' },
|
||||
{ name: 'partType', value: 'arm' },
|
||||
{ name: 'partSide', value: 'l' },
|
||||
{ name: 'partType', value: 'ARM' },
|
||||
{ name: 'partSide', value: 'L' },
|
||||
]
|
||||
const updated = withPartIdentity(original, part)
|
||||
const form = componentForm({
|
||||
@@ -94,10 +116,10 @@ it('persists recognized type and side through existing basicFields and replaces
|
||||
})
|
||||
expect(form.basicFields).toEqual([
|
||||
{ name: '供应商型号', value: 'A' },
|
||||
{ name: 'partType', value: 'hand' },
|
||||
{ name: 'partSide', value: 'r' },
|
||||
{ name: 'partType', value: 'HAND' },
|
||||
{ name: 'partSide', value: 'R' },
|
||||
])
|
||||
expect(original[1].value).toBe('arm')
|
||||
expect(original[1].value).toBe('ARM')
|
||||
expect(withPartIdentity(original, null)).toEqual([original[0]])
|
||||
})
|
||||
|
||||
@@ -105,13 +127,13 @@ it('submits the file-derived category instead of a manually entered or stale cla
|
||||
const info = { ...emptyPartInformation(), urdfInfo: {}, name: '躯干型号', category: '结构件' }
|
||||
const torso = partIdentityFromFileName('躯干_0_型号.urdf')!
|
||||
const form = componentForm(applyPartIdentity(info, torso))
|
||||
expect(form.category).toBe('torso_0')
|
||||
expect(form.category).toBe('TORSO_0')
|
||||
expect(form.basicFields).toEqual([
|
||||
{ name: 'partType', value: 'torso' },
|
||||
{ name: 'partType', value: 'TORSO' },
|
||||
{ name: 'partSide', value: '0' },
|
||||
])
|
||||
const arm = partIdentityFromFileName('arm_R_另一型号.urdf')!
|
||||
expect(componentForm(applyPartIdentity(info, arm)).category).toBe('arm_r')
|
||||
const arm = partIdentityFromFileName('ARM_R_另一型号.urdf')!
|
||||
expect(componentForm(applyPartIdentity(info, arm)).category).toBe('ARM_R')
|
||||
expect(info.category).toBe('结构件')
|
||||
expect(applyPartIdentity(info, null)).toBe(info)
|
||||
})
|
||||
|
||||
@@ -3,3 +3,21 @@ import { File, Blob } from 'node:buffer'
|
||||
import { TextEncoder, TextDecoder } from 'node:util'
|
||||
Object.defineProperty(globalThis, 'crypto', { value: webcrypto, configurable: true })
|
||||
Object.assign(globalThis, { File, Blob, TextEncoder, TextDecoder })
|
||||
|
||||
if (!window.matchMedia) {
|
||||
Object.defineProperty(window, 'matchMedia', {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: (query: string): MediaQueryList =>
|
||||
({
|
||||
matches: false,
|
||||
media: query,
|
||||
onchange: null,
|
||||
addEventListener: () => undefined,
|
||||
removeEventListener: () => undefined,
|
||||
addListener: () => undefined,
|
||||
removeListener: () => undefined,
|
||||
dispatchEvent: () => false,
|
||||
}) as MediaQueryList,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -18,6 +18,7 @@ it('admin preview and frontend assembly read identical internal transforms and o
|
||||
const files = [new File([torso], 'torso.urdf'), new File([head], 'head.urdf')]
|
||||
const bytesBefore = await Promise.all(files.map((file) => file.text()))
|
||||
const source = await Promise.all(files.map((file) => loadUrdfFiles([file])))
|
||||
const infos = bytesBefore.map((bytes) => urdfInfoFromFrames(readUrdfFrames(bytes)))
|
||||
const before = source.map((loaded) =>
|
||||
Object.fromEntries(
|
||||
Object.entries(loaded.root.links).map(([name, link]) => [name, link.matrixWorld.clone()]),
|
||||
@@ -34,13 +35,16 @@ it('admin preview and frontend assembly read identical internal transforms and o
|
||||
component: {
|
||||
componentCode: `CW-${i}`,
|
||||
componentName: file.name,
|
||||
category: i === 0 ? 'torso_0' : 'head_0',
|
||||
category: i === 0 ? 'TORSO_0' : 'HEAD_0',
|
||||
rotationAxis: i === 1 ? 'z' : null,
|
||||
version: 1,
|
||||
// Stale cached metadata must never override canonical names in the real file.
|
||||
urdfInfo: {
|
||||
...urdfInfoFromFrames(readUrdfFrames(bytesBefore[i])),
|
||||
frames: [{ child: 'LINK_HEAD_0', interfaceType: i === 0 ? 'foot_l' : 'leg_r' }],
|
||||
...infos[i],
|
||||
frames: (infos[i] as { frames: Record<string, unknown>[] }).frames.map((frame) => ({
|
||||
...frame,
|
||||
interfaceType: i === 0 ? 'FOOT_L' : 'LEG_R',
|
||||
})),
|
||||
},
|
||||
},
|
||||
urdfMainPath: file.name,
|
||||
@@ -56,10 +60,21 @@ it('admin preview and frontend assembly read identical internal transforms and o
|
||||
const match = {
|
||||
components,
|
||||
assembly: {
|
||||
status: 'blocked',
|
||||
status: 'ready',
|
||||
rootInstanceId: 'torso',
|
||||
matrixLayout: 'column-major',
|
||||
connections: [],
|
||||
connections: [
|
||||
{
|
||||
parentInstanceId: 'torso',
|
||||
parentFrame: 'head_joint',
|
||||
parentLink: 'LINK_HEAD_0',
|
||||
childInstanceId: 'head',
|
||||
childFrame: 'head_mount',
|
||||
childRootLink: 'base_link',
|
||||
interfaceChild: 'LINK_HEAD_0',
|
||||
parentFrameIndex: 1,
|
||||
childFrameIndex: 0,
|
||||
},
|
||||
],
|
||||
issues: [],
|
||||
},
|
||||
} as unknown as DemandMatch
|
||||
@@ -131,7 +146,7 @@ it('keeps every returned component visible even with empty root geometry and una
|
||||
component: {
|
||||
componentCode: name,
|
||||
componentName: name,
|
||||
category: i ? 'head_0' : 'torso_0',
|
||||
category: i ? 'HEAD_0' : 'TORSO_0',
|
||||
version: 1,
|
||||
urdfInfo: { rootLink: 'stale-cached-root' },
|
||||
},
|
||||
@@ -153,7 +168,6 @@ it('keeps every returned component visible even with empty root geometry and una
|
||||
rootInstanceId: 'anchor',
|
||||
connections: [],
|
||||
issues: [],
|
||||
matrixLayout: 'column-major',
|
||||
},
|
||||
} as unknown as DemandMatch,
|
||||
new AbortController().signal,
|
||||
@@ -164,7 +178,7 @@ it('keeps every returned component visible even with empty root geometry and una
|
||||
expect(child.visible).toBe(true)
|
||||
expect(child.matrixWorld.elements.every(Number.isFinite)).toBe(true)
|
||||
}
|
||||
expect(loaded.warnings.join(' ')).toContain('已单独展示')
|
||||
expect(loaded.warnings).toEqual([])
|
||||
})
|
||||
|
||||
it('a failed extra mesh does not discard the other geometry of a returned head', async () => {
|
||||
@@ -179,7 +193,7 @@ it('a failed extra mesh does not discard the other geometry of a returned head',
|
||||
component: {
|
||||
componentCode: 'head',
|
||||
componentName: '头部',
|
||||
category: 'head_0',
|
||||
category: 'HEAD_0',
|
||||
version: 1,
|
||||
urdfInfo: {},
|
||||
},
|
||||
@@ -201,7 +215,6 @@ it('a failed extra mesh does not discard the other geometry of a returned head',
|
||||
rootInstanceId: 'head',
|
||||
connections: [],
|
||||
issues: [],
|
||||
matrixLayout: 'column-major',
|
||||
},
|
||||
} as unknown as DemandMatch,
|
||||
new AbortController().signal,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { expect, it } from 'vitest'
|
||||
import { readUrdfFrames, urdfInfoFromFrames } from '@/domain/urdf-frames'
|
||||
import { isInterfaceFrame, readUrdfFrames, urdfInfoFromFrames } from '@/domain/urdf-frames'
|
||||
import {
|
||||
componentForm,
|
||||
emptyPartInformation,
|
||||
@@ -64,6 +64,43 @@ it('keeps omitted coordinates undefined and retains source precision', () => {
|
||||
).frames[0].xyz?.[0],
|
||||
).toBe(0.000000000123)
|
||||
})
|
||||
|
||||
it('keeps a standard root link available when an URDF has no joints', () => {
|
||||
const data = readUrdfFrames('<robot><link name="LINK_HEAD_0 "/></robot>')
|
||||
expect(data.rootLink).toBe('LINK_HEAD_0 ')
|
||||
expect(data.frames).toMatchObject([
|
||||
{
|
||||
name: '__root_interface__',
|
||||
kind: 'interface',
|
||||
parent: null,
|
||||
child: 'LINK_HEAD_0 ',
|
||||
interfaceName: 'LINK_HEAD_0',
|
||||
interfaceType: 'HEAD_0',
|
||||
isRoot: true,
|
||||
synthetic: true,
|
||||
xyz: [0, 0, 0],
|
||||
rpy: [0, 0, 0],
|
||||
},
|
||||
])
|
||||
})
|
||||
it('recognizes an undifferentiated leg root link as a synthetic interface', () => {
|
||||
const data = readUrdfFrames(
|
||||
'<robot><link name="LINK_LEG_0"/><link name="LINK_FOOT_0"/><joint name="J" type="fixed"><parent link="LINK_LEG_0"/><child link="LINK_FOOT_0"/></joint></robot>',
|
||||
)
|
||||
expect(data.rootLink).toBe('LINK_LEG_0')
|
||||
expect(data.frames.at(-1)).toMatchObject({
|
||||
name: '__root_interface__',
|
||||
child: 'LINK_LEG_0',
|
||||
interfaceName: 'LINK_LEG_0',
|
||||
interfaceType: 'LEG_0',
|
||||
isRoot: true,
|
||||
synthetic: true,
|
||||
})
|
||||
const serialized = urdfInfoFromFrames(data) as { frames: Array<Record<string, unknown>> }
|
||||
expect(serialized.frames).toContainEqual(
|
||||
expect.objectContaining({ child: 'LINK_FOOT_0', interfaceType: 'FOOT_0' }),
|
||||
)
|
||||
})
|
||||
it('rejects malformed coordinates and disconnected frames instead of showing invented zeros', () => {
|
||||
expect(() =>
|
||||
readUrdfFrames(
|
||||
@@ -84,6 +121,15 @@ it('does not supply missing coordinate attributes or select a mounting relations
|
||||
expect(data.frames[0]).not.toHaveProperty('role')
|
||||
})
|
||||
|
||||
it('filters display interfaces without removing internal joints from the raw frames', () => {
|
||||
const data = readUrdfFrames(
|
||||
'<robot><link name="base"/><link name="LINK_ARM_0"/><link name="elbow"/><joint name="arm_mount" type="fixed"><parent link="base"/><child link="LINK_ARM_0"/></joint><joint name="elbow_joint" type="revolute"><parent link="LINK_ARM_0"/><child link="elbow"/></joint></robot>',
|
||||
)
|
||||
expect(data.frames.map((frame) => frame.name)).toEqual(['arm_mount', 'elbow_joint'])
|
||||
expect(data.frames.filter(isInterfaceFrame).map((frame) => frame.name)).toEqual(['arm_mount'])
|
||||
expect(data.frames.find((frame) => frame.name === 'elbow_joint')).toBeDefined()
|
||||
})
|
||||
|
||||
it('saves named raw frames in the required urdfInfo on POST and on form-only PUT', async () => {
|
||||
const xml =
|
||||
'<robot name="原文件"><link name="BASE"/><link name="LINK_HEAD_0"/><joint name="J2" type="fixed"><parent link="BASE"/><child link="LINK_HEAD_0"/><origin xyz="0 0.0434269852498788 0" rpy="-1.5707963267949 -1.5707963267949 0"/><axis xyz="0 0 0"/></joint></robot>'
|
||||
@@ -95,7 +141,8 @@ it('saves named raw frames in the required urdfInfo on POST and on form-only PUT
|
||||
{
|
||||
name: 'J2',
|
||||
child: 'LINK_HEAD_0',
|
||||
interfaceType: 'head_0',
|
||||
interfaceType: 'HEAD_0',
|
||||
interfaceName: 'LINK_HEAD_0',
|
||||
xyz: [0, 0.0434269852498788, 0],
|
||||
limits: {},
|
||||
},
|
||||
@@ -105,7 +152,7 @@ it('saves named raw frames in the required urdfInfo on POST and on form-only PUT
|
||||
const form = componentForm({
|
||||
...emptyPartInformation(),
|
||||
name: '头',
|
||||
category: 'head_0',
|
||||
category: 'HEAD_0',
|
||||
urdfInfo,
|
||||
})
|
||||
const fetcher = vi.fn<typeof fetch>(async () =>
|
||||
@@ -136,6 +183,38 @@ it('saves named raw frames in the required urdfInfo on POST and on form-only PUT
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps duplicate Link ids in raw frames but canonicalizes submitted URDF metadata', () => {
|
||||
const data = readUrdfFrames(
|
||||
'<robot><link name="LINK#2_TORSO_0"/><link name="LINK#4_LEG_L"/><joint name="J" type="fixed"><parent link="LINK#2_TORSO_0"/><child link="LINK#4_LEG_L"/></joint></robot>',
|
||||
)
|
||||
expect(data.rootLink).toBe('LINK#2_TORSO_0')
|
||||
expect(data.frames.find((frame) => frame.name === 'J')).toMatchObject({
|
||||
parent: 'LINK#2_TORSO_0',
|
||||
child: 'LINK#4_LEG_L',
|
||||
})
|
||||
const submitted = urdfInfoFromFrames(data) as {
|
||||
rootLink: string
|
||||
frames: Array<Record<string, unknown>>
|
||||
}
|
||||
expect(submitted.rootLink).toBe('LINK_TORSO_0')
|
||||
expect(submitted.frames.find((frame) => frame.name === 'J')).toMatchObject({
|
||||
parent: 'LINK_TORSO_0',
|
||||
child: 'LINK_LEG_L',
|
||||
interfaceType: 'LEG_L',
|
||||
interfaceName: 'LINK_LEG_L',
|
||||
})
|
||||
})
|
||||
|
||||
it('does not rewrite ordinary Link names or joint names in submitted metadata', () => {
|
||||
const data = readUrdfFrames(
|
||||
'<robot><link name="BASK"/><link name="LINK#3_LEG_L"/><joint name="J#3" type="fixed"><parent link="BASK"/><child link="LINK#3_LEG_L"/></joint></robot>',
|
||||
)
|
||||
expect(urdfInfoFromFrames(data)).toMatchObject({
|
||||
rootLink: 'BASK',
|
||||
frames: [{ name: 'J#3', parent: 'BASK', child: 'LINK_LEG_L' }],
|
||||
})
|
||||
})
|
||||
|
||||
it('serializes absent attributes without inventing zeros and rejects missing round-trip JSON', () => {
|
||||
const info = urdfInfoFromFrames(
|
||||
readUrdfFrames(
|
||||
|
||||
@@ -29,7 +29,7 @@ export default defineConfig({
|
||||
resolve: { alias: { '@': fileURLToPath(new URL('./src', import.meta.url)) } },
|
||||
server: {
|
||||
host: '0.0.0.0',
|
||||
port: 8091,
|
||||
port: 8092,
|
||||
strictPort: true,
|
||||
proxy,
|
||||
},
|
||||
|
||||
@@ -8,13 +8,13 @@ React + TypeScript + Vite 管理后台,包含组件库、STEP/URDF 上传与
|
||||
|
||||
```sh
|
||||
npm ci
|
||||
npm run dev -- --port 8092
|
||||
npm run dev
|
||||
```
|
||||
|
||||
访问 `http://127.0.0.1:8092/`。默认通过本地代理请求开发 API。覆盖后端地址时,在终端设置 `ADMIN_API_TARGET` 后启动,例如:
|
||||
|
||||
```sh
|
||||
ADMIN_API_TARGET=http://127.0.0.1:8992 npm run dev -- --port 8092
|
||||
ADMIN_API_TARGET=http://127.0.0.1:8992 npm run dev
|
||||
```
|
||||
|
||||
## 验证与打包
|
||||
@@ -47,7 +47,7 @@ location / {
|
||||
- 新增零件仅 STEP/STP 必填;URDF 与其余表单字段选填。已提供的 URDF 文件夹仍须完整且可解析。
|
||||
- 原样读取 URDF 的 link/joint、origin、轴向与限制,不改写文件坐标或自动翻转零件。
|
||||
- 按最新 `LINK_部件_左右` 命名规则识别接口和分类,详见 [命名规范](Management/docs/part-naming.md)。
|
||||
- `rotationAxis` 选填,支持 `x/y/z/-x/-y/-z`,保存到组件顶层字段;未设置为 `null`。前台用其在装配接口上增加活动关节,详见 [接口文档](Management/docs/admin-api.md)。
|
||||
- `rotationAxis` 选填,按大写 `X/Y/Z/-X/-Y/-Z` 提交到组件顶层字段;未设置为 `null`。前台用其在装配接口上增加活动关节,详见 [接口文档](Management/docs/admin-api.md)。
|
||||
- Excel 内容解析为 `bomList` 提交并在编辑页回填,详见 [物料清单约定](Management/docs/bom-contract.md)。
|
||||
|
||||
## 目录
|
||||
|
||||
@@ -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` = '替换为已有用户唯一编码';
|
||||
```
|
||||
Generated
+1336
-1931
File diff suppressed because it is too large
Load Diff
+9
-17
@@ -1,24 +1,16 @@
|
||||
{
|
||||
"name": "cadworld-management-repository",
|
||||
"version": "0.1.0",
|
||||
"name": "cadworld-management-workspace",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"workspaces": [
|
||||
"Management"
|
||||
"Management",
|
||||
"Client"
|
||||
],
|
||||
"scripts": {
|
||||
"dev": "npm run dev --workspace Management --",
|
||||
"build": "npm run build --workspace Management",
|
||||
"test": "npm run test --workspace Management",
|
||||
"check": "npm run check --workspace Management",
|
||||
"preview": "npm run preview --workspace Management --"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.12.0"
|
||||
},
|
||||
"overrides": {
|
||||
"exceljs": {
|
||||
"uuid": "11.1.1"
|
||||
}
|
||||
"dev": "npm run dev --workspace=cadworld-management",
|
||||
"build": "npm run build --workspace=cadworld-management",
|
||||
"test": "npm run test --workspace=cadworld-management",
|
||||
"check": "npm run check --workspace=cadworld-management",
|
||||
"format": "npm run format --workspace=cadworld-management",
|
||||
"format:check": "npm run format:check --workspace=cadworld-management"
|
||||
}
|
||||
}
|
||||
|
||||
+60
-20
@@ -1,15 +1,15 @@
|
||||
export const PART_TYPES = [
|
||||
{ type: "torso", label: "躯干", bilateral: false },
|
||||
{ type: "head", label: "头", bilateral: false },
|
||||
{ type: "waist", label: "腰", bilateral: false },
|
||||
{ type: "arm", label: "臂", bilateral: true },
|
||||
{ type: "hand", label: "手", bilateral: true },
|
||||
{ type: "leg", label: "足", bilateral: true },
|
||||
{ type: "foot", label: "脚", bilateral: true },
|
||||
{ type: "tail", label: "尾", bilateral: false },
|
||||
{ type: "TORSO", label: "躯干", bilateral: false },
|
||||
{ type: "HEAD", label: "头", bilateral: false },
|
||||
{ type: "WAIST", label: "腰", bilateral: false },
|
||||
{ type: "ARM", label: "臂", bilateral: true },
|
||||
{ type: "HAND", label: "手", bilateral: true },
|
||||
{ type: "LEG", label: "足", bilateral: true },
|
||||
{ type: "FOOT", label: "脚", bilateral: true },
|
||||
{ type: "TAIL", label: "尾", bilateral: false },
|
||||
] as const;
|
||||
export type PartType = (typeof PART_TYPES)[number]["type"];
|
||||
export type PartSide = "0" | "l" | "r";
|
||||
export type PartSide = "0" | "L" | "R";
|
||||
export interface PartIdentity {
|
||||
type: PartType;
|
||||
label: string;
|
||||
@@ -17,9 +17,9 @@ export interface PartIdentity {
|
||||
key: string;
|
||||
}
|
||||
export const sideLabel = (side: PartSide) =>
|
||||
({ "0": "不分左右", l: "左", r: "右" })[side];
|
||||
({ "0": "不分左右", L: "左", R: "右" })[side];
|
||||
export const PART_CATEGORY_OPTIONS = PART_TYPES.flatMap((entry) =>
|
||||
(entry.bilateral ? ["l", "r"] : ["0"]).map((side) => ({
|
||||
(entry.bilateral ? (["L", "R", "0"] as const) : (["0"] as const)).map((side) => ({
|
||||
value: `${entry.type}_${side}`,
|
||||
label: `${entry.label} · ${sideLabel(side as PartSide)}`,
|
||||
})),
|
||||
@@ -27,12 +27,14 @@ export const PART_CATEGORY_OPTIONS = PART_TYPES.flatMap((entry) =>
|
||||
|
||||
function identity(typeName: string, side: string): PartIdentity | null {
|
||||
const entry = PART_TYPES.find(
|
||||
(item) => item.type === typeName.toLowerCase() || item.label === typeName,
|
||||
(item) => item.type === typeName || item.label === typeName,
|
||||
);
|
||||
const normalizedSide = side.toLowerCase();
|
||||
const normalizedSide = side;
|
||||
if (
|
||||
!entry ||
|
||||
!(entry.bilateral ? ["l", "r"] : ["0"]).includes(normalizedSide)
|
||||
!(entry.bilateral ? (["L", "R", "0"] as const) : (["0"] as const)).includes(
|
||||
normalizedSide as never,
|
||||
)
|
||||
)
|
||||
return null;
|
||||
return {
|
||||
@@ -47,18 +49,56 @@ function identity(typeName: string, side: string): PartIdentity | null {
|
||||
export function partIdentityFromFileName(
|
||||
fileName: string,
|
||||
): PartIdentity | null {
|
||||
const match = /^([^_]+)_([RL0])_(.+)\.(urdf|step|stp)$/i.exec(fileName);
|
||||
if (!match || !match[3].trim()) return null;
|
||||
const match = /^([^_]+)_([RL0])_(.+)\.([^.]+)$/.exec(fileName);
|
||||
if (!match || !match[3].trim() || !/^(urdf|step|stp)$/i.test(match[4]))
|
||||
return null;
|
||||
return identity(match[1], match[2]);
|
||||
}
|
||||
|
||||
/** Recognize the twelve declared interface names; preserve the original frame name. */
|
||||
export interface InterfaceLinkInfo extends PartIdentity {
|
||||
rawName: string;
|
||||
canonicalName: string;
|
||||
instanceId?: string;
|
||||
}
|
||||
|
||||
/** Remove an optional numeric instance suffix for classification only. */
|
||||
export function canonicalInterfaceLinkName(linkName: string): string | null {
|
||||
const normalized = linkName.trim();
|
||||
const match =
|
||||
/^LINK(?:#([1-9]\d*))?_(TORSO|HEAD|WAIST|ARM|HAND|LEG|FOOT|TAIL)_(L|R|0)$/.exec(
|
||||
normalized,
|
||||
);
|
||||
return match ? `LINK_${match[2]}_${match[3]}` : null;
|
||||
}
|
||||
|
||||
/** Recognize a declared interface and retain the source Link identity. */
|
||||
export function interfaceLinkInfoFromName(
|
||||
linkName: string,
|
||||
): InterfaceLinkInfo | null {
|
||||
const canonicalName = canonicalInterfaceLinkName(linkName);
|
||||
if (!canonicalName) return null;
|
||||
const match = /^LINK_(TORSO|HEAD|WAIST|ARM|HAND|LEG|FOOT|TAIL)_(L|R|0)$/.exec(
|
||||
canonicalName,
|
||||
);
|
||||
const part = match ? identity(match[1], match[2]) : null;
|
||||
if (!part || !match) return null;
|
||||
const instanceId = /^LINK#([1-9]\d*)_/.exec(linkName.trim())?.[1];
|
||||
return {
|
||||
...part,
|
||||
rawName: linkName,
|
||||
canonicalName,
|
||||
...(instanceId ? { instanceId } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/** Recognize the declared interface names without changing the source Link name. */
|
||||
export function interfaceIdentityFromLink(
|
||||
linkName: string,
|
||||
): PartIdentity | null {
|
||||
const match =
|
||||
/^LINK_(TORSO|HEAD|WAIST|ARM|HAND|LEG|FOOT|TAIL)_([RL0])$/i.exec(linkName);
|
||||
return match ? identity(match[1], match[2]) : null;
|
||||
const info = interfaceLinkInfoFromName(linkName);
|
||||
return info
|
||||
? { type: info.type, label: info.label, side: info.side, key: info.key }
|
||||
: null;
|
||||
}
|
||||
|
||||
/** URDF and STEP may have different descriptions, but must identify the same part. */
|
||||
|
||||
Reference in New Issue
Block a user