Files
zkxw/docs/superpowers/plans/2026-05-13-flow-designer-enhancements.md
T
2026-05-17 08:36:37 +08:00

15 KiB
Raw Blame History

FlowDesigner 功能补全实施计划

For agentic workers: REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (- [ ]) syntax for tracking.

Goal: 补全流程设计器三个核心功能缺口:审批人选择(用户/角色下拉数据加载)、连线条件分支配置(点击连线编辑条件表达式)、SQL查询帮助提示。

Architecture: 后端新增2个轻量options端点;前端FlowDesigner.vue增加edge:click事件处理、selectedEdge状态、条件表达式编辑面板、以及handleOpen时加载用户/角色数据。

Tech Stack: Python FastAPI, Vue 3 + Element Plus, AntV X6


File Structure

文件 操作 职责
backend/app/api/admin.py 修改 新增 GET /web/admin/users/options 和 GET /web/admin/roles/options
web-admin/src/api/admin.ts 修改 新增 fetchUserOptions() 和 fetchRoleOptions()
web-admin/src/views/system/workflow/designer/FlowDesigner.vue 修改 核心改动:edge事件、selectedEdge、条件编辑面板、数据加载

Task 1: 后端新增 users/options 和 roles/options 端点

Files:

  • Modify: backend/app/api/admin.py — 在 list_roles_for_select(line 33)后面新增两个端点

  • Step 1: 新增 GET /web/admin/users/options 端点

在 admin.py 的 list_roles_for_select 函数后面(约 line 63 之后),添加:

@router.get("/users/options")
async def list_users_for_select(
    _user: dict = Depends(require_admin_or_super_admin),
    db: Session = Depends(get_db),
):
    """返回用户下拉选项(label=昵称,value=用户ID),供流程设计器审批人选择使用。"""
    tenant_no = _user.get("tenant_no", "")
    q = db.query(SysUser).filter(SysUser.del_flag == 0, SysUser.status == "1")
    if tenant_no:
        q = q.filter(SysUser.tenant_no == tenant_no)
    rows = q.order_by(SysUser.order_num.asc(), SysUser.create_time.desc()).all()
    out = [{"label": (r.nick_name or r.user_no or ""), "value": r.id} for r in rows]
    return success_response(out)

注意:顶部已有 from app.models.models import SysUser, SysRole, ... 等导入,无需新增。

  • Step 2: 新增 GET /web/admin/roles/options 端点

紧接上面的函数后面添加:

@router.get("/roles/options")
async def list_roles_for_designer(
    _user: dict = Depends(require_admin_or_super_admin),
    db: Session = Depends(get_db),
):
    """返回角色下拉选项(label=角色名,value=角色ID UUID),供流程设计器审批人选择使用。
    与 /roles 不同,此端点返回角色 UUID 作为 value(引擎解析审批人需要 UUID)。"""
    tenant_no = _user.get("tenant_no", "")
    q = db.query(SysRole).filter(SysRole.del_flag == 0, SysRole.status == "1")
    if tenant_no:
        q = q.filter(SysRole.tenant_no == tenant_no)
    rows = q.order_by(SysRole.order_num.asc()).all()
    out = [{"label": (r.role_name or "").strip(), "value": r.id} for r in rows if (r.role_name or "").strip()]
    return success_response(out)
  • Step 3: 验证后端启动
cd /Users/wuzilong/work/00code/zkxw/backend && source venv/bin/activate && python -c "from app.api.admin import router; print('OK')"

Expected: OK


Task 2: 前端 API 函数 + 设计器加载用户/角色数据

Files:

  • Modify: web-admin/src/api/admin.ts — 新增两个 API 函数

  • Modify: web-admin/src/views/system/workflow/designer/FlowDesigner.vue — 导入 API、handleOpen 加载数据

  • Step 1: 在 admin.ts 新增两个 API 函数

在 fetchGetRoleList()(line 18-22)后面添加:

/** 流程设计器:用户下拉选项(label=昵称,value=用户ID) */
export function fetchUserOptions() {
  return request.get<Array<{ label: string; value: string }>>({
    url: '/web/admin/users/options'
  })
}

