Comprehensive Optimization Plan for Object Class Management
Version: v1.0 | Date: 2026-05-06 | Status: Pending Confirmation
I. Summary of Current State Diagnosis
1.1 ItemType Definition Analysis (24 XML Files)
| Category | Count | Types | Key Characteristics |
|------|------|------|----------|
| Design Class | 3 | Part, Document, CAD | Versionable, inherited from Change Controlled Item (polymorphic) |
| Change Management | 7 | ECR, ECN, PR, Simple ECO/MCO, Express DCO/ECO | Independent workflows and lifecycles |
| Affected Items | 2 | Affected Item/Relationship | is_dependent=1, dependent on change orders |
| Organization/Party | 3 | Customer, Manufacturer, Vendor | Nearly identical attribute structures |
| Procurement/Supply | 1 | Manufacturer Part | Associated with Manufacturer |
| Product | 1 | Product | Simplest, no version control |
| Dashboard | 5 | Design To Goal, etc. | No data structure, only TOC navigation entries |
| Polymorphic Base Classes | 2 | Change Controlled Item/Relationship | Polymorphic pattern, Morphae inheritance |
Core Design Patterns:
- Polymorphic Inheritance: Part/Document/CAD share the CCI data table, differentiated by the itemtype attribute
- Change Tracking: Affected Item records pre- and post-change states via old/new pairing
- Role-based Layered Permissions: World → All Employees → CM → Component Engineering → Administrators
1.2 Backend API Analysis (aml.js line 2276)
- 48 routes distributed across two export functions (29 main routes + 19 TOC configuration routes)
- Critical Bugs:
- generate-rules uses require('../database1').getDatabase() — module API mismatch
- SCIOT routes incorrectly nested within else block
- aml_properties table structure inconsistent in multiple places (missing default_value, item_type_name, is_required columns)
- No PUT update routes (can only create new, not modify)
- Architectural Issues: 2276-line if-else chain, no modularization, no error handling middleware
1.3 Frontend UI Analysis (app.js)
- Implemented: List display, viewing 9 types of sub-elements, AML edit/convert/save, AI assistant chat
- Missing Features:
- ❌ Create object class form
- ❌ Delete object class
- ❌ Edit object class properties (view only)
- ❌ File import/export (no upload/download components)
- ❌ Batch operations (select/delete/export)
- ❌ Version management
- 6 backend APIs unused by frontend: validate, compare, fix, generate, analyze, graph
1.4 SCSAI Communication Layer Analysis
| Channel | File | Environment | Endpoint | Issue |
|---|---|---|---|---|
| ASPX Direct | SCSAI-connection.js | Node.js | AgentRequestHandler.aspx | Manual regex XML parsing, 80% duplicate code |
| OData | api-utils.js | Node.js | /odata/AML | No error handling, no timeout |
| SOAP | Soap.js + soap_object.js | Browser | InnovatorServer.aspx | SyncPromise non-standard, synchronous UI blocking |
II. Optimizing Architecture Design
2.1 Overall Architecture
┌─────────────────────────────────────────────────────────────────┐
│ 前端 (Vue 3) │
│ ┌──────────────┐ ┌──────────────┐ ┌───────────────────────┐ │
│ │ 对象类列表 │ │ 对象类详情 │ │ AI 助手面板 │ │
│ │ (Search/过滤/ │ │ (属性/方法/ │ │ (Create/Repair/Optimize/Compare) │ │
│ │ 批量操作) │ │ 关系/生命周期)│ │ │ │
│ └──────┬───────┘ └──────┬───────┘ └───────────┬───────────┘ │
│ │ │ │ │
│ ┌──────┴─────────────────┴──────────────────────┴───────────┐ │
│ │ REST API Client (fetch) │ │
│ └──────────────────────────┬────────────────────────────────┘ │
└─────────────────────────────┼───────────────────────────────────┘
│
┌─────────────────────────────┼───────────────────────────────────┐
│ 后端 (Node.js) │
│ ┌──────────────────────────┴────────────────────────────────┐ │
│ │ Express Router (模块化) │ │
│ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────────┐ │ │
│ │ │ itemtype │ │ template │ │ import- │ │ ai- │ │ │
│ │ │ .router │ │ .router │ │ export │ │ assistant │ │ │
│ │ │ (CRUD) │ │ (AML管理)│ │ .router │ │ .router │ │ │
│ │ └────┬─────┘ └────┬─────┘ └────┬─────┘ └──────┬───────┘ │ │
│ │ │ │ │ │ │ │
│ │ ┌────┴────────────┴────────────┴───────────────┴───────┐ │ │
│ │ │ SCSAIClient (统一通信层) │ │ │
│ │ │ - sendAML(aml) → Promise<SCSAIResponse> │ │ │
│ │ │ - applyItem(aml) → Promise<SCSAIResponse> │ │ │
│ │ │ - validateUser(creds) → Promise<UserInfo> │ │ │
│ │ └──────────────────────┬───────────────────────────────┘ │ │
│ └─────────────────────────┼─────────────────────────────────┘ │
│ │ │
│ ┌─────────────────────────┼─────────────────────────────────┐ │
│ │ 数据层 │ │
│ │ ┌──────────┐ ┌──────────────┐ ┌────────────────────┐ │ │
│ │ │ SQLite │ │ ItemType XML │ │ SCSAI Server │ │ │
│ │ │ (本地) │ │ (定义文件) │ │ (PLM 主数据) │ │ │
│ │ └──────────┘ └──────────────┘ └────────────────────┘ │ │
│ └───────────────────────────────────────────────────────────┘ │
└───────────────────────────────────────────────────────────────┘
2.2 统一 SCSAI 通信层 (SCSAIClient)
// server/utils/SCSAI-client.js
class SCSAIClient {
constructor(config) {
this.serverUrl = config.serverUrl; // SCSAI 服务器地址
this.database = config.database; // 数据库名
this.username = config.username; // Username
this.password = config.password; // Password(明文,内部哈希)
this.hashType = 'md5'; // 哈希类型: md5 | sha256
this.timeout = 30000; // 超时 30秒
}
// 核心方法:Send AML 查询
async sendAML(amlString) {
// 1. 构建 SOAP Envelope
// 2. 添加认证头 (AUTHUSER + AUTHPASSWORD MD5)
// 3. POST 到 /server/InnovatorServer.aspx
// 4. 解析 XML 响应为标准 SCSAIResponse
// 5. 统一错误处理(HTTP错误 + SOAP Fault)
}
// ApplyItem:Create/更新/删除 SCSAI 对象
async applyItem(amlString) {
return this.sendAML(amlString);
}
// 验证用户
async validateUser() {
const hashPwd = crypto.createHash('md5').update(this.password).digest('hex');
const aml = `<Item type="User" action="ValidateUser">
<login_name>${this.username}</login_name>
<password>${hashPwd}</password>
<database>${this.database}</database>
</Item>`;
return this.sendAML(aml);
}
// 标准响应格式
// {
// success: boolean,
// items: Array<{ id, type, keyed_name, [propName]: value }>,
// fault: { code, string, message } | null,
// rawXml: string,
// count: number
// }
}
2.3 模块化路由设计
将 aml.js 2276行 if-else 链拆分为 6 个独立路由模块:
server/routes/
├── index.js # 路由注册入口
├── itemtype.router.js # 对象类 CRUD(核心)
├── template.router.js # AML 模板管理
├── import-export.router.js # 导入导出
├── ai-assistant.router.js # AI Create/Repair/Optimize/Compare
├── toc-config.router.js # TOC 配置管理
└── rules-prompts.router.js # 规则和 Prompt 管理
2.4 数据库表结构统一
-- 对象类主表
CREATE TABLE IF NOT EXISTS item_types (
id TEXT PRIMARY KEY,
name TEXT UNIQUE NOT NULL, -- ItemType 名称
label TEXT, -- 显示名称
category TEXT, -- Category: design/change/sourcing/organization/dashboard
source TEXT DEFAULT 'local', -- 数据源: local/SCSAI/sciot
description TEXT,
is_versionable INTEGER DEFAULT 0,
is_polymorphic INTEGER DEFAULT 0,
is_dependent INTEGER DEFAULT 0,
parent_type TEXT, -- 多态父类型
instance_data TEXT, -- SCSAI instance_data 表名
icon TEXT,
color TEXT,
sort_order INTEGER DEFAULT 0,
is_core_business INTEGER DEFAULT 0,
created_at TEXT DEFAULT (datetime('now')),
updated_at TEXT DEFAULT (datetime('now'))
);
-- 对象类属性表
CREATE TABLE IF NOT EXISTS item_type_properties (
id TEXT PRIMARY KEY,
item_type_name TEXT NOT NULL, -- 关联对象类名称
property_name TEXT NOT NULL,
label TEXT,
data_type TEXT DEFAULT 'string', -- string/integer/float/date/boolean/item/list/federated/text/image/decimal
stored_length INTEGER,
is_required INTEGER DEFAULT 0,
is_key INTEGER DEFAULT 0,
is_readonly INTEGER DEFAULT 0,
is_hidden INTEGER DEFAULT 0,
default_value TEXT,
data_source TEXT, -- list 数据源
foreign_type TEXT, -- item 外键指向的类型
sort_order INTEGER DEFAULT 0,
class_path TEXT, -- 分类路径(CAD的Mechanical/Electronic)
grid_events TEXT, -- JSON: Grid 事件配置
UNIQUE(item_type_name, property_name)
);
-- AML 模板表(保留现有功能)
CREATE TABLE IF NOT EXISTS aml_templates (
id TEXT PRIMARY KEY,
item_type_name TEXT NOT NULL,
name TEXT,
aml_content TEXT NOT NULL,
description TEXT,
version INTEGER DEFAULT 1,
is_active INTEGER DEFAULT 1,
created_at TEXT DEFAULT (datetime('now')),
updated_at TEXT DEFAULT (datetime('now'))
);
-- 操作日志表
CREATE TABLE IF NOT EXISTS operation_logs (
id TEXT PRIMARY KEY,
action TEXT NOT NULL, -- create/update/delete/import/export/ai_generate
target_type TEXT, -- 操作目标类型
target_name TEXT, -- 操作目标名称
status TEXT DEFAULT 'success', -- success/error
detail TEXT,
operator TEXT,
created_at TEXT DEFAULT (datetime('now'))
);
三、分阶段实施计划
Phase 0: 修复致命 Bug(预计 2-3 小时)
#### P0-1: Repair generate-rules 路由
- File: server/routes/aml.js Line 1553
- Issue: Module require('../database1').getDatabase() does not exist
- Fix: Change to use unified require('../database') + correct table structure
#### P0-2: Fix if-else nesting error
- File: server/routes/aml.js Line 1649
- Issue: SCIOT route incorrectly nested within else block
- Fix: Change } else { to a standalone if statement
#### P0-3: Fix inconsistent table structure
- File: server/routes/aml.js Lines 44-47 table creation statement
- Issue: aml_properties table missing default_value, item_type_name, is_required columns
- Fix: Unify table structure, add missing columns
#### P0-4: Add PUT update route
- File: server/routes/aml.js
- Issue: No route for updating existing templates
- Fix: Add PUT /api/aml/template/:id route
Phase 1: Unify SCSAI Communication Layer (Estimated 3-4 hours)
#### P1-1: Create SCSAIClient class
- New file: server/utils/SCSAI-client.js
- Merge functionality from SCSAI-connection.js and api-utils.js
- Uniformly use xml2js to parse XML (deprecate handwritten regex)
- Unify error handling (HTTP status codes + SOAP Fault)
- Uniformly add timeout and proxy support
- Extract common HTTP request function (eliminate 80% duplicate code)
#### P1-2: Migrate existing calls
- Replace runAml() calls in aml.js with SCSAIClient.sendAML()
- Replace CRUD calls in SCSAI-connection.js with SCSAIClient.applyItem()
- Keep SCSAI-connection.js and api-utils.js as a compatibility layer (marked deprecated)
#### P1-3: Frontend SOAP optimization
- File: SCSAI/core/Soap.js
- Deprecate SyncPromise, migrate to standard Promise
- Eliminate async: false synchronous blocking
Phase 2: Refactor backend routes (estimated 4-5 hours)
#### P2-1: Create modular routes
- Split aml.js into 6 independent route files
- Use Express Router standard pattern
- Add request validation middleware
- Unify error handling middleware
#### P2-2: Complete CRUD APIs
- POST /api/itemtypes — Create object class (sync to SCSAI)
- PUT /api/itemtypes/:name — Update object class definition
- DELETE /api/itemtypes/:name — Delete object class (logical delete)
- GET /api/itemtypes/:name/properties — Get property list
- POST /api/itemtypes/:name/properties — Add property
- PUT /api/itemtypes/:name/properties/:propName — Modify property
- DELETE /api/itemtypes/:name/properties/:propName — Delete property
- POST /api/itemtypes/batch — Batch operations
#### P2-3: Complete Import/Export APIs
- POST /api/itemtypes/import/xml — Import from XML file
- POST /api/itemtypes/import/SCSAI — Import from SCSAI
- GET /api/itemtypes/export/xml/:name — Export to XML file
- GET /api/itemtypes/export/json/:name — Export to JSON
- POST /api/itemtypes/export/batch — Batch export
Phase 3: Rewrite front-end object class management UI (estimated 6-8 hours)
#### P3-1: Enhance object class list
- Add 'Create Object Class' button → Launches creation wizard
- Add batch selection (checkbox) → Batch delete/export
- Add category filter tabs (Design/Change/Procurement/Organization/Dashboard)
- Add sorting (by name/type/property count/update time)
- Add right-click menu (Edit/Copy/Delete/Export)
#### P3-2: Create object class wizard
- Step 1: Select base type (Normal/Polymorphic/Dependent)
- Step 2: Fill in basic info (name/label/category/description)
- Step 3: Configure properties (name/type/required/default/data source)
- Step 4: Configure lifecycle (select or create Life Cycle Map)
- Step 5: Configure permissions (Can Add / Allowed Permission)
- Step 6: Preview AML → Confirm creation
#### P3-3: Object Class Detail Editing
- Attributes Tab: Supports adding/editing/deleting/sorting attributes
- Methods Tab: Supports viewing method code
- Relations Tab: Supports viewing and configuring relation types
- Lifecycle Tab: Visual lifecycle state diagram
- Permissions Tab: Permission rule editing
- AML Tab: Enhanced AML Editor (syntax highlighting/validation/auto-completion)
#### P3-4: Import/Export UI
- Import: File upload component (supports multi-file .xml drag-and-drop upload)
- Export: Download button (single/batch export to XML/JSON)
- Import Preview: Display parsed results after upload, confirm before import
- Import Report: Show successful/failed/skipped entries
#### P3-5: Activate Existing but Unused Backend APIs
- Validate: AML syntax validation button
- Compare: Diff comparison between two AML templates
- Fix: One-click fix for AML issues
- Analyze: Full analysis dashboard
- Graph: D3/Mermaid relationship diagram visualization
Phase 4: AI Capability Implementation (Estimated 4-6 hours)
#### P4-1: AI Object Class Creation
- Train/build Prompt templates based on ItemType XML definitions
- User describes requirements → AI generates complete AML definition
- AI automatically infers attribute types, data sources, lifecycle
- Supports inheritance/copying from existing types
#### P4-2: AI Object Class Repair
- Automatically detect issues in AML definitions (missing attributes, type mismatches, etc.)
- AI generates repair suggestions → User confirms → Automatically applies
- Supports batch repair
#### P4-3: AI Object Class Optimization
- Analyze attribute naming conventions, data type selection
- Suggest best practices (indexes, default values, classification structure)
- One-click application of optimization suggestions
#### P4-4: AI Object Class Comparison
- Compare local definitions vs SCSAI online definitions
- Compare differences between two different versions
- Generate difference report and merge suggestions
Phase 5: Integration Testing and Verification (Estimated 2-3 hours)
- End-to-end testing: Create → Edit → Export → Import → Delete
- SCSAI communication testing: Verify all CRUD operations
- AI functionality testing: Create/Fix/Optimize/Compare scenarios
- Performance testing: Full loading of 24 ItemTypes
- Error recovery testing: Network disconnect/SCSAI unavailable/Database lock
IV. Key Design Decisions
4.1 Why not directly replace the custom router with Express Router?
The current aml.js uses a custom signature (req, res, pathname, query, bodyStr) because server.js uses a custom HTTP framework, not Express. Decision: Use the Express Router pattern internally within the routing module for code organization, but maintain a compatible interface with the existing server.js. Migrate to Express gradually.
4.2 Why keep the local SQLite instead of accessing everything via SCSAI?
- Offline capability: View cached object class definitions when SCSAI is unavailable.
- Performance: Local queries are much faster than SCSAI SOAP calls.
- AI context: The AI assistant needs quick access to object class metadata, unsuitable for calling SCSAI every time.
- Version management: Store historical versions of object class definitions locally.
4.3 Why not split the frontend into multiple Vue components?
The current app.js is a single file with over 6000 lines. Decision: This optimization will not split files for now, but improve maintainability through clear function grouping and comments. Component splitting can be done later if needed.
4.4 AI Three-Level Degradation Strategy
L1 (直接执行): AI 返回 tool_call + auto_execute → 自动执行操作
↓ 失败/不支持
L2 (确认执行): AI 返回操作建议 → 用户确认后执行
↓ 失败/超时
L3 (纯对话): 降级为文本对话,提供指导建议
↓ 失败/超时
L4 (本地回退): 使用本地规则引擎,基于 ItemType XML 定义进行操作
五、风险与缓解
| 风险 | 影响 | 缓解措施 |
|------|------|----------|
| SCSAI communication layer refactoring causes regression of existing functionality | High | Keep old interfaces as a compatibility layer, migrate progressively |
| Database table structure changes causing data loss | High | Migration script + data backup |
| Frontend changes too extensive, affecting other modules | Medium | Object class management code is relatively independent, impact scope controllable |
| AI-generated AML quality unstable | Medium | Manual confirmation step + AML validator |
| Splitting 2276-line aml.js introduces new bugs | Medium | Migrate module by module, verify each step |
VI. Priority Ranking
| Priority | Phase | Estimated Hours | Value |
|--------|------|----------|------|
| P0 | Fix critical bugs | 2-3h | ? System unusable if not fixed |
| P1 | Unify communication layer | 3-4h | ? Architectural foundation |
| P2 | Refactor routing + complete APIs | 4-5h | ? Backend completeness |
| P3 | Rewrite frontend UI | 6-8h | ? User-visible |
| P4 | AI capabilities | 4-6h | ? Differentiated value |
| P5 | Integration testing | 2-3h | ? Quality assurance |
Total estimated hours: 21-29 hours
VII. Immediate Action Items (P0 Fix List)
- ✅ Fix aml.js:1553 — require('../database1') → require('../database')
- ✅ Fix aml.js:1649 — Remove erroneous else nesting
- ✅ Fix aml.js:44-47 — Add missing columns to aml_properties table
- ✅ Add PUT /api/aml/template/:id update route
- ✅ Fix aml.js:276 — getTemplateDetail query for default_value column
BossAgents