index.vue 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978
  1. <template>
  2. <div class="designer-container">
  3. <!-- 流程信息栏(新增/编辑模式显示) -->
  4. <div v-if="flowInfoVisible" class="flow-info-bar">
  5. <el-tag v-if="mode === 'create'" type="primary">新增流程</el-tag>
  6. <el-tag v-else-if="mode === 'edit'" type="warning">编辑流程</el-tag>
  7. <span class="flow-info-item"><strong>编码:</strong>{{ flowCode }}</span>
  8. <span class="flow-info-item"><strong>名称:</strong>{{ flowName }}</span>
  9. <span v-if="flowCategory" class="flow-info-item"><strong>分类:</strong>{{ flowCategory }}</span>
  10. </div>
  11. <div class="node-panel">
  12. <div class="panel-title">节点类型</div>
  13. <div
  14. v-for="node in nodeTypes"
  15. :key="node.type"
  16. class="node-item"
  17. draggable="true"
  18. @dragstart="handleDragStart($event, node)"
  19. >
  20. <div class="node-icon" :style="{ backgroundColor: node.color }">
  21. <el-icon><component :is="node.icon" /></el-icon>
  22. </div>
  23. <div class="node-name">{{ node.label }}</div>
  24. </div>
  25. </div>
  26. <div class="canvas-area" @drop="handleDrop" @dragover.prevent>
  27. <div ref="lfContainer" class="lf-container" />
  28. <div class="toolbar">
  29. <el-button type="primary" size="small" @click="handleSave">保存</el-button>
  30. <el-button size="small" @click="handleClear">清空</el-button>
  31. <el-button size="small" @click="goBack">返回</el-button>
  32. </div>
  33. </div>
  34. <div class="property-panel" v-if="selectedNode">
  35. <div class="panel-title">节点属性</div>
  36. <el-form label-width="80px" size="small">
  37. <el-form-item label="节点ID">
  38. <el-input v-model="selectedNode.id" disabled />
  39. </el-form-item>
  40. <el-form-item label="节点名称">
  41. <el-input v-model="nodeName" @blur="updateNodeName" />
  42. </el-form-item>
  43. <template v-if="selectedNode.type === 'approval-node'">
  44. <el-form-item label="审批员工">
  45. <el-select
  46. v-model="nodeProps.assigneeValue"
  47. filterable
  48. clearable
  49. placeholder="请选择审批角色中的成员"
  50. style="width: 100%"
  51. >
  52. <el-option
  53. v-for="role in roleList"
  54. :key="role.id"
  55. :label="role.roleName"
  56. :value="role.roleCode"
  57. />
  58. </el-select>
  59. </el-form-item>
  60. <el-form-item label="审批方式">
  61. <el-select v-model="nodeProps.approveMode" placeholder="请选择" style="width: 100%">
  62. <el-option label="或签(一人通过即可)" value="or" />
  63. <el-option label="会签(全部通过)" value="and" />
  64. </el-select>
  65. </el-form-item>
  66. <el-form-item label="审批时限">
  67. <el-input-number
  68. v-model="nodeProps.timeoutHours"
  69. :min="1"
  70. :max="720"
  71. :precision="0"
  72. placeholder="不填表示无限制"
  73. controls-position="right"
  74. style="width: 100%"
  75. />
  76. <div class="form-tip">单位:小时,为空则不计算超时</div>
  77. </el-form-item>
  78. <el-form-item label="超时动作">
  79. <el-select v-model="nodeProps.timeoutAction" placeholder="请选择" style="width: 100%">
  80. <el-option label="提醒" value="remind" />
  81. <el-option label="自动通过" value="pass" />
  82. <el-option label="自动驳回" value="reject" />
  83. </el-select>
  84. <div class="form-tip">目前仅实现「提醒」,自动通过/驳回预留</div>
  85. </el-form-item>
  86. </template>
  87. <template v-if="selectedNode.type === 'condition-node'">
  88. <el-form-item>
  89. <template #label>
  90. 条件表达式
  91. <el-tooltip placement="top" effect="dark" raw-content>
  92. <template #content>
  93. <div style="line-height: 1.8; max-width: 320px;">
  94. <div style="margin-bottom: 6px; font-weight: bold;">格式:字段名 运算符 值</div>
  95. <div>运算符:<code>==</code>&nbsp;<code>!=</code>&nbsp;<code>&gt;</code>&nbsp;<code>&lt;</code>&nbsp;<code>&gt;=</code>&nbsp;<code>&lt;=</code></div>
  96. <div style="margin-top: 4px;">示例:</div>
  97. <div><code>quantity &gt;= 10</code>&nbsp;&nbsp;数量 ≥ 10</div>
  98. <div><code>tradeTerms == "FOB"</code>&nbsp;&nbsp;贸易条款为FOB</div>
  99. <div><code>destCountry == "USA"</code>&nbsp;&nbsp;目的国为USA</div>
  100. <div style="margin-top: 4px; color: #e6a23c;">注意:条件不满足时走默认分支(无条件的连线)</div>
  101. </div>
  102. </template>
  103. <el-icon style="margin-left: 4px; cursor: help;"><QuestionFilled /></el-icon>
  104. </el-tooltip>
  105. </template>
  106. <el-input v-model="nodeProps.condition" type="textarea" placeholder="如: quantity >= 10" />
  107. </el-form-item>
  108. </template>
  109. <template v-if="selectedNode.type === 'cc-node'">
  110. <el-form-item label="抄送人">
  111. <el-select
  112. v-model="nodeProps.ccUsers"
  113. filterable
  114. clearable
  115. placeholder="请选择抄送人"
  116. style="width: 100%"
  117. >
  118. <el-option
  119. v-for="role in roleList"
  120. :key="role.id"
  121. :label="role.roleName"
  122. :value="role.roleCode"
  123. />
  124. </el-select>
  125. </el-form-item>
  126. </template>
  127. </el-form>
  128. </div>
  129. <div class="property-panel empty" v-else>
  130. <div class="panel-title">节点属性</div>
  131. <el-empty description="请选择节点" />
  132. </div>
  133. <!-- 保存确认弹窗(无模式时) -->
  134. <el-dialog v-model="saveDialogVisible" title="保存流程" width="600px">
  135. <el-form ref="saveFormRef" :model="saveForm" :rules="saveFormRules" label-width="100px">
  136. <el-form-item label="流程编码" prop="code">
  137. <el-input v-model="saveForm.code" />
  138. </el-form-item>
  139. <el-form-item label="流程名称" prop="name">
  140. <el-input v-model="saveForm.name" />
  141. </el-form-item>
  142. <el-form-item label="分类">
  143. <el-input v-model="saveForm.category" />
  144. </el-form-item>
  145. <el-form-item label="描述">
  146. <el-input v-model="saveForm.description" type="textarea" />
  147. </el-form-item>
  148. </el-form>
  149. <div class="form-fields-section">
  150. <div class="form-fields-header">
  151. <span class="form-fields-title">流程表单字段</span>
  152. <el-button type="primary" size="small" :icon="Delete" @click="addFormField">添加字段</el-button>
  153. </div>
  154. <el-table :data="formFields" size="small" border style="width: 100%">
  155. <el-table-column label="字段名" min-width="120">
  156. <template #default="{ $index }">
  157. <el-input v-model="formFields[$index].name" placeholder="英文标识" size="small" />
  158. </template>
  159. </el-table-column>
  160. <el-table-column label="显示名" min-width="120">
  161. <template #default="{ $index }">
  162. <el-input v-model="formFields[$index].label" placeholder="中文显示名" size="small" />
  163. </template>
  164. </el-table-column>
  165. <el-table-column label="类型" width="120">
  166. <template #default="{ $index }">
  167. <el-select v-model="formFields[$index].type" placeholder="类型" size="small" style="width: 100%">
  168. <el-option v-for="opt in fieldTypeOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
  169. </el-select>
  170. </template>
  171. </el-table-column>
  172. <el-table-column label="必填" width="70" align="center">
  173. <template #default="{ $index }">
  174. <el-checkbox v-model="formFields[$index].required" />
  175. </template>
  176. </el-table-column>
  177. <el-table-column label="多选" width="70" align="center">
  178. <template #default="{ $index }">
  179. <el-checkbox
  180. v-model="formFields[$index].multiple"
  181. :disabled="formFields[$index].type !== 'select'"
  182. />
  183. </template>
  184. </el-table-column>
  185. <el-table-column label="选项" width="90" align="center">
  186. <template #default="{ $index }">
  187. <el-button
  188. link
  189. type="primary"
  190. size="small"
  191. :disabled="formFields[$index].type !== 'select'"
  192. @click="openOptionDialog($index)"
  193. >
  194. 配置选项
  195. </el-button>
  196. </template>
  197. </el-table-column>
  198. <el-table-column label="操作" width="70" align="center">
  199. <template #default="{ $index }">
  200. <el-button link type="danger" size="small" @click="removeFormField($index)">删除</el-button>
  201. </template>
  202. </el-table-column>
  203. </el-table>
  204. <el-empty v-if="formFields.length === 0" description="暂无字段,点击上方按钮添加" :image-size="60" style="padding: 10px 0;" />
  205. </div>
  206. <template #footer>
  207. <el-button @click="saveDialogVisible = false">取消</el-button>
  208. <el-button type="primary" @click="submitSave">确认保存</el-button>
  209. </template>
  210. </el-dialog>
  211. <!-- 下拉选项配置弹窗 -->
  212. <el-dialog v-model="optionDialogVisible" title="配置下拉选项" width="500px">
  213. <div v-if="optionEditingField" class="option-edit-tip">
  214. 字段:{{ optionEditingField.label || optionEditingField.name }}
  215. <el-checkbox v-model="optionEditingField.multiple" style="margin-left: 16px;">允许多选</el-checkbox>
  216. </div>
  217. <el-table :data="optionList" size="small" border>
  218. <el-table-column label="显示文本" min-width="140">
  219. <template #default="{ $index }">
  220. <el-input v-model="optionList[$index].label" placeholder="显示文本" size="small" />
  221. </template>
  222. </el-table-column>
  223. <el-table-column label="选项值" min-width="140">
  224. <template #default="{ $index }">
  225. <el-input v-model="optionList[$index].value" placeholder="选项值" size="small" />
  226. </template>
  227. </el-table-column>
  228. <el-table-column label="操作" width="70" align="center">
  229. <template #default="{ $index }">
  230. <el-button link type="danger" size="small" @click="removeOption($index)">删除</el-button>
  231. </template>
  232. </el-table-column>
  233. </el-table>
  234. <el-button type="primary" size="small" style="margin-top: 12px;" @click="addOption">添加选项</el-button>
  235. <template #footer>
  236. <el-button @click="optionDialogVisible = false">取消</el-button>
  237. <el-button type="primary" @click="saveOptions">保存</el-button>
  238. </template>
  239. </el-dialog>
  240. </div>
  241. </template>
  242. <script setup lang="ts">
  243. import { ref, onMounted, onUnmounted, nextTick, reactive, computed } from 'vue'
  244. import { useRoute, useRouter } from 'vue-router'
  245. import LogicFlow, { RectNode, RectNodeModel, CircleNode, CircleNodeModel, PolygonNode, PolygonNodeModel } from '@logicflow/core'
  246. import { Menu, Snapshot } from '@logicflow/extension'
  247. import '@logicflow/core/dist/style/index.css'
  248. import '@logicflow/extension/lib/style/index.css'
  249. import { VideoPlay, User, Message, Operation, CircleCheck, QuestionFilled } from '@element-plus/icons-vue'
  250. import { ElMessage } from 'element-plus'
  251. import type { FormInstance, FormRules } from 'element-plus'
  252. import { listRole } from '@/api/system/role'
  253. import { addDefinition, updateDefinition, getDefinition } from '@/api/flow/definition'
  254. import type { Role } from '@/types/system'
  255. import type { FlowDefinition, FormField, FormFieldOption } from '@/types/flow'
  256. import { Delete } from '@element-plus/icons-vue'
  257. const route = useRoute()
  258. const router = useRouter()
  259. const lfContainer = ref<HTMLDivElement>()
  260. let lf: LogicFlow | null = null
  261. const mode = computed(() => (route.query.mode as string) || '')
  262. const flowId = computed(() => (route.query.id as string) || '')
  263. const flowCode = computed(() => (route.query.code as string) || '')
  264. const flowName = computed(() => (route.query.name as string) || '')
  265. const flowCategory = computed(() => (route.query.category as string) || '')
  266. const flowDescription = computed(() => (route.query.description as string) || '')
  267. const flowInfoVisible = computed(() => mode.value === 'create' || mode.value === 'edit')
  268. const selectedNode = ref<any>(null)
  269. const roleList = ref<Role[]>([])
  270. const nodeProps = reactive<Record<string, any>>({
  271. assigneeType: 'ROLE',
  272. assigneeValue: '',
  273. approveMode: 'or',
  274. timeoutHours: undefined as number | undefined,
  275. timeoutAction: 'remind',
  276. condition: '',
  277. ccUsers: ''
  278. })
  279. const nodeName = computed({
  280. get: () => selectedNode.value?.text?.value || '',
  281. set: (val: string) => {
  282. if (selectedNode.value) {
  283. selectedNode.value.text = { ...selectedNode.value.text, value: val }
  284. }
  285. }
  286. })
  287. const nodeTypes = [
  288. { type: 'start-node', label: '开始', icon: VideoPlay, color: '#67C23A' },
  289. { type: 'approval-node', label: '审批节点', icon: User, color: '#409EFF' },
  290. { type: 'cc-node', label: '抄送节点', icon: Message, color: '#E6A23C' },
  291. { type: 'condition-node', label: '条件节点', icon: Operation, color: '#909399' },
  292. { type: 'end-node', label: '结束', icon: CircleCheck, color: '#F56C6C' }
  293. ]
  294. function getDefaultProps(type: string) {
  295. if (type === 'approval-node') return { assigneeType: 'ROLE', assigneeValue: '', approveMode: 'or', timeoutHours: undefined, timeoutAction: 'remind' }
  296. if (type === 'condition-node') return { condition: '' }
  297. if (type === 'cc-node') return { ccUsers: '' }
  298. return {}
  299. }
  300. function saveCurrentNodeProps() {
  301. if (selectedNode.value && lf) {
  302. const type = selectedNode.value.type
  303. const defaultProps = getDefaultProps(type)
  304. // 只保存当前节点类型相关的属性,避免不同类型节点属性互相污染
  305. const props: Record<string, any> = JSON.parse(JSON.stringify(defaultProps))
  306. if (type === 'approval-node') {
  307. props.assigneeType = 'ROLE'
  308. props.assigneeValue = nodeProps.assigneeValue ?? ''
  309. props.approveMode = nodeProps.approveMode ?? 'or'
  310. props.timeoutHours = nodeProps.timeoutHours
  311. props.timeoutAction = nodeProps.timeoutAction ?? 'remind'
  312. } else if (type === 'condition-node') {
  313. props.condition = nodeProps.condition ?? ''
  314. } else if (type === 'cc-node') {
  315. props.ccUsers = nodeProps.ccUsers ?? ''
  316. }
  317. lf.setProperties(selectedNode.value.id, props)
  318. }
  319. }
  320. function loadNodeProps(data: any) {
  321. const props = data.properties || getDefaultProps(data.type)
  322. const cloned = JSON.parse(JSON.stringify(props))
  323. // 先重置为默认值,避免上一个节点的属性残留
  324. Object.assign(nodeProps, getDefaultProps(data.type))
  325. // 兼容旧格式:approver + approveType -> 新格式
  326. if (data.type === 'approval-node') {
  327. let assigneeType = 'ROLE'
  328. let assigneeValue = cloned.assigneeValue ?? ''
  329. let approveMode = cloned.approveMode ?? cloned.approveType ?? 'or'
  330. if (!cloned.assigneeValue && cloned.approver) {
  331. assigneeValue = cloned.approver
  332. }
  333. // 旧数据中的 USER/SELF/LEADER 不再支持,统一清空让用户重新选择员工角色
  334. if (cloned.assigneeType && cloned.assigneeType !== 'ROLE') {
  335. assigneeValue = ''
  336. }
  337. nodeProps.assigneeType = assigneeType
  338. nodeProps.assigneeValue = assigneeValue
  339. nodeProps.approveMode = approveMode
  340. nodeProps.timeoutHours = cloned.timeoutHours ?? undefined
  341. nodeProps.timeoutAction = cloned.timeoutAction ?? 'remind'
  342. } else if (data.type === 'condition-node') {
  343. nodeProps.condition = cloned.condition ?? ''
  344. } else if (data.type === 'cc-node') {
  345. nodeProps.ccUsers = cloned.ccUsers ?? ''
  346. }
  347. }
  348. function registerNodes() {
  349. if (!lf) return
  350. class StartNodeModel extends CircleNodeModel {
  351. setAttributes() {
  352. this.r = 30
  353. if (!this.text.value) this.text.value = '开始'
  354. }
  355. getNodeStyle() {
  356. const style = super.getNodeStyle()
  357. style.fill = '#67C23A'
  358. style.stroke = '#67C23A'
  359. return style
  360. }
  361. getTextStyle() {
  362. const style = super.getTextStyle()
  363. style.color = '#fff'
  364. return style
  365. }
  366. }
  367. lf.register({ type: 'start-node', view: CircleNode, model: StartNodeModel })
  368. class ApprovalNodeModel extends RectNodeModel {
  369. setAttributes() {
  370. this.width = 160
  371. this.height = 60
  372. this.radius = 8
  373. if (!this.text.value) this.text.value = '审批节点'
  374. }
  375. getNodeStyle() {
  376. const style = super.getNodeStyle()
  377. style.fill = '#fff'
  378. style.stroke = '#409EFF'
  379. style.strokeWidth = 1
  380. return style
  381. }
  382. }
  383. lf.register({ type: 'approval-node', view: RectNode, model: ApprovalNodeModel })
  384. class CcNodeModel extends RectNodeModel {
  385. setAttributes() {
  386. this.width = 160
  387. this.height = 60
  388. this.radius = 8
  389. if (!this.text.value) this.text.value = '抄送节点'
  390. }
  391. getNodeStyle() {
  392. const style = super.getNodeStyle()
  393. style.fill = '#fff'
  394. style.stroke = '#E6A23C'
  395. style.strokeWidth = 1
  396. return style
  397. }
  398. }
  399. lf.register({ type: 'cc-node', view: RectNode, model: CcNodeModel })
  400. class ConditionNodeModel extends PolygonNodeModel {
  401. setAttributes() {
  402. this.points = [[60, 0], [120, 40], [60, 80], [0, 40]]
  403. if (!this.text.value) this.text.value = '条件'
  404. }
  405. getNodeStyle() {
  406. const style = super.getNodeStyle()
  407. style.fill = '#fff'
  408. style.stroke = '#909399'
  409. return style
  410. }
  411. }
  412. lf.register({ type: 'condition-node', view: PolygonNode, model: ConditionNodeModel })
  413. class EndNodeModel extends CircleNodeModel {
  414. setAttributes() {
  415. this.r = 30
  416. if (!this.text.value) this.text.value = '结束'
  417. }
  418. getNodeStyle() {
  419. const style = super.getNodeStyle()
  420. style.fill = '#F56C6C'
  421. style.stroke = '#F56C6C'
  422. return style
  423. }
  424. getTextStyle() {
  425. const style = super.getTextStyle()
  426. style.color = '#fff'
  427. return style
  428. }
  429. }
  430. lf.register({ type: 'end-node', view: CircleNode, model: EndNodeModel })
  431. }
  432. function initLogicFlow() {
  433. if (!lfContainer.value) return
  434. lf = new LogicFlow({
  435. container: lfContainer.value,
  436. grid: true,
  437. plugins: [Menu, Snapshot],
  438. pluginsOptions: {
  439. menu: {
  440. nodeMenu: [{
  441. text: '删除',
  442. callback(node: any) { lf?.deleteNode(node.id) }
  443. }]
  444. }
  445. } as any
  446. })
  447. registerNodes()
  448. lf.on('node:click', ({ data }: any) => {
  449. saveCurrentNodeProps()
  450. selectedNode.value = data
  451. loadNodeProps(data)
  452. })
  453. lf.on('blank:click', () => {
  454. saveCurrentNodeProps()
  455. selectedNode.value = null
  456. })
  457. // 编辑模式:加载已有流程图
  458. if (mode.value === 'edit' && flowId.value) {
  459. getDefinition(Number(flowId.value)).then((def: FlowDefinition) => {
  460. parseFormSchema(def.formSchema)
  461. if (def.flowJson) {
  462. try {
  463. const parsed = JSON.parse(def.flowJson)
  464. console.log('[designer] flowJson parsed, nodes:', parsed.nodes?.length, 'edges:', parsed.edges?.length)
  465. const graphData = convertToFrontendFormat(parsed)
  466. console.log('[designer] after convert, first node:', JSON.stringify(graphData.nodes?.[0]))
  467. lf?.render(graphData)
  468. console.log('[designer] render done, lf graphData nodes:', (lf as any)?.getGraphData?.()?.nodes?.length)
  469. } catch (e) {
  470. console.error('[designer] render error:', e)
  471. lf?.render({ nodes: defaultNodes(), edges: [] })
  472. }
  473. } else {
  474. console.warn('[designer] flowJson is empty')
  475. lf?.render({ nodes: defaultNodes(), edges: [] })
  476. }
  477. }).catch((e) => {
  478. console.error('[designer] getDefinition error:', e)
  479. lf?.render({ nodes: defaultNodes(), edges: [] })
  480. })
  481. } else {
  482. console.log('[designer] create mode, rendering defaults')
  483. lf.render({ nodes: defaultNodes(), edges: [] })
  484. }
  485. }
  486. function defaultNodes() {
  487. return [
  488. { id: 'start-1', type: 'start-node', x: 200, y: 100, text: '开始' },
  489. { id: 'end-1', type: 'end-node', x: 200, y: 500, text: '结束' }
  490. ]
  491. }
  492. // 节点类型映射:LogicFlow <-> 后端
  493. const typeToBackend: Record<string, string> = {
  494. 'start-node': 'start',
  495. 'approval-node': 'approval',
  496. 'cc-node': 'cc',
  497. 'condition-node': 'condition',
  498. 'end-node': 'end'
  499. }
  500. const typeToFrontend: Record<string, string> = {
  501. 'start': 'start-node',
  502. 'approval': 'approval-node',
  503. 'cc': 'cc-node',
  504. 'condition': 'condition-node',
  505. 'end': 'end-node'
  506. }
  507. // 将 LogicFlow 的 graphData 转换为后端格式
  508. function convertToBackendFormat(graphData: any) {
  509. const data = JSON.parse(JSON.stringify(graphData))
  510. if (data.nodes) {
  511. data.nodes = data.nodes.map((node: any) => {
  512. const n = { ...node }
  513. if (n.type && typeToBackend[n.type]) {
  514. n.type = typeToBackend[n.type]
  515. }
  516. // text -> name
  517. if (n.text !== undefined) {
  518. n.name = typeof n.text === 'object' ? n.text.value : n.text
  519. delete n.text
  520. }
  521. return n
  522. })
  523. }
  524. // edges 保持原样,properties 中的 condition 会在后端解析
  525. return data
  526. }
  527. // 将后端的 graphData 转换为 LogicFlow 格式
  528. function convertToFrontendFormat(graphData: any) {
  529. const data = JSON.parse(JSON.stringify(graphData))
  530. if (data.nodes) {
  531. data.nodes = data.nodes.map((node: any) => {
  532. const n = { ...node }
  533. if (n.type && typeToFrontend[n.type]) {
  534. n.type = typeToFrontend[n.type]
  535. }
  536. // name -> text
  537. if (n.name !== undefined) {
  538. n.text = n.name
  539. delete n.name
  540. }
  541. return n
  542. })
  543. }
  544. return data
  545. }
  546. function handleDragStart(e: DragEvent, node: any) {
  547. const serializable = { type: node.type, label: node.label }
  548. e.dataTransfer?.setData('application/json', JSON.stringify(serializable))
  549. }
  550. function handleDrop(e: DragEvent) {
  551. e.preventDefault()
  552. const dataStr = e.dataTransfer?.getData('application/json')
  553. if (!dataStr || !lf) return
  554. const nodeData = JSON.parse(dataStr)
  555. const rect = lfContainer.value!.getBoundingClientRect()
  556. lf.addNode({
  557. type: nodeData.type,
  558. x: e.clientX - rect.left,
  559. y: e.clientY - rect.top,
  560. text: nodeData.label
  561. })
  562. }
  563. function updateNodeName() {
  564. if (!lf || !selectedNode.value) return
  565. lf.setNodeText(selectedNode.value.id, nodeName.value)
  566. }
  567. // 保存流程
  568. const saveDialogVisible = ref(false)
  569. const saveFormRef = ref<FormInstance>()
  570. const saveForm = reactive({
  571. code: '',
  572. name: '',
  573. category: '',
  574. description: ''
  575. })
  576. const saveFormRules: FormRules = {
  577. code: [{ required: true, message: '请输入流程编码', trigger: 'blur' }],
  578. name: [{ required: true, message: '请输入流程名称', trigger: 'blur' }]
  579. }
  580. const formFields = ref<FormField[]>([])
  581. const fieldTypeOptions = [
  582. { label: '文本', value: 'text' },
  583. { label: '多行文本', value: 'textarea' },
  584. { label: '数字', value: 'number' },
  585. { label: '日期', value: 'date' },
  586. { label: '下拉选择', value: 'select' }
  587. ]
  588. function addFormField() {
  589. formFields.value.push({ name: '', label: '', type: 'text', required: false })
  590. }
  591. function removeFormField(index: number) {
  592. formFields.value.splice(index, 1)
  593. }
  594. function getFormSchema(): string {
  595. const validFields = formFields.value.filter(f => f.name.trim() && f.label.trim())
  596. return validFields.length > 0 ? JSON.stringify(validFields) : ''
  597. }
  598. function parseFormSchema(schema?: string) {
  599. if (!schema) return
  600. try {
  601. const parsed = JSON.parse(schema)
  602. if (Array.isArray(parsed)) {
  603. formFields.value = parsed
  604. }
  605. } catch {
  606. formFields.value = []
  607. }
  608. }
  609. // 下拉选项编辑
  610. const optionDialogVisible = ref(false)
  611. const optionEditingIndex = ref<number | null>(null)
  612. const optionEditingField = ref<FormField | null>(null)
  613. const optionList = ref<FormFieldOption[]>([])
  614. function openOptionDialog(index: number) {
  615. optionEditingIndex.value = index
  616. optionEditingField.value = formFields.value[index]
  617. const rawOptions = optionEditingField.value.options || []
  618. optionList.value = rawOptions.map((opt: any) => {
  619. if (typeof opt === 'string') {
  620. return { label: opt, value: opt }
  621. }
  622. return { label: String(opt.label ?? opt.value), value: opt.value }
  623. })
  624. optionDialogVisible.value = true
  625. }
  626. function addOption() {
  627. optionList.value.push({ label: '', value: '' })
  628. }
  629. function removeOption(index: number) {
  630. optionList.value.splice(index, 1)
  631. }
  632. function saveOptions() {
  633. if (optionEditingIndex.value === null || !optionEditingField.value) return
  634. const validOptions = optionList.value.filter(opt => String(opt.label).trim() !== '' && String(opt.value).trim() !== '')
  635. formFields.value[optionEditingIndex.value].options = validOptions
  636. formFields.value[optionEditingIndex.value].multiple = optionEditingField.value.multiple
  637. optionDialogVisible.value = false
  638. }
  639. function validateFlow(graphData: any): string | null {
  640. const nodes = graphData.nodes || []
  641. const edges = graphData.edges || []
  642. if (nodes.length === 0) return '流程图不能为空'
  643. const startNodes = nodes.filter((n: any) => n.type === 'start-node' || n.type === 'start')
  644. const endNodes = nodes.filter((n: any) => n.type === 'end-node' || n.type === 'end')
  645. if (startNodes.length === 0) return '流程图缺少开始节点'
  646. if (endNodes.length === 0) return '流程图缺少结束节点'
  647. if (startNodes.length > 1) return '流程图只能有一个开始节点'
  648. // 检查审批节点是否选择了审批角色
  649. for (const node of nodes) {
  650. if (node.type === 'approval-node' || node.type === 'approval') {
  651. const props = node.properties || {}
  652. const assigneeValue = props.assigneeValue || props.approver
  653. if (!assigneeValue) {
  654. return `审批节点 "${node.text || node.name}" 未选择审批角色`
  655. }
  656. }
  657. }
  658. // 检查孤立节点
  659. const connectedNodeIds = new Set<string>()
  660. for (const edge of edges) {
  661. connectedNodeIds.add(edge.sourceNodeId)
  662. connectedNodeIds.add(edge.targetNodeId)
  663. }
  664. for (const node of nodes) {
  665. if (!connectedNodeIds.has(node.id) && node.type !== 'start-node' && node.type !== 'start' && node.type !== 'end-node' && node.type !== 'end') {
  666. return `节点 "${node.text || node.name}" 是孤立节点,请删除或连接`
  667. }
  668. }
  669. // 检查条件分支是否有默认分支
  670. const sourceMap: Record<string, any[]> = {}
  671. for (const edge of edges) {
  672. if (!sourceMap[edge.sourceNodeId]) sourceMap[edge.sourceNodeId] = []
  673. sourceMap[edge.sourceNodeId].push(edge)
  674. }
  675. for (const node of nodes) {
  676. if (node.type === 'condition-node' || node.type === 'condition') {
  677. const outEdges = sourceMap[node.id] || []
  678. if (outEdges.length > 1) {
  679. const hasDefault = outEdges.some((e: any) => !e.properties?.condition && !e.condition)
  680. if (!hasDefault) {
  681. return `条件节点 "${node.text || node.name}" 需要至少一条无条件的默认分支`
  682. }
  683. }
  684. }
  685. }
  686. return null
  687. }
  688. async function handleSave() {
  689. if (!lf) return
  690. saveCurrentNodeProps()
  691. const rawGraphData = lf.getGraphData()
  692. const error = validateFlow(rawGraphData)
  693. if (error) {
  694. ElMessage.warning(error)
  695. return
  696. }
  697. // 统一弹出保存弹窗,方便配置流程表单字段
  698. if (mode.value === 'create') {
  699. saveForm.code = flowCode.value
  700. saveForm.name = flowName.value
  701. saveForm.category = flowCategory.value
  702. saveForm.description = flowDescription.value
  703. formFields.value = []
  704. } else if (mode.value === 'edit' && flowId.value) {
  705. saveForm.code = flowCode.value
  706. saveForm.name = flowName.value
  707. saveForm.category = flowCategory.value
  708. saveForm.description = flowDescription.value
  709. // formFields 在编辑模式加载流程时已通过 parseFormSchema 填充
  710. } else {
  711. saveForm.code = ''
  712. saveForm.name = ''
  713. saveForm.category = ''
  714. saveForm.description = ''
  715. formFields.value = []
  716. }
  717. saveDialogVisible.value = true
  718. }
  719. async function submitSave() {
  720. const valid = await saveFormRef.value?.validate().catch(() => false)
  721. if (!valid) return
  722. if (!lf) return
  723. saveCurrentNodeProps()
  724. const rawGraphData = lf.getGraphData()
  725. const error = validateFlow(rawGraphData)
  726. if (error) {
  727. ElMessage.warning(error)
  728. return
  729. }
  730. const graphData = convertToBackendFormat(rawGraphData)
  731. if (mode.value === 'create') {
  732. const data: Partial<FlowDefinition> = {
  733. code: saveForm.code,
  734. name: saveForm.name,
  735. category: saveForm.category,
  736. description: saveForm.description,
  737. formSchema: getFormSchema(),
  738. flowJson: JSON.stringify(graphData),
  739. status: 0
  740. }
  741. await addDefinition(data)
  742. ElMessage.success('流程新增成功')
  743. saveDialogVisible.value = false
  744. router.push('/flow/definition')
  745. } else if (mode.value === 'edit' && flowId.value) {
  746. const data: Partial<FlowDefinition> = {
  747. id: Number(flowId.value),
  748. code: saveForm.code,
  749. name: saveForm.name,
  750. category: saveForm.category,
  751. description: saveForm.description,
  752. formSchema: getFormSchema(),
  753. flowJson: JSON.stringify(graphData)
  754. }
  755. const newId = await updateDefinition(data)
  756. if (newId !== Number(flowId.value)) {
  757. ElMessage.success('流程已创建为新版本,请重新发布')
  758. } else {
  759. ElMessage.success('流程修改成功')
  760. }
  761. saveDialogVisible.value = false
  762. router.push('/flow/definition')
  763. } else {
  764. const data: Partial<FlowDefinition> = {
  765. code: saveForm.code,
  766. name: saveForm.name,
  767. category: saveForm.category,
  768. description: saveForm.description,
  769. formSchema: getFormSchema(),
  770. flowJson: JSON.stringify(graphData),
  771. status: 0
  772. }
  773. await addDefinition(data)
  774. ElMessage.success('流程保存成功')
  775. saveDialogVisible.value = false
  776. router.push('/flow/definition')
  777. }
  778. }
  779. function handleClear() {
  780. if (!lf) return
  781. lf.clearData()
  782. selectedNode.value = null
  783. }
  784. function goBack() {
  785. router.push('/flow/definition')
  786. }
  787. async function loadRoles() {
  788. try {
  789. const res = await listRole({ pageNum: 1, pageSize: 100 })
  790. roleList.value = res.list
  791. } catch { /* ignore */ }
  792. }
  793. onMounted(() => {
  794. // 防止快速进入/离开设计器时重复创建 LogicFlow 实例(v1.x 无 destroy 方法)
  795. if (lf) {
  796. if (typeof lf.destroy === 'function') {
  797. lf.destroy()
  798. }
  799. lf = null
  800. }
  801. nextTick(initLogicFlow)
  802. loadRoles()
  803. })
  804. onUnmounted(() => {
  805. if (lf) {
  806. if (typeof lf.destroy === 'function') {
  807. lf.destroy()
  808. }
  809. lf = null
  810. }
  811. selectedNode.value = null
  812. })
  813. </script>
  814. <style scoped>
  815. .designer-container {
  816. display: flex;
  817. height: calc(100vh - 100px);
  818. background: #fff;
  819. }
  820. .flow-info-bar {
  821. position: absolute;
  822. top: 60px;
  823. left: 220px;
  824. right: 0;
  825. height: 40px;
  826. background: #f0f9ff;
  827. border-bottom: 1px solid #d9ecff;
  828. display: flex;
  829. align-items: center;
  830. gap: 16px;
  831. padding: 0 16px;
  832. z-index: 100;
  833. }
  834. .flow-info-item {
  835. font-size: 13px;
  836. color: #303133;
  837. }
  838. .node-panel {
  839. width: 200px;
  840. border-right: 1px solid #dcdfe6;
  841. padding: 16px;
  842. background: #fafafa;
  843. }
  844. .panel-title {
  845. font-size: 16px;
  846. font-weight: bold;
  847. margin-bottom: 16px;
  848. color: #303133;
  849. }
  850. .node-item {
  851. display: flex;
  852. align-items: center;
  853. padding: 12px;
  854. margin-bottom: 8px;
  855. border-radius: 6px;
  856. cursor: move;
  857. background: #fff;
  858. border: 1px solid #ebeef5;
  859. transition: all 0.2s;
  860. }
  861. .node-item:hover {
  862. box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  863. border-color: #c6e2ff;
  864. }
  865. .node-icon {
  866. width: 32px;
  867. height: 32px;
  868. border-radius: 50%;
  869. display: flex;
  870. align-items: center;
  871. justify-content: center;
  872. color: #fff;
  873. margin-right: 12px;
  874. }
  875. .node-name {
  876. font-size: 14px;
  877. color: #606266;
  878. }
  879. .canvas-area {
  880. flex: 1;
  881. position: relative;
  882. background: #f5f7fa;
  883. }
  884. .lf-container {
  885. width: 100%;
  886. height: 100%;
  887. }
  888. .toolbar {
  889. position: absolute;
  890. top: 16px;
  891. right: 16px;
  892. z-index: 10;
  893. }
  894. .property-panel {
  895. width: 300px;
  896. border-left: 1px solid #dcdfe6;
  897. padding: 16px;
  898. background: #fafafa;
  899. overflow-y: auto;
  900. }
  901. .property-panel.empty {
  902. display: flex;
  903. flex-direction: column;
  904. }
  905. .form-fields-section {
  906. margin-top: 16px;
  907. border-top: 1px solid #ebeef5;
  908. padding-top: 16px;
  909. }
  910. .form-fields-header {
  911. display: flex;
  912. justify-content: space-between;
  913. align-items: center;
  914. margin-bottom: 12px;
  915. }
  916. .form-fields-title {
  917. font-weight: bold;
  918. color: #303133;
  919. }
  920. </style>