/** 流程设计器:角色下拉选项(label=角色名,value=角色ID UUID) */
export function fetchRoleOptions() {
  return request.get<Array<{ label: string; value: string }>>({
    url: '/web/admin/roles/options'
  })
}
  • Step 2: 在 FlowDesigner.vue 导入新 API 并加载选项数据

修改 line 146 的 import 语句:

import { fetchDesignerData, fetchPublishVersion } from '@/api/workflow'

改为:

import { fetchDesignerData, fetchPublishVersion } from '@/api/workflow'
import { fetchUserOptions, fetchRoleOptions } from '@/api/admin'

然后在 handleOpen() 函数(line 742-748)中添加数据加载:

function handleOpen() {
  selectedNode.value = null
  selectedEdge.value = null
  registerShapes()
  nextTick(() => {
    initGraph()
    loadDesignerData()
    loadOptions()
  })
}

async function loadOptions() {
  try {
    const [users, roles] = await Promise.all([fetchUserOptions(), fetchRoleOptions()])
    userOptions.value = users || []
    roleOptions.value = roles || []
  } catch {
    // 加载失败则保持空选项,不影响设计器其他功能
  }
}

注意:selectedEdge 在 Task 3 中定义。


Task 3: 连线点击 + 条件表达式编辑器 + 连线标签

Files:

  • Modify: web-admin/src/views/system/workflow/designer/FlowDesigner.vue

这是最核心的改动。需要在 FlowDesigner.vue 中完成以下修改:

  • Step 1: 新增 selectedEdge 响应式状态和接口定义

在 selectedNode 定义(line 201)后面添加:

interface ConditionRule {
  field: string
  op: string
  value: string
}

interface SelectedEdgeData {
  id: string
  fromNodeName: string
  toNodeName: string
  rules: ConditionRule[]
  isDefault: boolean
}

const selectedEdge = ref<SelectedEdgeData | null>(null)
  • Step 2: 注册 edge:click 事件 + 修改 blank:click 和 node:click 清除 selectedEdge

在 initGraph() 函数中,graph.on('blank:click', ...) (line 560-563)后面添加 edge 事件:

// 连线点击 → 选中(仅条件节点的出线可编辑条件)
graph.on('edge:click', ({ edge }) => {
  const sourceId = edge.getSourceCellId() || ''
  const sourceNode = graph!.getCellById(sourceId)
  const sourceData = sourceNode?.getData() || {}
  const targetId = edge.getTargetCellId() || ''
  const targetNode = graph!.getCellById(targetId)
  const targetData = targetNode?.getData() || {}

  const edgeData = edge.getData() || {}
  const rawRules = edgeData.conditionExpr ? (JSON.parse(edgeData.conditionExpr) || {}) : {}
  const rules: ConditionRule[] = rawRules.rules || rawRules || []
  // 确保至少有一条规则
  if (!Array.isArray(rules) || rules.length === 0) {
    rules.push({ field: '', op: '==', value: '' })
  }
  // 规范化为 ConditionRule[](只保留简单的 field/op/value 三元组)
  const normalizedRules: ConditionRule[] = rules.map((r: any) => ({
    field: r.field || '',
    op: r.op || '==',
    value: String(r.value ?? ''),
  }))

  selectedEdge.value = {
    id: edge.id,
    fromNodeName: sourceData.nodeName || sourceId,
    toNodeName: targetData.nodeName || targetId,
    rules: normalizedRules,
    isDefault: !edgeData.conditionExpr,
  }
  selectedNode.value = null
})

同时修改 blank:click 和 node:click 事件处理,在清除/设置 selectedNode 时也清除 selectedEdge:

// node:click 处理中添加:
selectedEdge.value = null

// blank:click 处理中改为:
graph.on('blank:click', () => {
  selectedNode.value = null
  selectedEdge.value = null
})
  • Step 3: 连线创建时初始化 data

在 createEdge() 函数(约 line 522-539)中,给新创建的 edge 加上 data 初始化:

