Right-Hand Assistant — Requirements Specification Document (Optimization Plan)
Version: V1.0
Date: 2026-06-24
Scope: Based on gap analysis between product design documents and current code, focusing on V1.0 completion + V1.1 direction
Principle: Only document unimplemented or specific optimization requirements; do not repeat completed items.
1. Component Positioning
1.1 Core Responsibilities
This component is responsible for filling the functional gaps of the Right-Hand Assistant platform in four dimensions: voice-driven decision-making, tri-end collaboration, digital employee automation, and relationship-aware engine, achieving a leap from "functional" to "user-friendly."
1.2 Core Inputs
- Boss's voice command (Mini Program/Feishu) → ASR text → Intent recognition → Business operation
- BOM Excel file → AI recognition → Structured BOM tree → Association matching
- Feishu card button callback → Approval/confirmation action → Business system execution
- Email content → Command parsing → Automatic triggering of procurement/approval/notification processes
1.3 Core Outputs
- Structured execution results of voice commands (decision cards/approval status/operation confirmation)
- Unified data views and operational experience across three ends (web/Mini Program/Feishu)
- Automated task chains and execution reports for collaboration between digital employees
- Automatic association graphs and completeness scores for BOM/ECO/products
1.4 Responsibility Boundaries
- What it does NOT do: Does not implement personalized constitution detection (independent product line, outside this platform's scope).
- What it does NOT do: Does not implement the MTCLAW inference service itself (external service; this platform only handles client-side calls).
- What it does NOT do: Does not implement a data asset marketplace (V2.0 direction; V1.x only handles data collection and display).
- What it does NOT do: Does not refactor the existing architecture (unified Pipeline, SmartLLMRouter, and rule engine are already validated).
2. Domain Terminology
Voice Decision Chain
: The complete path from the boss issuing a voice command to system execution: Voice → ASR → NLU → Intent routing → Business operation → Result feedback.
Three-End Unification
: The web client (Vue 3 SPA), mini-program client (uni-app), and Feishu client (Bot + Cards) share the same set of backend APIs and business logic, with frontends adapted to their respective interaction patterns.
Decision Card
: A structured operation confirmation interface presented in Feishu/mini-programs, containing key information summaries, action buttons, and risk warnings.
Collaboration Chain
: A task relay mechanism automatically triggered among digital employees, where one employee, upon completing a task, automatically awakens the next relevant employee.
Relationship Awareness
: The capability to automatically discover existing objects and establish associations when creating/importing/fixing BOMs, ECOs, or Parts.
Email as Command
: Parsing received email content into business commands (e.g., quote confirmation, approval granted) to automatically trigger corresponding processes.
3. Roles and Boundaries
3.1 Core Roles
- Business Owner: Makes decision approvals via voice/Feishu cards, without directly operating complex interfaces.
- Business Operator: Performs in-depth work such as BOM management, content generation, and procurement operations via the web client.
- All-Staff Collaborator: Receives notifications, executes approvals, and views task statuses via Feishu.
3.2 External Systems
- WeChat Open Platform: Mini-program login authorization, subscription message push.
- Feishu Open Platform: Bot messages, card interactions, approval flows.
- iFlytek: Speech recognition (ASR).
- 1688 Open Platform: Supplier sourcing and quotation.
- SCSAI Agent: PLM data storage and business processes.
3.3 Interaction Context
@startuml
left to right direction
rectangle "左帮右臂平台" as platform {
}
actor "企业老板" as boss
actor "业务操作员" as operator
actor "全员协作者" as collaborator
boss --> platform : 语音指令 / 决策卡片
operator --> platform : BOM管理 / 采购 / 内容生成
collaborator --> platform : 飞书审批 / 通知确认
cloud "微信开放平台" as wechat
cloud "飞书开放平台" as feishu
cloud "讯飞 iFlytek" as iflytek
cloud "1688" as alibaba
database "SCSAI Agent" as SCSAI
platform --> wechat : 小程序登录/消息
platform --> feishu : Bot/卡片/审批
platform --> iflytek : 语音识别
platform --> alibaba : 供应商寻源
platform --> SCSAI : PLM数据读写
@enduml
4. DFX约束
4.1 性能
- 语音识别到意图路由的端到端延迟应当不超过 3 秒(ASR 1.5s + NLU 1.5s)
- 飞书卡片从按钮点击到结果返回应当不超过 5 秒
- BOM Excel 导入(1000 行)到生成 BOM 树应当不超过 30 秒
- 关系发现(100 个对象)的批量处理应当不超过 10 秒
4.2 可靠性
- 飞书 pendingActions 必须持久化,服务重启后不丢失未完成的审批状态
- 语音指令执行失败时,系统必须通过原通道(飞书/小程序)通知用户失败原因
- 邮件监听断连后必须自动重连,重连间隔不超过 30 秒
4.3 安全性
- 小程序微信登录的 JWT secret 禁止使用硬编码默认值
- 飞书事件订阅的加密/解密必须完整实现
- 多租户场景下,所有 SCSAI 查询必须注入 enterprise_id 过滤
4.4 可维护性
- 三端(网页/小程序/飞书)的 API 调用必须走统一的 Pipeline 入口
/api/pipeline/execute - 所有新增 API 必须在
server.js的handleRequest中注册 - 数字员工新增类型只需修改配置,不需要修改调度器代码
4.5 兼容性
- 微信发布服务的环境变量必须统一为
WECHAT_APP_ID/WECHAT_APP_SECRET,废弃MINIPROGRAM_APPID/MINIPROGRAM_SECRET - 小程序 API 必须兼容主服务器的
db-adapter双后端(SQLite/MySQL)
5. 核心能力
5.1 语音决策链路
5.1.1 业务规则
- 小程序语音输入接入 ASR: 当用户在小程序端按下"按住说话"按钮并松手后,系统应当录制音频、调用 ASR 服务识别文本、将识别结果发送到对话引擎。
a. 验收条件:[用户在小程序按下并松开语音按钮] → [系统调用 uni.getRecorderManager() 录制 PCM 音频] → [上传至 /api/asr/recognize 端点] → [返回识别文本并显示在聊天输入框]
- Voice/Text Intent Routing: After ASR returns recognized text, the system should route the text to the corresponding digital employee via the ConversationEngine's intent recognition.
a. Acceptance Criteria: [ASR returns "Procure 100 sets of motors"] → [ConversationEngine recognizes intent as procurement] → [Routed to DS-PROC-001 Procurement Assistant] → [Returns a procurement decision card]
- Feishu Voice Approval Execution: When a user clicks the '? Voice Approval' button on a Feishu card, the system should record this approval action and execute the corresponding business process.
a. Acceptance Criteria: [User clicks the 'Voice Approval' button on the Feishu card] → [System retrieves pending actions from pendingActions] → [Executes approval (e.g., ECR approval/BOM release/Purchase order placement)] → [Returns approval result card]
- Prohibition: The voice approval button must not appear on cards that have no pending actions.
a. Acceptance Criteria: [When pendingActions is empty, render the Feishu card] → [The card does not contain the 'Voice Approval' button]
5.1.2 Interaction Flow
@startuml
actor 老板
participant "小程序" as miniapp
participant "ASR服务" as asr
participant "对话引擎" as conv
participant "Digital Staff" as staff
participant "SCSAI" as SCSAI
老板 -> miniapp : 按住说话
miniapp -> miniapp : 录制PCM音频
老板 -> miniapp : 松手
miniapp -> asr : POST /api/asr/recognize (音频)
asr --> miniapp : 识别文本
miniapp -> conv : POST /api/digital-staff/chat (文本)
conv -> conv : 意图识别
conv -> staff : 路由到对应员工
staff -> SCSAI : 执行业务操作
SCSAI --> staff : 操作结果
staff --> conv : 生成回复
conv --> miniapp : 决策卡片/确认请求
miniapp --> 老板 : 展示结果
@enduml
5.1.3 异常场景
- ASR 服务不可用
a. 触发条件:讯飞 API 超时或返回错误
b. System Behavior: Degrades to Echo mode, returns preset command text based on audio volume, and annotates the reply with 'Voice recognition service is temporarily unavailable, simulated input is used.'
c. User Perception: A degradation notice is displayed in the chat interface, but functionality is not interrupted.
- Intent Recognition Failure
a. Trigger Condition: The ConversationEngine fails to match the text to any known intent.
b. System Behavior: Routes to the default digital employee (DS-SYS-001), returns 'I don't quite understand. You can try saying: Purchase XXX, View BOM, Generate announcement.'
c. User Perception: Receives a guiding reply instead of an error message.
5.2 Mini Program Tri-end Unification
5.2.1 Business Rules
- Complete WeChat Login Implementation: When a user clicks 'One-Click WeChat Login' in the mini program, the system should obtain the openid via the WeChat jscode2session interface, create or find the user, and issue a JWT.
a. Acceptance Criteria: [User clicks WeChat login] → [Calls uni.login() to get code] → [Backend calls WeChat jscode2session] → [Stores openid in users table] → [Issues JWT and returns it to the frontend]
- Complete Mini Program Voice Input Implementation: The VoiceInput component must implement the complete process of recording, uploading, and recognition.
a. Acceptance Criteria: [User presses voice button] → [Call uni.getRecorderManager().start() to start recording] → [Release to call stop()] → [Obtain temporary audio file path] → [Upload to /api/asr/recognize] → [Returned text is filled into the input box]
- Mini Program Page Data Integration: All mini program pages must call backend real data via miniappApi; hardcoded mock data is not allowed.
a. Acceptance Criteria: [Open the mini program workbench page] → [Call getDashboard() to obtain real statistics] → [The page displays real product count/change count/rule count/employee count]
- Three-End Message Synchronization: When an operation is triggered on the web page or Feishu side, the mini program must be able to receive the corresponding notification.
a. Acceptance Criteria: [An ECR change is created on the web page] → [A new notification appears in the mini program notification list] → [Clicking the notification jumps to the change details page]
5.2.2 Interaction Flow
@startuml
actor 用户
participant "小程序" as miniapp
participant "微信开放平台" as wx
participant "后端API" as api
participant "数据库" as db
用户 -> miniapp : 点击微信登录
miniapp -> wx : uni.login() → code
wx --> miniapp : code
miniapp -> api : POST /api/miniapp/login {code}
api -> wx : jscode2session(code)
wx --> api : {openid, session_key}
api -> db : INSERT/SELECT users
db --> api : user record
api --> miniapp : {token, user}
miniapp -> miniapp : 存储token到store
miniapp --> 用户 : 跳转到AI对话页
@enduml
5.2.3 异常场景
- 微信登录配置缺失
a. 触发条件:_config.wx.appId 或 _config.wx.appSecret 未配置
b. System Behavior: Use dev_ + code as openid for degraded login, and log a warning in the server log.
c. User Perception: Login is successful but the log is marked as development mode.
- Mini Program Backend Connection Failure
a. Trigger Condition: API server address is unreachable.
b. System Behavior: Display "Unable to connect to the server. Please check the server address configuration," and provide an entry to reconfigure.
c. User Perception: Sees the error message and a configuration button.
5.3 Feishu Integration Enhancement
5.3.1 Business Rules
- pendingActions Persistence: When the Feishu Bot creates a pendingAction, the system should simultaneously write it to persistent storage (SQLite/JSONL) to allow automatic recovery after service restart.
a. Acceptance criteria: [Create pendingAction] → [Write to feishu_pending_actions table] → [Service restart] → [Recover unexpired (within 10 minutes) pendingActions from database] → [User can still execute normally by clicking the card button]
- Feishu event subscription encryption and decryption: When receiving a Feishu event callback, the system should verify the signature and decrypt the message body.
a. Acceptance criteria: [Feishu sends encrypted event] → [Decrypt using Encrypt Key] → [Verify Verification Token] → [Process event] → [Return challenge response]
- Feishu approval flow integration: When a business operation requires approval, the system should create a Feishu approval instance instead of merely sending a card message.
a. Acceptance criteria: [ECR change requires approval] → [Call Feishu approval API to create approval instance] → [Approver sees pending item in Feishu Approval Center] → [Approval callback triggers SCSAI status change after approval]
5.3.2 Interaction Flow
@startuml
participant "飞书" as feishu
participant "飞书Bot" as bot
participant "数据库" as db
participant "SCSAI" as SCSAI
feishu -> bot : 卡片按钮回调 {action, pending_id}
bot -> db : SELECT * FROM feishu_pending_actions WHERE id = pending_id
db --> bot : pendingAction 数据
bot -> bot : 验证未过期
bot -> SCSAI : 执行业务操作
SCSAI --> bot : 操作结果
bot -> db : DELETE FROM feishu_pending_actions WHERE id = pending_id
bot -> feishu : 更新卡片状态
@enduml
5.3.3 异常场景
- pendingAction 已过期
a. 触发条件:用户点击卡片按钮时 pendingAction 已超过 10 分钟 TTL
b. System behavior: Returns "This operation has timed out, please initiate again"
c. User perception: Card updates to "Timed Out" status
- Feishu approval creation failure
a. Trigger condition: Feishu approval API returns an error
b. System behavior: Fallback to card message confirmation mode, log the reason for fallback
c. User perception: Receives a card message instead of a notification in the Approval Center
5.4 Procurement Process End-to-End
5.4.1 Business Rules
- Purchase order creation and tracking: When procurement comparison is completed and approved by the boss, the system should create a purchase order (PO) and track its delivery status.
a. Acceptance criteria: [Boss approves procurement plan] → [System creates PO record (including supplier/quantity/price/delivery date)] → [PO status is "Pending Confirmation"] → [Status changes to "Confirmed" after supplier confirmation] → [Status changes to "Completed" after delivery]
- 1688 Degraded Experience Optimization: When the 1688 API Key is not configured or the call fails, the system should provide clear degradation prompts instead of silently falling back to Mock.
a. Acceptance Criteria: [1688 API unavailable] → [Return "1688 interface temporarily unavailable, AI intelligent sourcing has been used as a substitute"] → [Call SmartLLMRouter's LLM sourcing capability] → [Result labeled "AI recommendation for reference only"]
- Enhanced Quotation Email Auto-Parsing: When a supplier quotation email is received, the system should automatically extract structured quotations and associate them with the corresponding procurement task.
a. Acceptance Criteria: [Quotation email received] → [EmailListener triggers newEmail event] → [llm-quotation-service parses structured quotation] → [Quotation data associated with procurement task in staff_tasks] → [Task board updated to "Quotation Received"]
5.4.2 Interaction Flow
@startuml
actor 老板
participant "飞书/小程序" as client
participant "采购助手" as proc
participant "1688/LLM" as sourcing
participant "邮件服务" as email
participant "任务看板" as board
老板 -> client : "采购100套电机"
client -> proc : 路由到采购助手
proc -> sourcing : 发起寻源请求
sourcing --> proc : 供应商列表+报价
proc -> board : 创建采购任务(待审批)
proc -> client : 比价决策卡片
老板 -> client : 审批通过
client -> proc : 确认采购
proc -> email : 发送采购订单邮件
proc -> board : 更新任务状态(已下单)
@enduml
5.4.3 异常场景
- 所有寻源渠道均不可用
a. 触发条件:1688 API、LLM 寻源、本地数据库均无法返回结果
b. System Behavior: Return "No supplier information available, recommend manually adding a supplier and re-initiating inquiry"
c. User Perception: Receive clear prompts and actionable suggestions
5.5 BOM Management Enhancement
5.5.1 Business Rules
- BOM Excel Import: When a user uploads an Excel/CSV file, the system should parse the file content, identify column mappings via AI, and generate structured BOM data.
a. Acceptance Criteria: [User uploads Excel file on BomAssistant page] → [Backend parses Excel (xlsx library)] → [AI identifies column-to-BOM field mapping (item_number/name/quantity/material)] → [Generate BOM tree structure] → [Frontend displays BOM tree]
- BOM Multi-level Graphical Display: When users view BOM details, the system should provide a graphical tree structure display.
a. Acceptance Criteria: [User clicks on a BOM item] → [Frontend renders an expandable/collapsible tree diagram (nodes=parts, edges=parent-child relationships)] → [Supports zooming and dragging] → [Clicking a node displays part details]
- BOM Automatic Matching with Industrial Object Library: When importing BOM data, the system should automatically search for matching objects in the SCIOT Industrial Object Library.
a. Acceptance Criteria: [BOM import completed] → [RelationshipResolver.resolveExistence performs a three-level check for each part] → [Matched parts are labeled "Linked" and linked to SCSAI objects] → [Unmatched parts are labeled "Pending Confirmation"]
5.5.2 Interaction Flow
@startuml
actor 用户
participant "BomAssistant" as bom
participant "后端API" as api
participant "AIIdentify" as ai
participant "关系解析器" as resolver
participant "SCSAI" as SCSAI
用户 -> bom : 上传Excel文件
bom -> api : POST /api/bom/import/upload (file)
api -> ai : 解析Excel + 列映射识别
ai --> api : 结构化BOM数据
api -> resolver : resolveExistence(每个零件)
resolver -> SCSAI : 查询已存在对象
SCSAI --> resolver : 匹配结果
resolver --> api : 关联计划
api --> bom : BOM树 + 匹配状态
bom --> 用户 : 展示BOM树(已关联/待确认)
@enduml
5.5.3 异常场景
- Excel 列名无法识别
a. 触发条件:AI 无法将 Excel 列名映射到 BOM 标准字段
b. System Behavior: Returns column mapping suggestions for user manual confirmation.
c. User Perception: Sees a mapping confirmation interface and can make manual adjustments.
- BOM Circular Dependency Detection
a. Trigger Condition: A circular reference A→B→A exists in the BOM tree.
b. System Behavior: Rejects the import and prompts "Circular dependency detected: A→B→A, please check the data."
c. User Perception: Receives a clear error message and the circular path.
5.6 Digital Employee Automated Collaboration
5.6.1 Business Rules
- Automatic Collaboration Orchestration Between Employees: When a digital employee completes a task, the system should automatically trigger the next relevant employee based on collaboration rules.
a. Acceptance Criteria: [DS-PROC-001 Procurement Assistant completes inquiry] → [System automatically triggers DS-COST-001 Cost Optimizer for cost analysis based on collaboration rules] → [After Cost Optimizer completes, triggers DS-VEN-001 Supplier Steward for supplier evaluation] → [Task board displays the complete collaboration chain]
- Collaboration Rule Configuration Driven: The triggering rules for the collaboration chain should be defined via YAML configuration, requiring no code changes.
a. Acceptance criteria: [Defined in digital-staff/collaboration-rules.yaml as DS-PROC-001 → DS-COST-001] → [Cost analysis automatically triggered after purchase task completion] → [Rule modifications in YAML take effect without service restart]
- Collaboration chain visualization: When a collaboration chain executes, the task board should display the complete task chain and the current execution node.
a. Acceptance criteria: [Collaboration chain starts] → [Task board displays chain diagram: Purchase Inquiry(✓) → Cost Analysis(In Progress) → Supplier Evaluation(Pending)] → [Each node is clickable for details]
5.6.2 Interaction Flow
@startuml
participant "采购助手" as proc
participant "协作调度器" as scheduler
participant "成本优化师" as cost
participant "供应商管家" as vendor
participant "任务看板" as board
proc -> board : 完成询价任务
board -> scheduler : 触发协作规则
scheduler -> scheduler : 查找 DS-PROC-001 的后继规则
scheduler -> cost : 创建成本分析任务
cost -> board : 完成成本分析
board -> scheduler : 触发协作规则
scheduler -> vendor : 创建供应商评估任务
vendor -> board : 完成供应商评估
@enduml
5.6.3 异常场景
- 协作链中某环节失败
a. 触发条件:成本优化师执行失败
b. System behavior: Pause the collaboration chain, notify the initiator "Cost analysis failed, collaboration chain paused", provide retry and skip options
c. User perception: Receive a Feishu/Mini Program notification, can choose to retry or skip this step
- Collaboration Rule Loop Detection
a. Trigger condition: YAML configuration contains a circular rule A→B→A
b. System behavior: Validate the rule graph on startup, reject loading and log an error if a cycle is detected
c. User perception: Log displays "Collaboration rule contains a cycle: A→B→A, skipped" during service startup
5.7 Relationship-Aware Engine (V1.1)
5.7.1 Business Rules
- BOM Auto-Association: When creating or importing a BOM, the system should automatically discover existing Part objects and establish BOM relationships.
a. Acceptance criteria: [Import a BOM containing "Motor-A"] → [RelationshipResolver.resolveExistence detects "Motor-A" already exists in SCSAI] → [Automatically creates a BOM relationship instead of duplicating the Part] → [Logs the association operation]
- ECO Auto-Association: When creating an Engineering Change Order (ECO), the system should automatically associate the affected BOMs, Parts, and documents.
a. Acceptance Criteria: [Create ECO "Modify Motor-A Specification"] → [RelationshipCapability.identifyRelations identifies associated BOMs and Parts] → [Automatically creates ECO→BOM and ECO→Part relationships] → [Change impact analysis report includes all associated objects]
- Product Auto-Association: When creating a product, the system should automatically associate all its subordinate BOMs, documents, and suppliers.
a. Acceptance Criteria: [Create product "Phosphorus Chemical Equipment-A"] → [discoverRelations discovers 3 associated BOMs and 5 documents] → [buildLinkPlan generates an association execution plan] → [After execution, the product details page displays the complete association graph]
- Relationship Completeness Score: After an object is created, the system should calculate a completeness score based on the RelationshipChecklist.
a. Acceptance Criteria: [Part creation completed] → [postValidate checks for required relationships (BOM parent, document, supplier)] → [3/5 required relationships established → completeness score 60%] → [Prompt: "Suggest adding: supplier association, quality document"]
5.7.2 Interaction Flow
@startuml
actor 用户
participant "创建能力" as create
participant "关系解析器" as resolver
participant "关系能力" as relCap
participant "检查清单" as checklist
participant "SCSAI" as SCSAI
用户 -> create : CreateBOM/ECO/产品
create -> resolver : resolveExistence(对象数据)
resolver -> SCSAI : 三级检测(精确→模糊→私有库)
SCSAI --> resolver : 存在性结果
create -> resolver : discoverRelations(批量对象)
resolver -> relCap : identifyRelations
relCap --> resolver : 候选关系列表
create -> resolver : buildLinkPlan(对象+关系)
resolver --> create : 关联执行计划
create -> SCSAI : 执行关联AML
create -> checklist : postValidate(已创建对象)
checklist --> create : 完整性评分+建议
create --> 用户 : 创建结果+关联状态+完整性评分
@enduml
5.7.3 异常场景
- 关系发现无结果
a. 触发条件:新创建的对象在 SCSAI 中无任何匹配
b. System Behavior: Marked as "Orphaned Object," completeness score 0%, prompt "Suggest manual association"
c. User Perception: Sees the "Orphaned Object" marker and association suggestions
- Batch Association Partial Failure
a. Trigger Condition: Batch creation of 10 relationships, 3 fail due to SCSAI permission issues
b. System Behavior: 7 succeed, 3 failures logged in error log, returns partial success result and failure reasons
c. User Perception: Sees "7/10 associations successful" and error details for failed items
5.8 Email as Command (V1.2 Direction)
5.8.1 Business Rules
- Universal Email Command Parsing: Upon receiving an email, the system should attempt to parse the email content as a business command, not limited to purchase quote recognition.
a. Acceptance Criteria: [Receive email with subject "ECR-2026-001 Approved"] → [EmailListener triggered] → [Command parser identifies as "approve" command] → [Automatically executes ECR status change] → [Notifies relevant personnel]
- Email Command Template Configuration: The matching rules for email commands should be defined via YAML configuration.
a. Acceptance Criteria: [Define subject.contains("Approved") → action: ecr_approve in email-commands.yaml] → [Automatically triggers approval upon receiving matching email] → [Changes to YAML take effect without restart]
- Email Listener IMAP Configuration: The IMAP server address for EmailListener should be read from configuration, not hardcoded as imap.sina.com.
a. Acceptance Criteria: [Configure email.imap.host: imap.qq.com in config.yaml] → [EmailListener connects to imap.qq.com] → [Uses default imap.sina.com if not configured]
5.8.2 Interaction Flow
@startuml
participant "邮件服务器" as imap
participant "邮件监听" as listener
participant "命令解析器" as parser
participant "业务执行器" as executor
participant "通知服务" as notify
imap -> listener : 新邮件推送
listener -> parser : 解析邮件内容
parser -> parser : 匹配命令模板
parser -> executor : 执行对应业务操作
executor --> parser : 执行结果
parser -> notify : 发送执行结果通知
notify --> listener : 飞书/小程序通知
@enduml
5.8.3 异常场景
- 邮件命令无法匹配
a. 触发条件:邮件内容不匹配任何已知命令模板
b. System Behavior: Archive email as "Unrecognized", trigger no action.
c. User Perception: No perception (silently processed, administrator can view in logs)
- IMAP Connection Persistently Fails
a. Trigger Condition: 5 consecutive reconnection attempts fail.
b. System Behavior: Stop reconnecting, send Lark alert to administrator: "Email listening service has stopped".
c. User Perception: Administrator receives Lark alert.
5.9 Multi-Tenant Security Hardening
5.9.1 Business Rules
- Tenant Middleware Auto-Injection: When an API request arrives, the system shall extract the enterprise_id from the JWT and automatically inject it into all SCSAI queries.
a. Acceptance Criteria: [Tenant A's user queries Part list] → [Middleware extracts enterprise_id=ent_A from JWT] → [SCSAI query to AML automatically adds ent_A filter] → [Only returns Tenant A's data]
- Tenant Data Isolation Verification: When performing any data operation, the system shall verify that the enterprise_id of the target object matches the current user's enterprise_id.
a. Acceptance Criteria: [Tenant A's user attempts to access a Part with enterprise_id=ent_B] → [Middleware intercepts] → [Returns 403 Forbidden] → [Logs unauthorized access audit log]
- Tenant Quota Limitation: When a tenant creates data, the system shall check if the quota limit is exceeded.
a. Acceptance Criteria: [Tenant A has created 1000 Parts (quota limit)] → [Attempts to create the 1001st] → [Returns "Data quota limit reached. Please contact administrator for upgrade."] → [Logs quota exceedance log]
5.9.2 Interaction Flow
@startuml
participant "客户端" as client
participant "租户中间件" as middleware
participant "业务处理" as handler
participant "SCSAI" as SCSAI
client -> middleware : 请求 (JWT含enterprise_id)
middleware -> middleware : 提取enterprise_id
middleware -> middleware : 验证数据隔离
middleware -> handler : 注入enterprise_id上下文
handler -> SCSAI : 查询(含enterprise_id过滤)
SCSAI --> handler : 结果(仅当前租户数据)
handler --> client : 响应
@enduml
5.9.3 异常场景
- JWT 中无 enterprise_id
a. 触发条件:用户 JWT 中未包含 enterprise_id 字段
b. System Behavior: Marked as "Public Tenant", uses default enterprise_id=default
c. User Perception: Normal usage, but can only see public data
5.10 WeChat Publishing Service Unification
5.10.1 Business Rules
- Environment Variable Unification: When the system starts, WeChat publishing-related environment variables must be unified to WECHAT_APP_ID / WECHAT_APP_SECRET, deprecating MINIPROGRAM_APPID / MINIPROGRAM_SECRET.
a. Acceptance criteria: [Configure WECHAT_APP_ID and WECHAT_APP_SECRET] → [Both wechat-publish.js and content-api.js use unified variables] → [MINIPROGRAM_* variables are no longer effective] → [Log prompts "WeChat configuration unified" on startup]
- Automatic retry on publish failure: The system should automatically retry up to 3 times when WeChat publishing fails.
a. Acceptance criteria: [WeChat API returns a 500 error] → [System waits 5 seconds before retrying] → [Retry up to 3 times] → [After 3 failures, mark as "Publish Failed" and notify the user]
- Published article management: After an article is successfully published, the system should record the publish ID to support subsequent querying and management.
a. Acceptance criteria: [Article published successfully] → [Record publish_id and publish_time] → [Content list page shows "Published" status] → [Support viewing the publish link]
5.10.2 Exception Scenarios
- WeChat Token Refresh Failure
a. Trigger condition: WeChat access_token refresh API returns an error
b. System behavior: Use the cached old token (if not expired); if the old token is also expired, pause publishing functionality
c. User perception: Publish button displays "WeChat service temporarily unavailable"
6. Data Constraints
6.1 Purchase Order (PurchaseOrder)
- poId: Unique identifier, format PO-{YYYYMMDD}-{seq4}
- supplierId: Associated supplier ID, required
- items: List of purchase items (JSON array), each containing partNumber/quantity/unitPrice/currency
- status: Enum values: draft / pending_approval / approved / confirmed / shipped / completed / cancelled
- totalAmount: Automatically calculated from the sum of items
- approvedBy: Approver ID, required after approval
- approvedAt: Approval time, required after approval
- deliveryDate: Estimated delivery date, format ISO 8601
6.2 Feishu Pending Action (FeishuPendingAction)
- id: UUID, primary key
- action: Action type, enum values: approve / reject / confirm / cancel
- businessType: Business type, enum values: ecr / bom / procurement / vendor
- businessId: Business object ID
- userId: Initiator ID
- feishuUserId: Feishu user open_id
- cardMessageId: Feishu card message ID
- payload: Operation parameters (JSON)
- createdAt: Creation time
- expiresAt: Expiration time, createdAt + 10 minutes
- consumedAt: Consumption time, required after consumption
6.3 Collaboration Rule (CollaborationRule)
- sourceStaffId: Triggering staff ID, e.g., DS-PROC-001
- targetStaffId: Target staff ID, e.g., DS-COST-001
- triggerCondition: Trigger condition, e.g., task_status=completed
- triggerEvent: Trigger event, enum values: task_completed / task_failed / task_escalated
- delaySeconds: Delay execution time in seconds, default 0
- enabled: Whether enabled, boolean
6.4 Email Command Template (EmailCommandTemplate)
- name: Template name, e.g., ecr_approve
- subjectPattern: Subject matching regex, e.g., /Approval Passed/
- bodyPattern: Body matching regex (optional)
- action: Trigger action, e.g., ecr.approve
- params: Action parameter template (supports extracting variables from email content)
- priority: Priority, lower number indicates higher match precedence
- enabled: Whether enabled
6.5 Tenant Quota (TenantQuota)
- enterpriseId: Tenant ID
- maxParts: Maximum number of Parts, default 10000
- maxBoms: Maximum number of BOMs, default 1000
- maxUsers: Maximum number of users, default 50
- maxStaffTasks: Monthly digital employee task limit, default 5000
- currentParts: Current Part count (automatically maintained by system)
- currentBoms: Current BOM count (automatically maintained by system)
Appendix: Requirement Priority Overview
| ID | Requirement Name | Priority | Phase | Estimated Effort |
|---|---|---|---|---|
| 5.1.1-R1 | Mini Program Voice Input Access to ASR | P0 | V1.0 | 3 days |
| 5.1.1-R2 | Voice Text Intent Routing | P0 | V1.0 | 2 days |
| 5.1.1-R3 | Feishu Voice Approval Execution | P0 | V1.0 | 2 days |
| 5.2.1-R1 | WeChat Login Full Implementation | P0 | V1.0 | 2 days |
| 5.2.1-R2 | Mini Program Voice Input Full Implementation | P0 | V1.0 | 2 days |
| 5.2.1-R3 | Mini Program Page Data Integration | P1 | V1.0 | 3 days |
| 5.2.1-R4 | Three-End Message Synchronization | P1 | V1.0 | 3 days |
| 5.3.1-R1 | pendingActions Persistence | P0 | V1.0 | 1 day |
| 5.3.1-R2 | Feishu Event Subscription Encryption/Decryption | P1 | V1.0 | 2 days |
| 5.3.1-R3 | Feishu Approval Flow Integration | P1 | V1.0 | 3 days |
| 5.4.1-R1 | Purchase Order Creation and Tracking | P0 | V1.0 | 3 days |
| 5.4.1-R2 | 1688 Degraded Experience Optimization | P1 | V1.0 | 1 day |
| 5.4.1-R3 | Quotation Email Auto-Parsing Enhancement | P1 | V1.0 | 2 days |
| 5.5.1-R1 | BOM Excel Import | P0 | V1.0 | 3 days |
| 5.5.1-R2 | BOM Multi-Level Graphical Display | P1 | V1.0 | 3 days |
| 5.5.1-R3 | BOM and Industrial Object Library Auto-Matching | P0 | V1.0 | 2 days |
| 5.6.1-R1 | Automated Collaboration Orchestration Between Employees | P1 | V1.0 | 3 days |
| 5.6.1-R2 | Collaboration Rule Configuration-Driven | P1 | V1.0 | 2 days |
| 5.6.1-R3 | Collaboration Chain Visualization | P2 | V1.0 | 2 days |
| 5.7.1-R1 | BOM Auto-Association | P0 | V1.1 | 3 days |
| 5.7.1-R2 | ECO Auto-Association | P0 | V1.1 | 3 days |
| 5.7.1-R3 | Product Auto-Association | P1 | V1.1 | 2 days |
| 5.7.1-R4 | Relationship Integrity Scoring | P1 | V1.1 | 2 days |
| 5.8.1-R1 | Generic Email Command Parsing | P1 | V1.2 | 3 days |
| 5.8.1-R2 | Email Command Template Configuration | P1 | V1.2 | 2 days |
| 5.8.1-R3 | Email Listener IMAP Configuration | P0 | V1.2 | 1 day |
| 5.9.1-R1 | Tenant Middleware Auto-Injection | P0 | V1.0 | 3 days |
| 5.9.1-R2 | Tenant Data Isolation Verification | P0 | V1.0 | 2 days |
| 5.9.1-R3 | Tenant Quota Limitation | P2 | V1.1 | 2 days |
| 5.10.1-R1 | WeChat Release Environment Variable Unification | P0 | V1.0 | 0.5 days |
| 5.10.1-R2 | Release Failure Auto-Retry | P1 | V1.0 | 1 day |
| 5.10.1-R3 | Published Article Management | P2 | V1.0 | 2 days |
P0 Total Effort: Approx. 21.5 days
P1 Total Effort: Approx. 24 days
P2 Total Effort: Approx. 6 days
Total: Approx. 51.5 days (Single Full-Stack Developer)
BossAgents