在 graph!.createEdge({...}) 调用中添加 data: { conditionExpr: '' } 属性:

createEdge() {
  return graph!.createEdge({
    shape: 'edge',
    data: { conditionExpr: '' },
    attrs: {
      // ... 保持原有 attrs 不变
    },
    router: { name: 'manhattan' },
    connector: { name: 'rounded', args: { radius: 8 } },
  })
}
  • Step 4: 添加同步连线条件数据到 graph edge 的函数

在 syncNodeLabel 函数后面添加:

// 同步条件表达式到 edge 并更新标签
function syncEdgeCondition() {
  if (!selectedEdge.value || !graph) return
  const edge = graph.getCellById(selectedEdge.value.id)
  if (!edge || !edge.isEdge()) return

  if (selectedEdge.value.isDefault) {
    edge.setData({ ...edge.getData(), conditionExpr: '' })
    edge.setLabels([])
  } else {
    const rules = selectedEdge.value.rules
      .filter((r) => r.field.trim())
      .map((r) => ({ field: r.field, op: r.op, value: r.value }))
    const expr = JSON.stringify({ rules })
    edge.setData({ ...edge.getData(), conditionExpr: expr })
    // 设置标签显示条件摘要
    const summary = rules.map((r) => `${r.field} ${r.op} ${r.value}`).join(' & ')
    edge.setLabels([
      {
        attrs: {
          label: {
            text: summary || '条件',
            fill: '#374151',
            fontSize: 11,
            textAnchor: 'middle',
            textVerticalAnchor: 'bottom',
          },
          rect: {
            fill: '#fff',
            stroke: '#d1d5db',
            strokeWidth: 1,
            rx: 4,
            ry: 4,
          },
        },
        position: {
          distance: 0.5,
        },
      },
    ])
  }
}
  • Step 5: 修改序列化函数,从 edge data 读取 conditionExpr

当前 serializeGraph() 已经正确读取 e.getData()?.conditionExpr(line 670),无需修改。确认即可。

  • Step 6: 修改模板 — 右侧属性面板增加连线编辑状态

在模板的 <aside class="props-panel"> 中(line 60-138),修改三态逻辑:

将原来的 <template v-if="selectedNode"> ... <template v-else> 结构改为三态:

<!-- 右侧属性面板 -->
<aside class="props-panel">
  <!-- 节点选中状态 -->
  <template v-if="selectedNode">
    <div class="panel-section-title">节点属性</div>
    <el-form label-position="top" class="props-form">
      <!-- ... 保持原有节点属性表单不变 (lines 64-132) ... -->
    </el-form>
  </template>

  <!-- 连线选中状态(条件编辑) -->
  <template v-else-if="selectedEdge">
    <div class="panel-section-title">连线条件</div>
    <div class="edge-info">
      <span class="edge-from">{{ selectedEdge.fromNodeName }}</span>
      <span class="edge-arrow">→</span>
      <span class="edge-to">{{ selectedEdge.toNodeName }}</span>
    </div>

    <el-form label-position="top" class="props-form" style="margin-top: 12px">
      <el-form-item>
        <el-checkbox v-model="selectedEdge.isDefault" @change="syncEdgeCondition">
          默认分支(无条件,其他分支都不满足时走此路径)
        </el-checkbox>
      </el-form-item>

      <template v-if="!selectedEdge.isDefault">
        <div v-for="(rule, idx) in selectedEdge.rules" :key="idx" class="condition-rule-row">
          <el-input v-model="rule.field" placeholder="字段名" style="width: 30%" @input="syncEdgeCondition" />
          <el-select v-model="rule.op" style="width: 22%" @change="syncEdgeCondition">
            <el-option label="==" value="==" />
            <el-option label="!=" value="!=" />
            <el-option label=">" value=">" />
            <el-option label="<" value="<" />
            <el-option label=">=" value=">=" />
            <el-option label="<=" value="<=" />
            <el-option label="in" value="in" />
            <el-option label="not_in" value="not_in" />
            <el-option label="contains" value="contains" />
          </el-select>
          <el-input v-model="rule.value" placeholder="值" style="width: 30%" @input="syncEdgeCondition" />
          <el-button
            :icon="selectedEdge.rules.length > 1 ? 'Delete' : undefined"
            text
            type="danger"
            @click="removeConditionRule(idx)"
          />
        </div>
        <el-button type="primary" link @click="addConditionRule">+ 添加条件</el-button>
      </template>
    </el-form>
  </template>

  <!-- 空状态 -->
  <template v-else>
    <div class="panel-section-title">属性</div>
    <div class="empty-hint">点击画布中的节点或连线查看属性</div>
  </template>
</aside>
  • Step 7: 添加条件规则操作函数

在 syncEdgeCondition 函数后面添加:

function addConditionRule() {
  if (selectedEdge.value) {
    selectedEdge.value.rules.push({ field: '', op: '==', value: '' })
  }
}

function removeConditionRule(idx: number) {
  if (selectedEdge.value && selectedEdge.value.rules.length > 1) {
    selectedEdge.value.rules.splice(idx, 1)
    syncEdgeCondition()
  }
}
  • Step 8: 添加条件编辑面板的 CSS

在 <style scoped lang="scss"> 块中添加:

.edge-info {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  background: #f9fafb;
  border-radius: 6px;
  font-size: 13px;
  color: #374151;
}

.edge-from {
  font-weight: 500;
}

.edge-arrow {
  color: #9ca3af;
}

.edge-to {
  font-weight: 500;
}

.condition-rule-row {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}
  • Step 9: 更新操作提示列表

在左侧面板的操作提示(line 46-51)中,添加连线相关的提示:

<li>点击连线编辑条件规则</li>

添加在 "从节点连接点拖出连线" 后面。


Task 4: SQL 模式帮助提示

Files:

  • Modify: web-admin/src/views/system/workflow/designer/FlowDesigner.vue

  • Step 1: 在 SQL textarea 下方添加帮助提示

将原有的 SQL textarea(约 line 111-118)修改为:

<el-form-item v-if="selectedNode.config.strategy === 'sql'" label="SQL查询语句">
  <el-input
    v-model="selectedNode.config.sqlExpr"
    type="textarea"
    :rows="4"
    placeholder="SELECT user_id FROM sys_user WHERE ..."
  />
  <div class="sql-help">
    <p><strong>SQL审批人策略说明:</strong></p>
    <ul>
      <li>必须以 <code>SELECT</code> 开头,只允许只读查询</li>
      <li>查询结果第一列将作为审批人 user_id</li>
      <li>可使用流程变量作为参数:<code>:var_name</code> 占位符</li>
      <li>禁止 INSERT / UPDATE / DELETE / DROP 等写操作</li>
    </ul>
    <p class="sql-example">示例:<code>SELECT id FROM sys_user WHERE dept_id = :dept_id AND del_flag = 0</code></p>
  </div>
</el-form-item>
  • Step 2: 添加 SQL 帮助样式

在 scoped style 中添加:

.sql-help {
  margin-top: 8px;
  padding: 10px 12px;
  background: #f0fdf4;
  border: 1px solid #bbf7d0;
  border-radius: 6px;
  font-size: 12px;
  color: #374151;
  line-height: 1.6;

  p {
    margin: 0 0 4px;
  }

  ul {
    margin: 4px 0;
    padding-left: 18px;
  }

  li {
    margin-bottom: 2px;
  }

  code {
    background: #e0f2fe;
    padding: 1px 4px;
    border-radius: 3px;
    font-size: 11px;
    color: #0369a1;
  }
}

.sql-example {
  margin-top: 6px !important;
  color: #059669;
}

Task 5: 验证

  • Step 1: 后端验证
cd /Users/wuzilong/work/00code/zkxw/backend && source venv/bin/activate && python -c "from app.api.admin import router; print('OK')"

Expected: OK

  • Step 2: 前端 build 验证
cd /Users/wuzilong/work/00code/zkxw/web-admin && pnpm build

Expected: Build 成功,无新增错误

  • Step 3: LSP 诊断

对 FlowDesigner.vue 运行 lsp_diagnostics,确认无类型错误。