!397 Vue3 工作流的预览版

Merge pull request !397 from 芋道源码/feature/vue3-bpm
This commit is contained in:
芋道源码 2023-02-04 13:01:04 +00:00 committed by Gitee
commit 5addbb23d2
No known key found for this signature in database
GPG Key ID: 173E9B9CA92EEF8F
117 changed files with 14359 additions and 1547 deletions

View File

@ -229,7 +229,7 @@ ps核心功能已经实现正在对接微信小程序中...
| 框架 | 说明 | 版本 | 学习指南 |
|---------------------------------------------------------------------------------------------|------------------|-------------|----------------------------------------------------------------|
| [Spring Boot](https://spring.io/projects/spring-boot) | 应用开发框架 | 2.7.7 | [文档](https://github.com/YunaiV/SpringBoot-Labs) |
| [Spring Boot](https://spring.io/projects/spring-boot) | 应用开发框架 | 2.7.8 | [文档](https://github.com/YunaiV/SpringBoot-Labs) |
| [MySQL](https://www.mysql.com/cn/) | 数据库服务器 | 5.7 / 8.0+ | |
| [Druid](https://github.com/alibaba/druid) | JDBC 连接池、监控组件 | 1.2.15 | [文档](http://www.iocoder.cn/Spring-Boot/datasource-pool/?yudao) |
| [MyBatis Plus](https://mp.baomidou.com/) | MyBatis 增强工具包 | 3.5.3.1 | [文档](http://www.iocoder.cn/Spring-Boot/MyBatis/?yudao) |

View File

@ -36,7 +36,7 @@
<opentracing.version>0.33.0</opentracing.version>
<!-- Test 测试相关 -->
<podam.version>7.2.11.RELEASE</podam.version>
<jedis-mock.version>1.0.5</jedis-mock.version>
<jedis-mock.version>1.0.6</jedis-mock.version>
<mockito-inline.version>4.11.0</mockito-inline.version>
<!-- Bpm 工作流相关 -->
<flowable.version>6.8.0</flowable.version>
@ -221,8 +221,6 @@
<version>${redisson.version}</version>
</dependency>
<!-- Config 配置中心相关 -->
<!-- Job 定时任务相关 -->
<dependency>
<groupId>cn.iocoder.boot</groupId>

View File

@ -1,6 +1,7 @@
package cn.iocoder.yudao.module.bpm.controller.admin.task.vo.task;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.date.DateUtils;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
@ -20,12 +21,8 @@ public class BpmTaskTodoPageReqVO extends PageParam {
@Schema(description = "流程任务名", example = "芋道")
private String name;
@Schema(description = "开始的创建收间")
@DateTimeFormat(pattern = FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND)
private LocalDateTime beginCreateTime;
@Schema(description = "结束的创建时间")
@DateTimeFormat(pattern = FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND)
private LocalDateTime endCreateTime;
@Schema(description = "创建时间")
@DateTimeFormat(pattern = DateUtils.FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND)
private LocalDateTime[] createTime;
}

View File

@ -3,7 +3,6 @@ package cn.iocoder.yudao.module.bpm.service.definition;
import cn.hutool.core.lang.Assert;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
import cn.iocoder.yudao.framework.common.util.validation.ValidationUtils;
import cn.iocoder.yudao.module.bpm.controller.admin.definition.vo.form.BpmFormCreateReqVO;
import cn.iocoder.yudao.module.bpm.controller.admin.definition.vo.form.BpmFormPageReqVO;
import cn.iocoder.yudao.module.bpm.controller.admin.definition.vo.form.BpmFormUpdateReqVO;
@ -107,17 +106,15 @@ public class BpmFormServiceImpl implements BpmFormService {
return null;
}
private void checkKeyNCName(String key) {
if (!ValidationUtils.isXmlNCName(key)) {
throw exception(MODEL_KEY_VALID);
}
}
/**
* 校验 Field避免 field 重复
*
* @param fields field 数组
*/
private void checkFields(List<String> fields) {
if (true) { // TODO 芋艿兼容 Vue3 工作流因为采用了新的表单设计器所以暂时不校验
return;
}
Map<String, String> fieldMap = new HashMap<>(); // key vModelvalue label
for (String field : fields) {
BpmFormFieldRespDTO fieldDTO = JsonUtils.parseObject(field, BpmFormFieldRespDTO.class);

View File

@ -1,6 +1,8 @@
package cn.iocoder.yudao.module.bpm.service.task;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.date.DateUtils;
@ -75,11 +77,11 @@ public class BpmTaskServiceImpl implements BpmTaskService {
if (StrUtil.isNotBlank(pageVO.getName())) {
taskQuery.taskNameLike("%" + pageVO.getName() + "%");
}
if (pageVO.getBeginCreateTime() != null) {
taskQuery.taskCreatedAfter(DateUtils.of(pageVO.getBeginCreateTime()));
if (ArrayUtil.get(pageVO.getCreateTime(), 0) != null) {
taskQuery.taskCreatedAfter(DateUtils.of(pageVO.getCreateTime()[0]));
}
if (pageVO.getEndCreateTime() != null) {
taskQuery.taskCreatedBefore(DateUtils.of(pageVO.getEndCreateTime()));
if (ArrayUtil.get(pageVO.getCreateTime(), 1) != null) {
taskQuery.taskCreatedBefore(DateUtils.of(pageVO.getCreateTime()[1]));
}
// 执行查询
List<Task> tasks = taskQuery.listPage(PageUtils.getStart(pageVO), pageVO.getPageSize());

View File

@ -24,40 +24,52 @@
"lint:pretty": "pretty-quick --staged"
},
"dependencies": {
"@iconify/iconify": "^3.0.1",
"@vueuse/core": "^9.11.0",
"@form-create/designer": "^3.1.0",
"@form-create/element-ui": "^3.1.17",
"@iconify/iconify": "^3.1.0",
"@vueuse/core": "^9.11.1",
"@wangeditor/editor": "^5.1.23",
"@wangeditor/editor-for-vue": "^5.1.10",
"@zxcvbn-ts/core": "^2.1.0",
"@zxcvbn-ts/core": "^2.2.0",
"animate.css": "^4.1.1",
"axios": "^1.2.3",
"axios": "^1.2.5",
"bpmn-js-token-simulation": "^0.10.0",
"camunda-bpmn-moddle": "^7.0.1",
"cropperjs": "^1.5.13",
"crypto-js": "^4.1.1",
"dayjs": "^1.11.7",
"diagram-js": "^11.6.0",
"echarts": "^5.4.1",
"echarts-wordcloud": "^2.1.0",
"element-plus": "2.2.28",
"fast-xml-parser": "^4.0.13",
"highlight.js": "^11.7.0",
"intro.js": "^6.0.0",
"jsencrypt": "^3.3.1",
"lodash-es": "^4.17.21",
"min-dash": "^4.0.0",
"mitt": "^3.0.0",
"nprogress": "^0.2.0",
"pinia": "^2.0.29",
"qrcode": "^1.5.1",
"qs": "^6.11.0",
"steady-xml": "^0.1.0",
"url": "^0.11.0",
"vue": "3.2.45",
"vue-i18n": "9.2.2",
"vue-router": "^4.1.6",
"vue-types": "^5.0.2",
"vue3-treeselect": "^0.1.10",
"vuedraggable": "^4.1.0",
"vxe-table": "^4.3.9",
"web-storage-cache": "^1.1.1",
"xe-utils": "^3.5.7"
"xe-utils": "^3.5.7",
"xml-js": "^1.6.11"
},
"devDependencies": {
"@commitlint/cli": "^17.4.2",
"@commitlint/config-conventional": "^17.4.2",
"@iconify/json": "^2.2.8",
"@iconify/json": "^2.2.13",
"@intlify/unplugin-vue-i18n": "^0.8.1",
"@purge-icons/generated": "^0.9.0",
"@types/intro.js": "^5.1.0",
@ -66,12 +78,14 @@
"@types/nprogress": "^0.2.0",
"@types/qrcode": "^1.5.0",
"@types/qs": "^6.9.7",
"@typescript-eslint/eslint-plugin": "^5.48.2",
"@typescript-eslint/parser": "^5.48.2",
"@vitejs/plugin-legacy": "^3.0.1",
"@typescript-eslint/eslint-plugin": "^5.49.0",
"@typescript-eslint/parser": "^5.49.0",
"@vitejs/plugin-legacy": "^3.0.2",
"@vitejs/plugin-vue": "^4.0.0",
"@vitejs/plugin-vue-jsx": "^3.0.0",
"autoprefixer": "^10.4.13",
"bpmn-js": "^8.9.0",
"bpmn-js-properties-panel": "^0.46.0",
"consola": "^2.15.3",
"eslint": "^8.32.0",
"eslint-config-prettier": "^8.6.0",
@ -83,8 +97,8 @@
"postcss-html": "^1.5.0",
"postcss-scss": "^4.0.6",
"prettier": "^2.8.3",
"rimraf": "^4.1.1",
"rollup": "^3.10.0",
"rimraf": "^4.1.2",
"rollup": "^3.11.0",
"sass": "^1.57.1",
"stylelint": "^14.16.1",
"stylelint-config-html": "^1.1.0",
@ -94,7 +108,7 @@
"stylelint-order": "^6.0.1",
"terser": "^5.16.1",
"typescript": "4.9.4",
"unplugin-auto-import": "^0.12.1",
"unplugin-auto-import": "^0.12.2",
"unplugin-element-plus": "^0.4.1",
"unplugin-vue-components": "^0.22.12",
"vite": "4.0.4",
@ -121,4 +135,4 @@
"url": "https://gitee.com/zhijiantianya/ruoyi-vue-pro/issues"
},
"homepage": "https://gitee.com/zhijiantianya/ruoyi-vue-pro"
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,8 @@
import request from '@/config/axios'
export const getActivityList = async (params) => {
return await request.get({
url: '/bpm/activity/list',
params
})
}

View File

@ -0,0 +1,21 @@
import request from '@/config/axios'
export const getProcessDefinitionBpmnXMLApi = async (id: number) => {
return await request.get({
url: '/bpm/process-definition/get-bpmn-xml?id=' + id
})
}
export const getProcessDefinitionPageApi = async (params) => {
return await request.get({
url: '/bpm/process-definition/page',
params
})
}
export const getProcessDefinitionListApi = async (params) => {
return await request.get({
url: '/bpm/process-definition/list',
params
})
}

View File

@ -1,5 +1,14 @@
import request from '@/config/axios'
import { FormVO } from './types'
export type FormVO = {
id: number
name: string
conf: string
fields: string[]
status: number
remark: string
createTime: string
}
// 创建工作流的表单定义
export const createFormApi = async (data: FormVO) => {

View File

@ -1,9 +0,0 @@
export type FormVO = {
id: number
name: string
conf: string
fields: string[]
status: number
remark: string
createTime: string
}

View File

@ -1,5 +1,15 @@
import request from '@/config/axios'
import { LeaveVO } from './types'
export type LeaveVO = {
id: number
result: number
type: number
reason: string
processInstanceId: string
startTime: string
endTime: string
createTime: string
}
// 创建请假申请
export const createLeaveApi = async (data: LeaveVO) => {

View File

@ -1,10 +0,0 @@
export type LeaveVO = {
id: number
result: number
type: number
reason: string
processInstanceId: string
startTime: string
endTime: string
createTime: string
}

View File

@ -1,5 +1,28 @@
import request from '@/config/axios'
import { ModelVO } from './types'
export type ProcessDefinitionVO = {
id: string
version: number
deploymentTIme: string
suspensionState: number
}
export type ModelVO = {
id: number
formName: string
key: string
name: string
description: string
category: string
formType: number
formId: number
formCustomCreatePath: string
formCustomViewPath: string
processDefinition: ProcessDefinitionVO
status: number
remark: string
createTime: string
}
export const getModelPageApi = async (params) => {
return await request.get({ url: '/bpm/model/page', params })

View File

@ -1,23 +0,0 @@
export type ProcessDefinitionVO = {
id: string
version: number
deploymentTIme: string
suspensionState: number
}
export type ModelVO = {
id: number
formName: string
key: string
name: string
description: string
category: string
formType: number
formId: number
formCustomCreatePath: string
formCustomViewPath: string
processDefinition: ProcessDefinitionVO
status: number
remark: string
createTime: string
}

View File

@ -1,11 +1,29 @@
import request from '@/config/axios'
import { ProcessInstanceVO } from './types'
export type Task = {
id: string
name: string
}
export type ProcessInstanceVO = {
id: number
name: string
processDefinitionId: string
category: string
result: number
tasks: Task[]
fields: string[]
status: number
remark: string
businessKey: string
createTime: string
endTime: string
}
export const getMyProcessInstancePageApi = async (params) => {
return await request.get({ url: '/bpm/process-instance/my-page', params })
}
export const createProcessInstanceApi = async (data: ProcessInstanceVO) => {
export const createProcessInstanceApi = async (data) => {
return await request.post({ url: '/bpm/process-instance/create', data: data })
}

View File

@ -1,18 +0,0 @@
export type task = {
id: string
name: string
}
export type ProcessInstanceVO = {
id: number
name: string
processDefinitionId: string
category: string
result: number
tasks: task[]
fields: string[]
status: number
remark: string
businessKey: string
createTime: string
endTime: string
}

View File

@ -1,39 +0,0 @@
export type FormVO = {
id: number
name: string
conf: string
fields: string[]
status: number
remark: string
createTime: string
}
export type TaskProcessVO = {
id: string
name: string
startUserId: number
startUserNickname: string
processDefinitionId: string
}
export type TaskTodoVO = {
id: string
name: string
claimTime: string
createTime: string
suspensionState: number
processInstance: TaskProcessVO
}
export type TaskDoneVO = {
id: string
name: string
claimTime: string
createTime: string
endTime: string
durationInMillis: number
suspensionState: number
result: number
reason: string
processInstance: TaskProcessVO
}

View File

@ -1,5 +1,14 @@
import request from '@/config/axios'
import { TaskAssignVO } from './types'
export type TaskAssignVO = {
id: number
modelId: string
processDefinitionId: string
taskDefinitionKey: string
taskDefinitionName: string
options: string[]
type: number
}
export const getTaskAssignRuleList = async (params) => {
return await request.get({ url: '/bpm/task-assign-rule/list', params })

View File

@ -1,9 +0,0 @@
export type TaskAssignVO = {
id: number
modelId: string
processDefinitionId: string
taskDefinitionKey: string
taskDefinitionName: string
options: string[]
type: number
}

View File

@ -1,5 +1,14 @@
import request from '@/config/axios'
import { UserGroupVO } from './types'
export type UserGroupVO = {
id: number
name: string
description: string
memberUserIds: number[]
status: number
remark: string
createTime: string
}
// 创建用户组
export const createUserGroupApi = async (data: UserGroupVO) => {

View File

@ -1,9 +0,0 @@
export type UserGroupVO = {
id: number
name: string
description: string
memberUserIds: number[]
status: number
remark: string
createTime: string
}

View File

@ -33,6 +33,9 @@ export default defineComponent({
if (!props.type) {
return null
}
if (!props.value) {
return null
}
getDictObj(props.type, props.value.toString())
return (
<ElTag

View File

@ -0,0 +1,690 @@
<template>
<div class="my-process-designer">
<div class="my-process-designer__header">
<slot name="control-header"></slot>
<template v-if="!$slots['control-header']">
<ElButtonGroup key="file-control">
<XButton preIcon="ep:folder-opened" title="打开文件" @click="refFile.click()" />
<el-tooltip effect="light" placement="bottom">
<template #content>
<div style="color: #409eff">
<!-- <el-button link @click="downloadProcessAsXml()">下载为XML文件</el-button> -->
<XTextButton title="下载为XML文件" @click="downloadProcessAsXml()" />
<br />
<!-- <el-button link @click="downloadProcessAsSvg()">下载为SVG文件</el-button> -->
<XTextButton title="下载为SVG文件" @click="downloadProcessAsSvg()" />
<br />
<!-- <el-button link @click="downloadProcessAsBpmn()">下载为BPMN文件</el-button> -->
<XTextButton title="下载为BPMN文件" @click="downloadProcessAsBpmn()" />
</div>
</template>
<XButton title="下载文件" preIcon="ep:download" />
</el-tooltip>
<el-tooltip effect="light">
<XButton preIcon="ep:view" title="浏览" />
<template #content>
<!-- <el-button link @click="previewProcessXML">预览XML</el-button> -->
<XTextButton title="预览XML" @click="previewProcessXML" />
<br />
<!-- <el-button link @click="previewProcessJson">预览JSON</el-button> -->
<XTextButton title="预览JSON" @click="previewProcessJson" />
</template>
</el-tooltip>
<el-tooltip
v-if="props.simulation"
effect="light"
:content="simulationStatus ? '退出模拟' : '开启模拟'"
>
<XButton preIcon="ep:cpu" title="模拟" @click="processSimulation" />
</el-tooltip>
</ElButtonGroup>
<ElButtonGroup key="align-control">
<el-tooltip effect="light" content="向左对齐">
<!-- <el-button
class="align align-left"
icon="el-icon-s-data"
@click="elementsAlign('left')"
/> -->
<XButton
preIcon="fa:align-left"
class="align align-bottom"
@click="elementsAlign('left')"
/>
</el-tooltip>
<el-tooltip effect="light" content="向右对齐">
<!-- <el-button
class="align align-right"
icon="el-icon-s-data"
@click="elementsAlign('right')"
/> -->
<XButton
preIcon="fa:align-left"
class="align align-top"
@click="elementsAlign('right')"
/>
</el-tooltip>
<el-tooltip effect="light" content="向上对齐">
<!-- <el-button
class="align align-top"
icon="el-icon-s-data"
@click="elementsAlign('top')"
/> -->
<XButton
preIcon="fa:align-left"
class="align align-left"
@click="elementsAlign('top')"
/>
</el-tooltip>
<el-tooltip effect="light" content="向下对齐">
<!-- <el-button
class="align align-bottom"
icon="el-icon-s-data"
@click="elementsAlign('bottom')"
/> -->
<XButton
preIcon="fa:align-left"
class="align align-right"
@click="elementsAlign('bottom')"
/>
</el-tooltip>
<el-tooltip effect="light" content="水平居中">
<!-- <el-button
class="align align-center"
icon="el-icon-s-data"
@click="elementsAlign('center')"
/> -->
<!-- class="align align-center" -->
<XButton
preIcon="fa:align-left"
class="align align-center"
@click="elementsAlign('center')"
/>
</el-tooltip>
<el-tooltip effect="light" content="垂直居中">
<!-- <el-button
class="align align-middle"
icon="el-icon-s-data"
@click="elementsAlign('middle')"
/> -->
<XButton
preIcon="fa:align-left"
class="align align-middle"
@click="elementsAlign('middle')"
/>
</el-tooltip>
</ElButtonGroup>
<ElButtonGroup key="scale-control">
<el-tooltip effect="light" content="缩小视图">
<!-- <el-button
:disabled="defaultZoom < 0.2"
icon="el-icon-zoom-out"
@click="processZoomOut()"
/> -->
<XButton
preIcon="ep:zoom-out"
@click="processZoomOut()"
:disabled="defaultZoom < 0.2"
/>
</el-tooltip>
<el-button>{{ Math.floor(defaultZoom * 10 * 10) + '%' }}</el-button>
<el-tooltip effect="light" content="放大视图">
<!-- <el-button
:disabled="defaultZoom > 4"
icon="el-icon-zoom-in"
@click="processZoomIn()"
/> -->
<XButton preIcon="ep:zoom-in" @click="processZoomIn()" :disabled="defaultZoom > 4" />
</el-tooltip>
<el-tooltip effect="light" content="重置视图并居中">
<!-- <el-button icon="el-icon-c-scale-to-original" @click="processReZoom()" /> -->
<XButton preIcon="ep:scale-to-original" @click="processReZoom()" />
</el-tooltip>
</ElButtonGroup>
<ElButtonGroup key="stack-control">
<el-tooltip effect="light" content="撤销">
<!-- <el-button :disabled="!revocable" icon="el-icon-refresh-left" @click="processUndo()" /> -->
<XButton preIcon="ep:refresh-left" @click="processUndo()" :disabled="!revocable" />
</el-tooltip>
<el-tooltip effect="light" content="恢复">
<!-- <el-button
:disabled="!recoverable"
icon="el-icon-refresh-right"
@click="processRedo()"
/> -->
<XButton preIcon="ep:refresh-right" @click="processRedo()" :disabled="!recoverable" />
</el-tooltip>
<el-tooltip effect="light" content="重新绘制">
<!-- <el-button icon="el-icon-refresh" @click="processRestart" /> -->
<XButton preIcon="ep:refresh" @click="processRestart()" />
</el-tooltip>
</ElButtonGroup>
<XButton
preIcon="ep:plus"
title="保存模型"
@click="processSave"
:type="props.headerButtonType"
:disabled="simulationStatus"
/>
</template>
<!-- 用于打开本地文件-->
<input
type="file"
id="files"
ref="refFile"
style="display: none"
accept=".xml, .bpmn"
@change="importLocalFile"
/>
</div>
<div class="my-process-designer__container">
<div
class="my-process-designer__canvas"
ref="bpmnCanvas"
id="bpmnCanvas"
style="width: 1680px; height: 800px"
></div>
<!-- <div id="js-properties-panel" class="panel"></div> -->
<!-- <div class="my-process-designer__canvas" ref="bpmn-canvas"></div> -->
</div>
<XModal title="预览" width="80%" height="90%" v-model="previewModelVisible" destroy-on-close>
<!-- append-to-body -->
<pre v-highlight>
<code class="hljs">
<!-- 高亮代码块 -->
{{ previewResult }}
</code>
</pre>
<!-- <pre>
<code class="hljs" v-html="highlightedCode(previewType, previewResult)"></code>
</pre> -->
</XModal>
</div>
</template>
<script setup lang="ts" name="MyProcessDesigner">
// import 'bpmn-js/dist/assets/diagram-js.css' //
// import 'bpmn-js/dist/assets/bpmn-font/css/bpmn.css'
// import 'bpmn-js/dist/assets/bpmn-font/css/bpmn-codes.css'
// import 'bpmn-js/dist/assets/bpmn-font/css/bpmn-embedded.css'
// import 'bpmn-js-properties-panel/dist/assets/bpmn-js-properties-panel.css' //
import { ElTooltip, ElButtonGroup, ElButton, ElMessage, ElMessageBox } from 'element-plus'
import { computed, onBeforeMount, onBeforeUnmount, onMounted, provide, ref } from 'vue'
import BpmnModeler from 'bpmn-js/lib/Modeler'
import DefaultEmptyXML from './plugins/defaultEmpty'
//
import customTranslate from './plugins/translate/customTranslate'
import translationsCN from './plugins/translate/zh'
//
import tokenSimulation from 'bpmn-js-token-simulation'
//
// import bpmnPropertiesProvider from "bpmn-js-properties-panel/lib/provider/bpmn";
// import propertiesPanelModule from 'bpmn-js-properties-panel'
// import propertiesProviderModule from 'bpmn-js-properties-panel/lib/provider/camunda'
// Moddle
import camundaModdleDescriptor from './plugins/descriptor/camundaDescriptor.json'
import activitiModdleDescriptor from './plugins/descriptor/activitiDescriptor.json'
import flowableModdleDescriptor from './plugins/descriptor/flowableDescriptor.json'
// Extension
import camundaModdleExtension from './plugins/extension-moddle/camunda'
import activitiModdleExtension from './plugins/extension-moddle/activiti'
import flowableModdleExtension from './plugins/extension-moddle/flowable'
// json
// import xml2js from 'xml-js'
import xml2js from 'fast-xml-parser'
import { XmlNode, XmlNodeType, parseXmlString } from 'steady-xml'
//
// import hljs from 'highlight.js/lib/highlight'
// import 'highlight.js/styles/github-gist.css'
// hljs.registerLanguage('xml', 'highlight.js/lib/languages/xml')
// hljs.registerLanguage('json', 'highlight.js/lib/languages/json')
// const eventName = reactive({
// name: ''
// })
const bpmnCanvas = ref()
const refFile = ref()
const emit = defineEmits([
'destroy',
'init-finished',
'save',
'commandStack-changed',
'input',
'change',
'canvas-viewbox-changed',
// eventName.name
'element-click'
])
const props = defineProps({
value: String, // xml
// valueWatch: true, // xml watch
processId: String, // key
processName: String, // name
formId: Number, // form
translations: Object, //
additionalModel: [Object, Array], // model
moddleExtension: Object, // moddle
onlyCustomizeAddi: {
type: Boolean,
default: false
},
onlyCustomizeModdle: {
type: Boolean,
default: false
},
simulation: {
type: Boolean,
default: true
},
keyboard: {
type: Boolean,
default: true
},
prefix: {
type: String,
default: 'camunda'
},
events: {
type: Array,
default: () => ['element.click']
},
headerButtonSize: {
type: String,
default: 'small',
validator: (value) => ['default', 'medium', 'small', 'mini'].indexOf(value) !== -1
},
headerButtonType: {
type: String,
default: 'primary',
validator: (value) =>
['default', 'primary', 'success', 'warning', 'danger', 'info'].indexOf(value) !== -1
}
})
provide('configGlobal', props)
let bpmnModeler = null
const defaultZoom = ref(1)
const previewModelVisible = ref(false)
const simulationStatus = ref(false)
const previewResult = ref('')
const previewType = ref('xml')
const recoverable = ref(false)
const revocable = ref(false)
const additionalModules = computed(() => {
console.log(props.additionalModel, 'additionalModel')
const Modules = []
//
if (props.onlyCustomizeAddi) {
if (Object.prototype.toString.call(props.additionalModel) == '[object Array]') {
return props.additionalModel || []
}
return [props.additionalModel]
}
//
if (Object.prototype.toString.call(props.additionalModel) == '[object Array]') {
Modules.push(...props.additionalModel)
} else {
props.additionalModel && Modules.push(props.additionalModel)
}
//
const TranslateModule = {
translate: ['value', customTranslate(props.translations || translationsCN)]
}
Modules.push(TranslateModule)
//
if (props.simulation) {
Modules.push(tokenSimulation)
}
//
// if (this.prefix === "bpmn") {
// Modules.push(bpmnModdleExtension);
// }
console.log(props.prefix, 'props.prefix ')
if (props.prefix === 'camunda') {
Modules.push(camundaModdleExtension)
}
if (props.prefix === 'flowable') {
Modules.push(flowableModdleExtension)
}
if (props.prefix === 'activiti') {
Modules.push(activitiModdleExtension)
}
return Modules
})
const moddleExtensions = computed(() => {
console.log(props.onlyCustomizeModdle, 'props.onlyCustomizeModdle')
console.log(props.moddleExtension, 'props.moddleExtension')
console.log(props.prefix, 'props.prefix')
const Extensions = {}
// 使
if (props.onlyCustomizeModdle) {
return props.moddleExtension || null
}
//
if (props.moddleExtension) {
for (let key in props.moddleExtension) {
Extensions[key] = props.moddleExtension[key]
}
}
// ""
if (props.prefix === 'activiti') {
Extensions.activiti = activitiModdleDescriptor
}
if (props.prefix === 'flowable') {
Extensions.flowable = flowableModdleDescriptor
}
if (props.prefix === 'camunda') {
Extensions.camunda = camundaModdleDescriptor
}
return Extensions
})
console.log(additionalModules, 'additionalModules()')
console.log(moddleExtensions, 'moddleExtensions()')
const initBpmnModeler = () => {
if (bpmnModeler) return
let data = document.getElementById('bpmnCanvas')
console.log(data, 'data')
console.log(props.keyboard, 'props.keyboard')
console.log(additionalModules, 'additionalModules()')
console.log(moddleExtensions, 'moddleExtensions()')
bpmnModeler = new BpmnModeler({
// container: this.$refs['bpmn-canvas'],
// container: getCurrentInstance(),
// container: needClass,
// container: bpmnCanvas.value,
container: data,
// width: '100%',
//
// propertiesPanel: {
// parent: '#js-properties-panel'
// },
keyboard: props.keyboard ? { bindTo: document } : null,
// additionalModules: additionalModules.value,
additionalModules: additionalModules.value,
moddleExtensions: moddleExtensions.value
// additionalModules: [
// additionalModules.value
// propertiesPanelModule,
// propertiesProviderModule
// propertiesProviderModule
// ],
// moddleExtensions: { camunda: moddleExtensions.value }
})
// bpmnModeler.createDiagram()
console.log(bpmnModeler, 'bpmnModeler111111')
emit('init-finished', bpmnModeler)
initModelListeners()
}
const initModelListeners = () => {
const EventBus = bpmnModeler.get('eventBus')
console.log(EventBus, 'EventBus')
// , . - ,
props.events.forEach((event) => {
EventBus.on(event, function (eventObj) {
let eventName = event.replace(/\./g, '-')
// eventName.name = eventName
let element = eventObj ? eventObj.element : null
console.log(eventName, 'eventName')
console.log(element, 'element')
emit('element-click', element, eventObj)
// emit(eventName, element, eventObj)
})
})
// xml
EventBus.on('commandStack.changed', async (event) => {
try {
recoverable.value = bpmnModeler.get('commandStack').canRedo()
revocable.value = bpmnModeler.get('commandStack').canUndo()
let { xml } = await bpmnModeler.saveXML({ format: true })
emit('commandStack-changed', event)
emit('input', xml)
emit('change', xml)
} catch (e) {
console.error(`[Process Designer Warn]: ${e.message || e}`)
}
})
//
bpmnModeler.on('canvas.viewbox.changed', ({ viewbox }) => {
emit('canvas-viewbox-changed', { viewbox })
const { scale } = viewbox
defaultZoom.value = Math.floor(scale * 100) / 100
})
}
/* 创建新的流程图 */
const createNewDiagram = async (xml) => {
console.log(xml, 'xml')
//
let newId = props.processId || `Process_${new Date().getTime()}`
let newName = props.processName || `业务流程_${new Date().getTime()}`
let xmlString = xml || DefaultEmptyXML(newId, newName, props.prefix)
try {
// console.log(xmlString, 'xmlString')
// console.log(this.bpmnModeler.importXML);
let { warnings } = await bpmnModeler.importXML(xmlString)
console.log(warnings, 'warnings')
if (warnings && warnings.length) {
warnings.forEach((warn) => console.warn(warn))
}
} catch (e) {
console.error(`[Process Designer Warn]: ${e?.message || e}`)
}
}
//
const downloadProcess = async (type, name) => {
try {
//
if (type === 'xml' || type === 'bpmn') {
const { err, xml } = await bpmnModeler.saveXML()
//
if (err) {
console.error(`[Process Designer Warn ]: ${err.message || err}`)
}
let { href, filename } = setEncoded(type.toUpperCase(), name, xml)
downloadFunc(href, filename)
} else {
const { err, svg } = await bpmnModeler.saveSVG()
//
if (err) {
return console.error(err)
}
let { href, filename } = setEncoded('SVG', name, svg)
downloadFunc(href, filename)
}
} catch (e) {
console.error(`[Process Designer Warn ]: ${e.message || e}`)
}
//
function downloadFunc(href, filename) {
if (href && filename) {
let a = document.createElement('a')
a.download = filename //
a.href = href // URL
a.click() //
URL.revokeObjectURL(a.href) // URL
}
}
}
//
const setEncoded = (type, filename = 'diagram', data) => {
const encodedData = encodeURIComponent(data)
return {
filename: `${filename}.${type}`,
href: `data:application/${
type === 'svg' ? 'text/xml' : 'bpmn20-xml'
};charset=UTF-8,${encodedData}`,
data: data
}
}
//
const importLocalFile = () => {
const file = refFile.value.files[0]
const reader = new FileReader()
reader.readAsText(file)
reader.onload = function () {
let xmlStr = this.result
createNewDiagram(xmlStr)
}
}
/* ------------------------------------------------ refs methods ------------------------------------------------------ */
const downloadProcessAsXml = () => {
downloadProcess('xml')
}
const downloadProcessAsBpmn = () => {
downloadProcess('bpmn')
}
const downloadProcessAsSvg = () => {
downloadProcess('svg')
}
const processSimulation = () => {
simulationStatus.value = !simulationStatus.value
console.log(bpmnModeler.get('toggleMode', 'strict'), "bpmnModeler.get('toggleMode')")
props.simulation && bpmnModeler.get('toggleMode', 'strict').toggleMode()
}
const processRedo = () => {
bpmnModeler.get('commandStack').redo()
}
const processUndo = () => {
bpmnModeler.get('commandStack').undo()
}
const processZoomIn = (zoomStep = 0.1) => {
let newZoom = Math.floor(defaultZoom.value * 100 + zoomStep * 100) / 100
if (newZoom > 4) {
throw new Error('[Process Designer Warn ]: The zoom ratio cannot be greater than 4')
}
defaultZoom.value = newZoom
bpmnModeler.get('canvas').zoom(defaultZoom.value)
}
const processZoomOut = (zoomStep = 0.1) => {
let newZoom = Math.floor(defaultZoom.value * 100 - zoomStep * 100) / 100
if (newZoom < 0.2) {
throw new Error('[Process Designer Warn ]: The zoom ratio cannot be less than 0.2')
}
defaultZoom.value = newZoom
bpmnModeler.get('canvas').zoom(defaultZoom.value)
}
// const processZoomTo = (newZoom = 1) => {
// if (newZoom < 0.2) {
// throw new Error('[Process Designer Warn ]: The zoom ratio cannot be less than 0.2')
// }
// if (newZoom > 4) {
// throw new Error('[Process Designer Warn ]: The zoom ratio cannot be greater than 4')
// }
// defaultZoom = newZoom
// bpmnModeler.get('canvas').zoom(newZoom)
// }
const processReZoom = () => {
defaultZoom.value = 1
bpmnModeler.get('canvas').zoom('fit-viewport', 'auto')
}
const processRestart = () => {
recoverable.value = false
revocable.value = false
createNewDiagram(null)
}
const elementsAlign = (align) => {
const Align = bpmnModeler.get('alignElements')
const Selection = bpmnModeler.get('selection')
const SelectedElements = Selection.get()
if (!SelectedElements || SelectedElements.length <= 1) {
ElMessage.warning('请按住 Shift 键选择多个元素对齐')
// alert(' Ctrl
return
}
ElMessageBox.confirm('自动对齐可能造成图形变形,是否继续?', '警告', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
Align.trigger(SelectedElements, align)
})
}
/*----------------------------- 方法结束 ---------------------------------*/
const previewProcessXML = () => {
console.log(bpmnModeler.saveXML, 'bpmnModeler')
bpmnModeler.saveXML({ format: true }).then(({ xml }) => {
console.log(xml, 'xml111111')
previewResult.value = xml
previewType.value = 'xml'
previewModelVisible.value = true
})
}
const previewProcessJson = () => {
bpmnModeler.saveXML({ format: true }).then(({ xml }) => {
console.log(xml, 'xml')
// const rootNode = parseXmlString(xml)
// console.log(rootNode, 'rootNoderootNode')
const rootNodes = new XmlNode(XmlNodeType.Root, parseXmlString(xml))
// console.log(rootNodes, 'rootNodesrootNodesrootNodes')
// console.log(rootNodes.parent.toJsObject(), 'rootNodes.toJSON()')
// console.log(JSON.stringify(rootNodes.parent.toJsObject()), 'rootNodes.toJSON()')
// console.log(JSON.stringify(rootNodes.parent.toJSON()), 'rootNodes.toJSON()')
const parser = new xml2js.XMLParser()
let jObj = parser.parse(xml)
console.log(jObj, 'jObjjObjjObjjObjjObj')
// const builder = new xml2js.XMLBuilder(xml)
// const xmlContent = builder
// console.log(xmlContent, 'xmlContent')
// console.log(xml2js, 'convertconvertconvert')
previewResult.value = rootNodes.parent.toJSON()
// previewResult.value = jObj
// previewResult.value = convert.xml2json(xml, {explicitArray : false},{ spaces: 2 })
previewType.value = 'json'
previewModelVisible.value = true
})
}
/* ------------------------------------------------ 芋道源码 methods ------------------------------------------------------ */
const processSave = async () => {
console.log(bpmnModeler, 'bpmnModelerbpmnModelerbpmnModelerbpmnModeler')
const { err, xml } = await bpmnModeler.saveXML()
console.log(err, 'errerrerrerrerr')
console.log(xml, 'xmlxmlxmlxmlxml')
//
if (err) {
// this.$modal.msgError('')
alert('保存模型失败,请重试!')
return
}
// save
emit('save', xml)
}
/** 高亮显示 */
// const highlightedCode = (previewType, previewResult) => {
// console.log(previewType, 'previewType, previewResult')
// console.log(previewResult, 'previewType, previewResult')
// console.log(hljs.highlight, 'hljs.highlight')
// const result = hljs.highlight(previewType, previewResult.value || '', true)
// return result.value || '&nbsp;'
// }
onBeforeMount(() => {
console.log(props, 'propspropspropsprops')
})
onMounted(() => {
initBpmnModeler()
createNewDiagram(props.value)
})
onBeforeUnmount(() => {
// this.$once('hook:beforeDestroy', () => {
// })
if (bpmnModeler) bpmnModeler.destroy()
emit('destroy', bpmnModeler)
bpmnModeler = null
})
</script>

View File

@ -0,0 +1,594 @@
<template>
<div class="my-process-designer">
<div class="my-process-designer__container">
<div class="my-process-designer__canvas" style="height: 760px" ref="bpmnCanvas"></div>
</div>
</div>
</template>
<script setup lang="ts" name="MyProcessViewer">
import BpmnViewer from 'bpmn-js/lib/Viewer'
import DefaultEmptyXML from './plugins/defaultEmpty'
import { onMounted, onBeforeUnmount, provide, ref, watch, toRaw } from 'vue'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
const props = defineProps({
value: {
// BPMN XML
type: String
},
prefix: {
// 使
type: String,
default: 'camunda'
},
activityData: {
//
type: Array,
default: () => []
},
processInstanceData: {
//
type: Object
},
taskData: {
// UserTask
type: Array,
default: () => []
}
})
provide('configGlobal', props)
const emit = defineEmits(['destroy'])
let bpmnModeler
const xml = ref('')
const activityLists = ref([])
const processInstance = ref(undefined)
const taskList = ref([])
const bpmnCanvas = ref()
// const element = ref()
const elementOverlayIds = ref(null)
const overlays = ref(null)
const initBpmnModeler = () => {
if (bpmnModeler) return
bpmnModeler = new BpmnViewer({
container: bpmnCanvas.value,
bpmnRenderer: {}
})
}
/* 创建新的流程图 */
const createNewDiagram = async (xml) => {
//
let newId = `Process_${new Date().getTime()}`
let newName = `业务流程_${new Date().getTime()}`
let xmlString = xml || DefaultEmptyXML(newId, newName, props.prefix)
try {
let { warnings } = await bpmnModeler.importXML(xmlString)
if (warnings && warnings.length) {
warnings.forEach((warn) => console.warn(warn))
}
//
await highlightDiagram()
const canvas = bpmnModeler.get('canvas')
canvas.zoom('fit-viewport', 'auto')
} catch (e) {
console.error(e)
// console.error(`[Process Designer Warn]: ${e?.message || e}`);
}
}
/* 高亮流程图 */
// TODO endActivity https://www.jdon.com/workflow/multi-events.html
const highlightDiagram = async () => {
const activityList = activityLists.value
if (activityList.length === 0) {
return
}
// https://gitee.com/tony2y/RuoYi-flowable/blob/master/ruoyi-ui/src/components/Process/index.vue#L222
//
let canvas = bpmnModeler.get('canvas')
let todoActivity = activityList.find((m) => !m.endTime) //
let endActivity = activityList[activityList.length - 1] //
// debugger
bpmnModeler.getDefinitions().rootElements[0].flowElements?.forEach((n) => {
let activity = activityList.find((m) => m.key === n.id) //
if (!activity) {
return
}
if (n.$type === 'bpmn:UserTask') {
//
//
const task = taskList.value.find((m) => m.id === activity.taskId) // taskId
if (!task) {
return
}
//
canvas.addMarker(n.id, getResultCss(task.result))
// 线
if (task.result !== 2) {
return
}
// outgoing 线
const outgoing = getActivityOutgoing(activity)
outgoing?.forEach((nn) => {
// debugger
let targetActivity = activityList.find((m) => m.key === nn.targetRef.id)
// bpmn:SequenceFlow线
if (targetActivity) {
canvas.addMarker(nn.id, targetActivity.endTime ? 'highlight' : 'highlight-todo')
} else if (nn.targetRef.$type === 'bpmn:ExclusiveGateway') {
// TODO
canvas.addMarker(nn.id, activity.endTime ? 'highlight' : 'highlight-todo')
canvas.addMarker(nn.targetRef.id, activity.endTime ? 'highlight' : 'highlight-todo')
} else if (nn.targetRef.$type === 'bpmn:EndEvent') {
// TODO
if (!todoActivity && endActivity.key === n.id) {
canvas.addMarker(nn.id, 'highlight')
canvas.addMarker(nn.targetRef.id, 'highlight')
}
if (!activity.endTime) {
canvas.addMarker(nn.id, 'highlight-todo')
canvas.addMarker(nn.targetRef.id, 'highlight-todo')
}
}
})
} else if (n.$type === 'bpmn:ExclusiveGateway') {
//
// bpmn:ExclusiveGateway
canvas.addMarker(n.id, getActivityHighlightCss(activity))
// 线
let matchNN = undefined
let matchActivity = undefined
n.outgoing?.forEach((nn) => {
let targetActivity = activityList.find((m) => m.key === nn.targetRef.id)
if (!targetActivity) {
return
}
// endEvent ExclusiveGateway 2
// 1. UserTask => EndEvent
// 2. EndEvent
// 1 EndEvent 1 2
// matchActivity EndEvent ~~
if (!matchActivity || matchActivity.type === 'endEvent') {
matchNN = nn
matchActivity = targetActivity
}
})
if (matchNN && matchActivity) {
canvas.addMarker(matchNN.id, getActivityHighlightCss(matchActivity))
}
} else if (n.$type === 'bpmn:ParallelGateway') {
//
// bpmn:ParallelGateway
canvas.addMarker(n.id, getActivityHighlightCss(activity))
n.outgoing?.forEach((nn) => {
// 线
const targetActivity = activityList.find((m) => m.key === nn.targetRef.id)
if (targetActivity) {
canvas.addMarker(nn.id, getActivityHighlightCss(targetActivity)) // bpmn:SequenceFlow线
// ... ... bpm:UserTask bpm:UserTask
canvas.addMarker(nn.targetRef.id, getActivityHighlightCss(targetActivity))
}
})
} else if (n.$type === 'bpmn:StartEvent') {
//
n.outgoing?.forEach((nn) => {
// outgoing bpmn:SequenceFlow线
// 线
let targetActivity = activityList.find((m) => m.key === nn.targetRef.id)
if (targetActivity) {
canvas.addMarker(nn.id, 'highlight') // bpmn:SequenceFlow线
canvas.addMarker(n.id, 'highlight') // bpmn:StartEvent
}
})
} else if (n.$type === 'bpmn:EndEvent') {
//
if (!processInstance.value || processInstance.value.result === 1) {
return
}
canvas.addMarker(n.id, getResultCss(processInstance.value.result))
} else if (n.$type === 'bpmn:ServiceTask') {
//
if (activity.startTime > 0 && activity.endTime === 0) {
//
canvas.addMarker(n.id, getResultCss(1))
}
if (activity.endTime > 0) {
// , outgoing
canvas.addMarker(n.id, getResultCss(2))
const outgoing = getActivityOutgoing(activity)
outgoing?.forEach((out) => {
canvas.addMarker(out.id, getResultCss(2))
})
}
}
})
}
const getActivityHighlightCss = (activity) => {
return activity.endTime ? 'highlight' : 'highlight-todo'
}
const getResultCss = (result) => {
if (result === 1) {
//
return 'highlight-todo'
} else if (result === 2) {
//
return 'highlight'
} else if (result === 3) {
//
return 'highlight-reject'
} else if (result === 4) {
//
return 'highlight-cancel'
}
return ''
}
const getActivityOutgoing = (activity) => {
// outgoing使
if (activity.outgoing && activity.outgoing.length > 0) {
return activity.outgoing
}
// bpmn:SequenceFlowbpmn-js UserTask outgoing
const flowElements = bpmnModeler.getDefinitions().rootElements[0].flowElements
const outgoing = []
flowElements.forEach((item) => {
if (item.$type !== 'bpmn:SequenceFlow') {
return
}
if (item.sourceRef.id === activity.key) {
outgoing.push(item)
}
})
return outgoing
}
const initModelListeners = () => {
const EventBus = bpmnModeler.get('eventBus')
//
EventBus.on('element.hover', function (eventObj) {
let element = eventObj ? eventObj.element : null
elementHover(element)
})
EventBus.on('element.out', function (eventObj) {
let element = eventObj ? eventObj.element : null
elementOut(element)
})
}
// hover
const elementHover = (element) => {
element.value = element
!elementOverlayIds.value && (elementOverlayIds.value = {})
!overlays.value && (overlays.value = bpmnModeler.get('overlays'))
//
console.log(activityLists.value, 'activityLists.value')
console.log(element.value, 'element.value')
const activity = activityLists.value.find((m) => m.key === element.value.id)
console.log(activity, 'activityactivityactivityactivity')
// if (!activity) {
// return
// }
if (!elementOverlayIds.value[element.value.id] && element.value.type !== 'bpmn:Process') {
let html = `<div class="element-overlays">
<p>Elemet id: ${element.value.id}</p>
<p>Elemet type: ${element.value.type}</p>
</div>` // 默认值
if (element.value.type === 'bpmn:StartEvent' && processInstance.value) {
html = `<p>发起人:${processInstance.value.startUser.nickname}</p>
<p>部门${processInstance.value.startUser.deptName}</p>
<p>创建时间${parseTime(processInstance.value.createTime)}`
} else if (element.value.type === 'bpmn:UserTask') {
// debugger
let task = taskList.value.find((m) => m.id === activity.taskId) // taskId
if (!task) {
return
}
let optionData = getIntDictOptions(DICT_TYPE.BPM_PROCESS_INSTANCE_RESULT)
let dataResult = ''
optionData.forEach((element) => {
if (element.value == task.result) {
dataResult = element.label
}
})
html = `<p>审批人:${task.assigneeUser.nickname}</p>
<p>部门${task.assigneeUser.deptName}</p>
<p>结果${dataResult}</p>
<p>创建时间${parseTime(task.createTime)}</p>`
// html = `<p>${task.assigneeUser.nickname}</p>
// <p>${task.assigneeUser.deptName}</p>
// <p>${getIntDictOptions(
// DICT_TYPE.BPM_PROCESS_INSTANCE_RESULT,
// task.result
// )}</p>
// <p>${parseTime(task.createTime)}</p>`
if (task.endTime) {
html += `<p>结束时间:${parseTime(task.endTime)}</p>`
}
if (task.reason) {
html += `<p>审批建议:${task.reason}</p>`
}
} else if (element.value.type === 'bpmn:ServiceTask' && processInstance.value) {
if (activity.startTime > 0) {
html = `<p>创建时间:${parseTime(activity.startTime)}</p>`
}
if (activity.endTime > 0) {
html += `<p>结束时间:${parseTime(activity.endTime)}</p>`
}
console.log(html)
} else if (element.value.type === 'bpmn:EndEvent' && processInstance.value) {
let optionData = getIntDictOptions(DICT_TYPE.BPM_PROCESS_INSTANCE_RESULT)
let dataResult = ''
optionData.forEach((element) => {
if (element.value == processInstance.value.result) {
dataResult = element.label
}
})
html = `<p>结果:${dataResult}</p>`
// html = `<p>${getIntDictOptions(
// DICT_TYPE.BPM_PROCESS_INSTANCE_RESULT,
// processInstance.value.result
// )}</p>`
if (processInstance.value.endTime) {
html += `<p>结束时间:${parseTime(processInstance.value.endTime)}</p>`
}
}
console.log(html, 'html111111111111111')
elementOverlayIds.value[element.value.id] = toRaw(overlays.value).add(element.value, {
position: { left: 0, bottom: 0 },
html: `<div class="element-overlays">${html}</div>`
})
}
}
// out
const elementOut = (element) => {
toRaw(overlays.value).remove({ element })
elementOverlayIds.value[element.id] = null
}
const parseTime = (time) => {
if (!time) {
return null
}
const format = '{y}-{m}-{d} {h}:{i}:{s}'
let date
if (typeof time === 'object') {
date = time
} else {
if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
time = parseInt(time)
} else if (typeof time === 'string') {
time = time
.replace(new RegExp(/-/gm), '/')
.replace('T', ' ')
.replace(new RegExp(/\.[\d]{3}/gm), '')
}
if (typeof time === 'number' && time.toString().length === 10) {
time = time * 1000
}
date = new Date(time)
}
const formatObj = {
y: date.getFullYear(),
m: date.getMonth() + 1,
d: date.getDate(),
h: date.getHours(),
i: date.getMinutes(),
s: date.getSeconds(),
a: date.getDay()
}
const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
let value = formatObj[key]
// Note: getDay() returns 0 on Sunday
if (key === 'a') {
return ['日', '一', '二', '三', '四', '五', '六'][value]
}
if (result.length > 0 && value < 10) {
value = '0' + value
}
return value || 0
})
return time_str
}
onMounted(() => {
xml.value = props.value
activityLists.value = props.activityData
//
initBpmnModeler()
createNewDiagram(xml.value)
//
initModelListeners()
})
onBeforeUnmount(() => {
// this.$once('hook:beforeDestroy', () => {
// })
if (bpmnModeler) bpmnModeler.destroy()
emit('destroy', bpmnModeler)
bpmnModeler = null
})
watch(
() => props.value,
(newValue) => {
xml.value = newValue
createNewDiagram(xml.value)
}
)
watch(
() => props.activityData,
(newActivityData) => {
activityLists.value = newActivityData
createNewDiagram(xml.value)
}
)
watch(
() => props.processInstanceData,
(newProcessInstanceData) => {
processInstance.value = newProcessInstanceData
createNewDiagram(xml.value)
}
)
watch(
() => props.taskData,
(newTaskListData) => {
taskList.value = newTaskListData
createNewDiagram(xml.value)
}
)
</script>
<style>
/** 处理中 */
.highlight-todo.djs-connection > .djs-visual > path {
stroke: #1890ff !important;
stroke-dasharray: 4px !important;
fill-opacity: 0.2 !important;
}
.highlight-todo.djs-shape .djs-visual > :nth-child(1) {
fill: #1890ff !important;
stroke: #1890ff !important;
stroke-dasharray: 4px !important;
fill-opacity: 0.2 !important;
}
:deep(.highlight-todo.djs-connection > .djs-visual > path) {
stroke: #1890ff !important;
stroke-dasharray: 4px !important;
fill-opacity: 0.2 !important;
marker-end: url(#sequenceflow-end-_E7DFDF-_E7DFDF-803g1kf6zwzmcig1y2ulm5egr);
}
:deep(.highlight-todo.djs-shape .djs-visual > :nth-child(1)) {
fill: #1890ff !important;
stroke: #1890ff !important;
stroke-dasharray: 4px !important;
fill-opacity: 0.2 !important;
}
/** 通过 */
.highlight.djs-shape .djs-visual > :nth-child(1) {
fill: green !important;
stroke: green !important;
fill-opacity: 0.2 !important;
}
.highlight.djs-shape .djs-visual > :nth-child(2) {
fill: green !important;
}
.highlight.djs-shape .djs-visual > path {
fill: green !important;
fill-opacity: 0.2 !important;
stroke: green !important;
}
.highlight.djs-connection > .djs-visual > path {
stroke: green !important;
}
.highlight:not(.djs-connection) .djs-visual > :nth-child(1) {
fill: green !important; /* color elements as green */
}
:deep(.highlight.djs-shape .djs-visual > :nth-child(1)) {
fill: green !important;
stroke: green !important;
fill-opacity: 0.2 !important;
}
:deep(.highlight.djs-shape .djs-visual > :nth-child(2)) {
fill: green !important;
}
:deep(.highlight.djs-shape .djs-visual > path) {
fill: green !important;
fill-opacity: 0.2 !important;
stroke: green !important;
}
:deep(.highlight.djs-connection > .djs-visual > path) {
stroke: green !important;
}
/** 不通过 */
.highlight-reject.djs-shape .djs-visual > :nth-child(1) {
fill: red !important;
stroke: red !important;
fill-opacity: 0.2 !important;
}
.highlight-reject.djs-shape .djs-visual > :nth-child(2) {
fill: red !important;
}
.highlight-reject.djs-shape .djs-visual > path {
fill: red !important;
fill-opacity: 0.2 !important;
stroke: red !important;
}
.highlight-reject.djs-connection > .djs-visual > path {
stroke: red !important;
}
.highlight-reject:not(.djs-connection) .djs-visual > :nth-child(1) {
fill: red !important; /* color elements as green */
}
:deep(.highlight-reject.djs-shape .djs-visual > :nth-child(1)) {
fill: red !important;
stroke: red !important;
fill-opacity: 0.2 !important;
}
:deep(.highlight-reject.djs-shape .djs-visual > :nth-child(2)) {
fill: red !important;
}
:deep(.highlight-reject.djs-shape .djs-visual > path) {
fill: red !important;
fill-opacity: 0.2 !important;
stroke: red !important;
}
:deep(.highlight-reject.djs-connection > .djs-visual > path) {
stroke: red !important;
}
/** 已取消 */
.highlight-cancel.djs-shape .djs-visual > :nth-child(1) {
fill: grey !important;
stroke: grey !important;
fill-opacity: 0.2 !important;
}
.highlight-cancel.djs-shape .djs-visual > :nth-child(2) {
fill: grey !important;
}
.highlight-cancel.djs-shape .djs-visual > path {
fill: grey !important;
fill-opacity: 0.2 !important;
stroke: grey !important;
}
.highlight-cancel.djs-connection > .djs-visual > path {
stroke: grey !important;
}
.highlight-cancel:not(.djs-connection) .djs-visual > :nth-child(1) {
fill: grey !important; /* color elements as green */
}
:deep(.highlight-cancel.djs-shape .djs-visual > :nth-child(1)) {
fill: grey !important;
stroke: grey !important;
fill-opacity: 0.2 !important;
}
:deep(.highlight-cancel.djs-shape .djs-visual > :nth-child(2)) {
fill: grey !important;
}
:deep(.highlight-cancel.djs-shape .djs-visual > path) {
fill: grey !important;
fill-opacity: 0.2 !important;
stroke: grey !important;
}
:deep(.highlight-cancel.djs-connection > .djs-visual > path) {
stroke: grey !important;
}
.element-overlays {
box-sizing: border-box;
padding: 8px;
background: rgba(0, 0, 0, 0.6);
border-radius: 4px;
color: #fafafa;
width: 200px;
}
</style>

View File

@ -0,0 +1,8 @@
import MyProcessDesigner from './ProcessDesigner.vue'
MyProcessDesigner.install = function (Vue) {
Vue.component(MyProcessDesigner.name, MyProcessDesigner)
}
// 流程图的设计器,可编辑
export default MyProcessDesigner

View File

@ -0,0 +1,8 @@
import MyProcessViewer from './ProcessViewer.vue'
MyProcessViewer.install = function (Vue) {
Vue.component(MyProcessViewer.name, MyProcessViewer)
}
// 流程图的查看器,不可编辑
export default MyProcessViewer

View File

@ -0,0 +1,390 @@
import { assign, forEach, isArray } from 'min-dash'
import { is } from "bpmn-js/lib/util/ModelUtil"
import { isExpanded, isEventSubProcess } from "bpmn-js/lib/util/DiUtil"
import { isAny } from "bpmn-js/lib/features/modeling/util/ModelingUtil"
import { getChildLanes } from "bpmn-js/lib/features/modeling/util/LaneUtil"
import { hasPrimaryModifier } from "diagram-js/lib/util/Mouse"
/**
* A provider for BPMN 2.0 elements context pad
*/
export default function ContextPadProvider (
config,
injector,
eventBus,
contextPad,
modeling,
elementFactory,
connect,
create,
popupMenu,
canvas,
rules,
translate,
elementRegistry
) {
config = config || {}
contextPad.registerProvider(this)
this._contextPad = contextPad
this._modeling = modeling
this._elementFactory = elementFactory
this._connect = connect
this._create = create
this._popupMenu = popupMenu
this._canvas = canvas
this._rules = rules
this._translate = translate
if (config.autoPlace !== false) {
this._autoPlace = injector.get("autoPlace", false)
}
eventBus.on("create.end", 250, function (event) {
const context = event.context,
shape = context.shape
if (!hasPrimaryModifier(event) || !contextPad.isOpen(shape)) {
return
}
const entries = contextPad.getEntries(shape)
if (entries.replace) {
entries.replace.action.click(event, shape)
}
})
}
ContextPadProvider.$inject = [
"config.contextPad",
"injector",
"eventBus",
"contextPad",
"modeling",
"elementFactory",
"connect",
"create",
"popupMenu",
"canvas",
"rules",
"translate",
"elementRegistry"
]
ContextPadProvider.prototype.getContextPadEntries = function (element) {
const contextPad = this._contextPad,
modeling = this._modeling,
elementFactory = this._elementFactory,
connect = this._connect,
create = this._create,
popupMenu = this._popupMenu,
canvas = this._canvas,
rules = this._rules,
autoPlace = this._autoPlace,
translate = this._translate
const actions = {}
if (element.type === "label") {
return actions
}
const businessObject = element.businessObject
function startConnect (event, element) {
connect.start(event, element)
}
function removeElement () {
modeling.removeElements([element])
}
function getReplaceMenuPosition (element) {
const Y_OFFSET = 5
const diagramContainer = canvas.getContainer(),
pad = contextPad.getPad(element).html
const diagramRect = diagramContainer.getBoundingClientRect(),
padRect = pad.getBoundingClientRect()
const top = padRect.top - diagramRect.top
const left = padRect.left - diagramRect.left
const pos = {
x: left,
y: top + padRect.height + Y_OFFSET
}
return pos
}
/**
* Create an append action
*
* @param {string} type
* @param {string} className
* @param {string} [title]
* @param {Object} [options]
*
* @return {Object} descriptor
*/
function appendAction (type, className, title, options) {
if (typeof title !== "string") {
options = title
title = translate("Append {type}", { type: type.replace(/^bpmn:/, "") })
}
function appendStart (event, element) {
const shape = elementFactory.createShape(assign({ type: type }, options))
create.start(event, shape, {
source: element
})
}
const append = autoPlace
? function (event, element) {
const shape = elementFactory.createShape(assign({ type: type }, options))
autoPlace.append(element, shape)
}
: appendStart
return {
group: "model",
className: className,
title: title,
action: {
dragstart: appendStart,
click: append
}
}
}
function splitLaneHandler (count) {
return function (event, element) {
// actual split
modeling.splitLane(element, count)
// refresh context pad after split to
// get rid of split icons
contextPad.open(element, true)
}
}
if (isAny(businessObject, ["bpmn:Lane", "bpmn:Participant"]) && isExpanded(businessObject)) {
const childLanes = getChildLanes(element)
assign(actions, {
"lane-insert-above": {
group: "lane-insert-above",
className: "bpmn-icon-lane-insert-above",
title: translate("Add Lane above"),
action: {
click: function (event, element) {
modeling.addLane(element, "top")
}
}
}
})
if (childLanes.length < 2) {
if (element.height >= 120) {
assign(actions, {
"lane-divide-two": {
group: "lane-divide",
className: "bpmn-icon-lane-divide-two",
title: translate("Divide into two Lanes"),
action: {
click: splitLaneHandler(2)
}
}
})
}
if (element.height >= 180) {
assign(actions, {
"lane-divide-three": {
group: "lane-divide",
className: "bpmn-icon-lane-divide-three",
title: translate("Divide into three Lanes"),
action: {
click: splitLaneHandler(3)
}
}
})
}
}
assign(actions, {
"lane-insert-below": {
group: "lane-insert-below",
className: "bpmn-icon-lane-insert-below",
title: translate("Add Lane below"),
action: {
click: function (event, element) {
modeling.addLane(element, "bottom")
}
}
}
})
}
if (is(businessObject, "bpmn:FlowNode")) {
if (is(businessObject, "bpmn:EventBasedGateway")) {
assign(actions, {
"append.receive-task": appendAction("bpmn:ReceiveTask", "bpmn-icon-receive-task", translate("Append ReceiveTask")),
"append.message-intermediate-event": appendAction(
"bpmn:IntermediateCatchEvent",
"bpmn-icon-intermediate-event-catch-message",
translate("Append MessageIntermediateCatchEvent"),
{ eventDefinitionType: "bpmn:MessageEventDefinition" }
),
"append.timer-intermediate-event": appendAction(
"bpmn:IntermediateCatchEvent",
"bpmn-icon-intermediate-event-catch-timer",
translate("Append TimerIntermediateCatchEvent"),
{ eventDefinitionType: "bpmn:TimerEventDefinition" }
),
"append.condition-intermediate-event": appendAction(
"bpmn:IntermediateCatchEvent",
"bpmn-icon-intermediate-event-catch-condition",
translate("Append ConditionIntermediateCatchEvent"),
{ eventDefinitionType: "bpmn:ConditionalEventDefinition" }
),
"append.signal-intermediate-event": appendAction(
"bpmn:IntermediateCatchEvent",
"bpmn-icon-intermediate-event-catch-signal",
translate("Append SignalIntermediateCatchEvent"),
{ eventDefinitionType: "bpmn:SignalEventDefinition" }
)
})
} else if (isEventType(businessObject, "bpmn:BoundaryEvent", "bpmn:CompensateEventDefinition")) {
assign(actions, {
"append.compensation-activity": appendAction("bpmn:Task", "bpmn-icon-task", translate("Append compensation activity"), {
isForCompensation: true
})
})
} else if (
!is(businessObject, "bpmn:EndEvent") &&
!businessObject.isForCompensation &&
!isEventType(businessObject, "bpmn:IntermediateThrowEvent", "bpmn:LinkEventDefinition") &&
!isEventSubProcess(businessObject)
) {
assign(actions, {
"append.end-event": appendAction("bpmn:EndEvent", "bpmn-icon-end-event-none", translate("Append EndEvent")),
"append.gateway": appendAction("bpmn:ExclusiveGateway", "bpmn-icon-gateway-none", translate("Append Gateway")),
"append.append-task": appendAction("bpmn:UserTask", "bpmn-icon-user-task", translate("Append Task")),
"append.intermediate-event": appendAction(
"bpmn:IntermediateThrowEvent",
"bpmn-icon-intermediate-event-none",
translate("Append Intermediate/Boundary Event")
)
})
}
}
if (!popupMenu.isEmpty(element, "bpmn-replace")) {
// Replace menu entry
assign(actions, {
replace: {
group: "edit",
className: "bpmn-icon-screw-wrench",
title: '修改类型',
action: {
click: function (event, element) {
const position = assign(getReplaceMenuPosition(element), {
cursor: { x: event.x, y: event.y }
})
popupMenu.open(element, "bpmn-replace", position)
}
}
}
})
}
if (isAny(businessObject, ["bpmn:FlowNode", "bpmn:InteractionNode", "bpmn:DataObjectReference", "bpmn:DataStoreReference"])) {
assign(actions, {
"append.text-annotation": appendAction("bpmn:TextAnnotation", "bpmn-icon-text-annotation"),
connect: {
group: "connect",
className: "bpmn-icon-connection-multi",
title: translate("Connect using " + (businessObject.isForCompensation ? "" : "Sequence/MessageFlow or ") + "Association"),
action: {
click: startConnect,
dragstart: startConnect
}
}
})
}
if (isAny(businessObject, ["bpmn:DataObjectReference", "bpmn:DataStoreReference"])) {
assign(actions, {
connect: {
group: "connect",
className: "bpmn-icon-connection-multi",
title: translate("Connect using DataInputAssociation"),
action: {
click: startConnect,
dragstart: startConnect
}
}
})
}
if (is(businessObject, "bpmn:Group")) {
assign(actions, {
"append.text-annotation": appendAction("bpmn:TextAnnotation", "bpmn-icon-text-annotation")
})
}
// delete element entry, only show if allowed by rules
let deleteAllowed = rules.allowed('elements.delete', { elements: [element] })
if (isArray(deleteAllowed)) {
// was the element returned as a deletion candidate?
deleteAllowed = deleteAllowed[0] === element
}
if (deleteAllowed) {
assign(actions, {
delete: {
group: "edit",
className: "bpmn-icon-trash",
title: translate("Remove"),
action: {
click: removeElement
}
}
})
}
return actions
}
// helpers /////////
function isEventType (eventBo, type, definition) {
const isType = eventBo.$instanceOf(type)
let isDefinition = false
const definitions = eventBo.eventDefinitions || []
forEach(definitions, function (def) {
if (def.$type === definition) {
isDefinition = true
}
})
return isType && isDefinition
}

View File

@ -0,0 +1,6 @@
import CustomContextPadProvider from "./contentPadProvider";
export default {
__init__: ["contextPadProvider"],
contextPadProvider: ["type", CustomContextPadProvider]
};

View File

@ -0,0 +1,24 @@
export default (key, name, type) => {
if (!type) type = "camunda";
const TYPE_TARGET = {
activiti: "http://activiti.org/bpmn",
camunda: "http://bpmn.io/schema/bpmn",
flowable: "http://flowable.org/bpmn"
};
return `<?xml version="1.0" encoding="UTF-8"?>
<bpmn2:definitions
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:bpmn2="http://www.omg.org/spec/BPMN/20100524/MODEL"
xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI"
xmlns:dc="http://www.omg.org/spec/DD/20100524/DC"
xmlns:di="http://www.omg.org/spec/DD/20100524/DI"
id="diagram_${key}"
targetNamespace="${TYPE_TARGET[type]}">
<bpmn2:process id="${key}" name="${name}" isExecutable="true">
</bpmn2:process>
<bpmndi:BPMNDiagram id="BPMNDiagram_1">
<bpmndi:BPMNPlane id="BPMNPlane_1" bpmnElement="${key}">
</bpmndi:BPMNPlane>
</bpmndi:BPMNDiagram>
</bpmn2:definitions>`;
};

View File

@ -0,0 +1,79 @@
"use strict"
import { some } from 'min-dash'
// const some = require('min-dash').some
// const some = some
const ALLOWED_TYPES = {
FailedJobRetryTimeCycle: ['bpmn:StartEvent', 'bpmn:BoundaryEvent', 'bpmn:IntermediateCatchEvent', 'bpmn:Activity'],
Connector: ['bpmn:EndEvent', 'bpmn:IntermediateThrowEvent'],
Field: ['bpmn:EndEvent', 'bpmn:IntermediateThrowEvent']
}
function is (element, type) {
return element && typeof element.$instanceOf === "function" && element.$instanceOf(type)
}
function exists (element) {
return element && element.length
}
function includesType (collection, type) {
return (
exists(collection) &&
some(collection, function (element) {
return is(element, type)
})
)
}
function anyType (element, types) {
return some(types, function (type) {
return is(element, type)
})
}
function isAllowed (propName, propDescriptor, newElement) {
const name = propDescriptor.name,
types = ALLOWED_TYPES[name.replace(/activiti:/, '')]
return name === propName && anyType(newElement, types)
}
function ActivitiModdleExtension (eventBus) {
eventBus.on(
"property.clone",
function (context) {
const newElement = context.newElement,
propDescriptor = context.propertyDescriptor
this.canCloneProperty(newElement, propDescriptor)
},
this
)
}
ActivitiModdleExtension.$inject = ["eventBus"]
ActivitiModdleExtension.prototype.canCloneProperty = function (newElement, propDescriptor) {
if (isAllowed("activiti:FailedJobRetryTimeCycle", propDescriptor, newElement)) {
return (
includesType(newElement.eventDefinitions, "bpmn:TimerEventDefinition") ||
includesType(newElement.eventDefinitions, "bpmn:SignalEventDefinition") ||
is(newElement.loopCharacteristics, "bpmn:MultiInstanceLoopCharacteristics")
)
}
if (isAllowed("activiti:Connector", propDescriptor, newElement)) {
return includesType(newElement.eventDefinitions, "bpmn:MessageEventDefinition")
}
if (isAllowed("activiti:Field", propDescriptor, newElement)) {
return includesType(newElement.eventDefinitions, "bpmn:MessageEventDefinition")
}
}
// module.exports = ActivitiModdleExtension;
export default ActivitiModdleExtension

View File

@ -0,0 +1,11 @@
/*
* @author igdianov
* address https://github.com/igdianov/activiti-bpmn-moddle
* */
import activitiExtension from "./activitiExtension"
export default {
__init__: ["ActivitiModdleExtension"],
ActivitiModdleExtension: ["type", activitiExtension]
}

View File

@ -0,0 +1,157 @@
"use strict"
import {
isFunction,
isObject,
some
} from 'min-dash'
// const isFunction = isFunction,
// isObject = isObject,
// some = some
// const isFunction = require('min-dash').isFunction,
// isObject = require('min-dash').isObject,
// some = require('min-dash').some
const WILDCARD = '*'
function CamundaModdleExtension (eventBus) {
const self = this
eventBus.on("moddleCopy.canCopyProperty", function (context) {
const property = context.property,
parent = context.parent
return self.canCopyProperty(property, parent)
})
}
CamundaModdleExtension.$inject = ["eventBus"]
/**
* Check wether to disallow copying property.
*/
CamundaModdleExtension.prototype.canCopyProperty = function (property, parent) {
// (1) check wether property is allowed in parent
if (isObject(property) && !isAllowedInParent(property, parent)) {
return false
}
// (2) check more complex scenarios
if (is(property, "camunda:InputOutput") && !this.canHostInputOutput(parent)) {
return false
}
if (isAny(property, ["camunda:Connector", "camunda:Field"]) && !this.canHostConnector(parent)) {
return false
}
if (is(property, "camunda:In") && !this.canHostIn(parent)) {
return false
}
}
CamundaModdleExtension.prototype.canHostInputOutput = function (parent) {
// allowed in camunda:Connector
const connector = getParent(parent, 'camunda:Connector')
if (connector) {
return true
}
// special rules inside bpmn:FlowNode
const flowNode = getParent(parent, 'bpmn:FlowNode')
if (!flowNode) {
return false
}
if (isAny(flowNode, ["bpmn:StartEvent", "bpmn:Gateway", "bpmn:BoundaryEvent"])) {
return false
}
return !(is(flowNode, "bpmn:SubProcess") && flowNode.get("triggeredByEvent"))
}
CamundaModdleExtension.prototype.canHostConnector = function (parent) {
const serviceTaskLike = getParent(parent, 'camunda:ServiceTaskLike')
if (is(serviceTaskLike, "bpmn:MessageEventDefinition")) {
// only allow on throw and end events
return getParent(parent, "bpmn:IntermediateThrowEvent") || getParent(parent, "bpmn:EndEvent")
}
return true
}
CamundaModdleExtension.prototype.canHostIn = function (parent) {
const callActivity = getParent(parent, 'bpmn:CallActivity')
if (callActivity) {
return true
}
const signalEventDefinition = getParent(parent, 'bpmn:SignalEventDefinition')
if (signalEventDefinition) {
// only allow on throw and end events
return getParent(parent, "bpmn:IntermediateThrowEvent") || getParent(parent, "bpmn:EndEvent")
}
return true
}
// module.exports = CamundaModdleExtension;
export default CamundaModdleExtension
// helpers //////////
function is (element, type) {
return element && isFunction(element.$instanceOf) && element.$instanceOf(type)
}
function isAny (element, types) {
return some(types, function (t) {
return is(element, t)
})
}
function getParent (element, type) {
if (!type) {
return element.$parent
}
if (is(element, type)) {
return element
}
if (!element.$parent) {
return
}
return getParent(element.$parent, type)
}
function isAllowedInParent (property, parent) {
// (1) find property descriptor
const descriptor = property.$type && property.$model.getTypeDescriptor(property.$type)
const allowedIn = descriptor && descriptor.meta && descriptor.meta.allowedIn
if (!allowedIn || isWildcard(allowedIn)) {
return true
}
// (2) check wether property has parent of allowed type
return some(allowedIn, function (type) {
return getParent(parent, type)
})
}
function isWildcard (allowedIn) {
return allowedIn.indexOf(WILDCARD) !== -1
}

View File

@ -0,0 +1,8 @@
"use strict"
import extension from "./extension"
export default {
__init__: ["camundaModdleExtension"],
camundaModdleExtension: ["type", extension]
}

View File

@ -0,0 +1,80 @@
"use strict"
import { some } from 'min-dash'
// const some = some
// const some = require('min-dash').some
const ALLOWED_TYPES = {
FailedJobRetryTimeCycle: ['bpmn:StartEvent', 'bpmn:BoundaryEvent', 'bpmn:IntermediateCatchEvent', 'bpmn:Activity'],
Connector: ['bpmn:EndEvent', 'bpmn:IntermediateThrowEvent'],
Field: ['bpmn:EndEvent', 'bpmn:IntermediateThrowEvent']
}
function is (element, type) {
return element && typeof element.$instanceOf === "function" && element.$instanceOf(type)
}
function exists (element) {
return element && element.length
}
function includesType (collection, type) {
return (
exists(collection) &&
some(collection, function (element) {
return is(element, type)
})
)
}
function anyType (element, types) {
return some(types, function (type) {
return is(element, type)
})
}
function isAllowed (propName, propDescriptor, newElement) {
const name = propDescriptor.name,
types = ALLOWED_TYPES[name.replace(/flowable:/, '')]
return name === propName && anyType(newElement, types)
}
function FlowableModdleExtension (eventBus) {
eventBus.on(
"property.clone",
function (context) {
const newElement = context.newElement,
propDescriptor = context.propertyDescriptor
this.canCloneProperty(newElement, propDescriptor)
},
this
)
}
FlowableModdleExtension.$inject = ["eventBus"]
FlowableModdleExtension.prototype.canCloneProperty = function (newElement, propDescriptor) {
if (isAllowed("flowable:FailedJobRetryTimeCycle", propDescriptor, newElement)) {
return (
includesType(newElement.eventDefinitions, "bpmn:TimerEventDefinition") ||
includesType(newElement.eventDefinitions, "bpmn:SignalEventDefinition") ||
is(newElement.loopCharacteristics, "bpmn:MultiInstanceLoopCharacteristics")
)
}
if (isAllowed("flowable:Connector", propDescriptor, newElement)) {
return includesType(newElement.eventDefinitions, "bpmn:MessageEventDefinition")
}
if (isAllowed("flowable:Field", propDescriptor, newElement)) {
return includesType(newElement.eventDefinitions, "bpmn:MessageEventDefinition")
}
}
// module.exports = FlowableModdleExtension;
export default FlowableModdleExtension

View File

@ -0,0 +1,10 @@
/*
* @author igdianov
* address https://github.com/igdianov/activiti-bpmn-moddle
* */
import flowableExtension from "./flowableExtension"
export default {
__init__: ["FlowableModdleExtension"],
FlowableModdleExtension: ["type", flowableExtension]
}

View File

@ -0,0 +1,157 @@
import PaletteProvider from 'bpmn-js/lib/features/palette/PaletteProvider'
import { assign } from "min-dash"
export default function CustomPalette (palette, create, elementFactory, spaceTool, lassoTool, handTool, globalConnect, translate) {
PaletteProvider.call(this, palette, create, elementFactory, spaceTool, lassoTool, handTool, globalConnect, translate, 2000)
}
const F = function () { } // 核心,利用空对象作为中介;
F.prototype = PaletteProvider.prototype // 核心将父类的原型赋值给空对象F
// 利用中介函数重写原型链方法
F.prototype.getPaletteEntries = function () {
const actions = {},
create = this._create,
elementFactory = this._elementFactory,
spaceTool = this._spaceTool,
lassoTool = this._lassoTool,
handTool = this._handTool,
globalConnect = this._globalConnect,
translate = this._translate
function createAction (type, group, className, title, options) {
function createListener (event) {
const shape = elementFactory.createShape(assign({ type: type }, options))
if (options) {
shape.businessObject.di.isExpanded = options.isExpanded
}
create.start(event, shape)
}
const shortType = type.replace(/^bpmn:/, '')
return {
group: group,
className: className,
title: title || translate("Create {type}", { type: shortType }),
action: {
dragstart: createListener,
click: createListener
}
}
}
function createSubprocess (event) {
const subProcess = elementFactory.createShape({
type: 'bpmn:SubProcess',
x: 0,
y: 0,
isExpanded: true
})
const startEvent = elementFactory.createShape({
type: 'bpmn:StartEvent',
x: 40,
y: 82,
parent: subProcess
})
create.start(event, [subProcess, startEvent], {
hints: {
autoSelect: [startEvent]
}
})
}
function createParticipant (event) {
create.start(event, elementFactory.createParticipantShape())
}
assign(actions, {
"hand-tool": {
group: "tools",
className: "bpmn-icon-hand-tool",
title: '激活抓手工具',
// title: translate("Activate the hand tool"),
action: {
click: function (event) {
handTool.activateHand(event)
}
}
},
"lasso-tool": {
group: "tools",
className: "bpmn-icon-lasso-tool",
title: translate("Activate the lasso tool"),
action: {
click: function (event) {
lassoTool.activateSelection(event)
}
}
},
"space-tool": {
group: "tools",
className: "bpmn-icon-space-tool",
title: translate("Activate the create/remove space tool"),
action: {
click: function (event) {
spaceTool.activateSelection(event)
}
}
},
"global-connect-tool": {
group: "tools",
className: "bpmn-icon-connection-multi",
title: translate("Activate the global connect tool"),
action: {
click: function (event) {
globalConnect.toggle(event)
}
}
},
"tool-separator": {
group: "tools",
separator: true
},
"create.start-event": createAction("bpmn:StartEvent", "event", "bpmn-icon-start-event-none", translate("Create StartEvent")),
"create.intermediate-event": createAction(
"bpmn:IntermediateThrowEvent",
"event",
"bpmn-icon-intermediate-event-none",
translate("Create Intermediate/Boundary Event")
),
"create.end-event": createAction("bpmn:EndEvent", "event", "bpmn-icon-end-event-none", translate("Create EndEvent")),
"create.exclusive-gateway": createAction("bpmn:ExclusiveGateway", "gateway", "bpmn-icon-gateway-none", translate("Create Gateway")),
"create.user-task": createAction("bpmn:UserTask", "activity", "bpmn-icon-user-task", translate("Create User Task")),
"create.data-object": createAction("bpmn:DataObjectReference", "data-object", "bpmn-icon-data-object", translate("Create DataObjectReference")),
"create.data-store": createAction("bpmn:DataStoreReference", "data-store", "bpmn-icon-data-store", translate("Create DataStoreReference")),
"create.subprocess-expanded": {
group: "activity",
className: "bpmn-icon-subprocess-expanded",
title: translate("Create expanded SubProcess"),
action: {
dragstart: createSubprocess,
click: createSubprocess
}
},
"create.participant-expanded": {
group: "collaboration",
className: "bpmn-icon-participant",
title: translate("Create Pool/Participant"),
action: {
dragstart: createParticipant,
click: createParticipant
}
},
"create.group": createAction("bpmn:Group", "artifact", "bpmn-icon-group", translate("Create Group"))
})
return actions
}
CustomPalette.$inject = ["palette", "create", "elementFactory", "spaceTool", "lassoTool", "handTool", "globalConnect", "translate"]
CustomPalette.prototype = new F() // 核心,将 F的实例赋值给子类
CustomPalette.prototype.constructor = CustomPalette // 修复子类CustomPalette的构造器指向防止原型链的混乱

View File

@ -0,0 +1,22 @@
// import PaletteModule from "diagram-js/lib/features/palette";
// import CreateModule from "diagram-js/lib/features/create";
// import SpaceToolModule from "diagram-js/lib/features/space-tool";
// import LassoToolModule from "diagram-js/lib/features/lasso-tool";
// import HandToolModule from "diagram-js/lib/features/hand-tool";
// import GlobalConnectModule from "diagram-js/lib/features/global-connect";
// import translate from "diagram-js/lib/i18n/translate";
//
// import PaletteProvider from "./paletteProvider";
//
// export default {
// __depends__: [PaletteModule, CreateModule, SpaceToolModule, LassoToolModule, HandToolModule, GlobalConnectModule, translate],
// __init__: ["paletteProvider"],
// paletteProvider: ["type", PaletteProvider]
// };
import CustomPalette from "./CustomPalette";
export default {
__init__: ["paletteProvider"],
paletteProvider: ["type", CustomPalette]
};

View File

@ -0,0 +1,160 @@
import { assign } from "min-dash"
/**
* A palette provider for BPMN 2.0 elements.
*/
export default function PaletteProvider (palette, create, elementFactory, spaceTool, lassoTool, handTool, globalConnect, translate) {
this._palette = palette
this._create = create
this._elementFactory = elementFactory
this._spaceTool = spaceTool
this._lassoTool = lassoTool
this._handTool = handTool
this._globalConnect = globalConnect
this._translate = translate
palette.registerProvider(this)
}
PaletteProvider.$inject = ["palette", "create", "elementFactory", "spaceTool", "lassoTool", "handTool", "globalConnect", "translate"]
PaletteProvider.prototype.getPaletteEntries = function () {
const actions = {},
create = this._create,
elementFactory = this._elementFactory,
spaceTool = this._spaceTool,
lassoTool = this._lassoTool,
handTool = this._handTool,
globalConnect = this._globalConnect,
translate = this._translate
function createAction (type, group, className, title, options) {
function createListener (event) {
const shape = elementFactory.createShape(assign({ type: type }, options))
if (options) {
shape.businessObject.di.isExpanded = options.isExpanded
}
create.start(event, shape)
}
const shortType = type.replace(/^bpmn:/, '')
return {
group: group,
className: className,
title: title || translate("Create {type}", { type: shortType }),
action: {
dragstart: createListener,
click: createListener
}
}
}
function createSubprocess (event) {
const subProcess = elementFactory.createShape({
type: 'bpmn:SubProcess',
x: 0,
y: 0,
isExpanded: true
})
const startEvent = elementFactory.createShape({
type: 'bpmn:StartEvent',
x: 40,
y: 82,
parent: subProcess
})
create.start(event, [subProcess, startEvent], {
hints: {
autoSelect: [startEvent]
}
})
}
function createParticipant (event) {
create.start(event, elementFactory.createParticipantShape())
}
assign(actions, {
"hand-tool": {
group: "tools",
className: "bpmn-icon-hand-tool",
title: translate("Activate the hand tool"),
action: {
click: function (event) {
handTool.activateHand(event)
}
}
},
"lasso-tool": {
group: "tools",
className: "bpmn-icon-lasso-tool",
title: translate("Activate the lasso tool"),
action: {
click: function (event) {
lassoTool.activateSelection(event)
}
}
},
"space-tool": {
group: "tools",
className: "bpmn-icon-space-tool",
title: translate("Activate the create/remove space tool"),
action: {
click: function (event) {
spaceTool.activateSelection(event)
}
}
},
"global-connect-tool": {
group: "tools",
className: "bpmn-icon-connection-multi",
title: translate("Activate the global connect tool"),
action: {
click: function (event) {
globalConnect.toggle(event)
}
}
},
"tool-separator": {
group: "tools",
separator: true
},
"create.start-event": createAction("bpmn:StartEvent", "event", "bpmn-icon-start-event-none", translate("Create StartEvent")),
"create.intermediate-event": createAction(
"bpmn:IntermediateThrowEvent",
"event",
"bpmn-icon-intermediate-event-none",
translate("Create Intermediate/Boundary Event")
),
"create.end-event": createAction("bpmn:EndEvent", "event", "bpmn-icon-end-event-none", translate("Create EndEvent")),
"create.exclusive-gateway": createAction("bpmn:ExclusiveGateway", "gateway", "bpmn-icon-gateway-none", translate("Create Gateway")),
"create.user-task": createAction("bpmn:UserTask", "activity", "bpmn-icon-user-task", translate("Create User Task")),
"create.data-object": createAction("bpmn:DataObjectReference", "data-object", "bpmn-icon-data-object", translate("Create DataObjectReference")),
"create.data-store": createAction("bpmn:DataStoreReference", "data-store", "bpmn-icon-data-store", translate("Create DataStoreReference")),
"create.subprocess-expanded": {
group: "activity",
className: "bpmn-icon-subprocess-expanded",
title: translate("Create expanded SubProcess"),
action: {
dragstart: createSubprocess,
click: createSubprocess
}
},
"create.participant-expanded": {
group: "collaboration",
className: "bpmn-icon-participant",
title: translate("Create Pool/Participant"),
action: {
dragstart: createParticipant,
click: createParticipant
}
},
"create.group": createAction("bpmn:Group", "artifact", "bpmn-icon-group", translate("Create Group"))
})
return actions
}

View File

@ -0,0 +1,41 @@
// import translations from "./zh";
//
// export default function customTranslate(template, replacements) {
// replacements = replacements || {};
//
// // Translate
// template = translations[template] || template;
//
// // Replace
// return template.replace(/{([^}]+)}/g, function(_, key) {
// let str = replacements[key];
// if (
// translations[replacements[key]] !== null &&
// translations[replacements[key]] !== "undefined"
// ) {
// // eslint-disable-next-line no-mixed-spaces-and-tabs
// str = translations[replacements[key]];
// // eslint-disable-next-line no-mixed-spaces-and-tabs
// }
// return str || "{" + key + "}";
// });
// }
export default function customTranslate(translations) {
return function(template, replacements) {
replacements = replacements || {};
// Translate
template = translations[template] || template;
// Replace
return template.replace(/{([^}]+)}/g, function(_, key) {
let str = replacements[key];
if (translations[replacements[key]] !== null && translations[replacements[key]] !== undefined) {
// eslint-disable-next-line no-mixed-spaces-and-tabs
str = translations[replacements[key]];
// eslint-disable-next-line no-mixed-spaces-and-tabs
}
return str || "{" + key + "}";
});
};
}

View File

@ -0,0 +1,238 @@
/**
* This is a sample file that should be replaced with the actual translation.
*
* Checkout https://github.com/bpmn-io/bpmn-js-i18n for a list of available
* translations and labels to translate.
*/
export default {
// 添加部分
"Append EndEvent": "追加结束事件",
"Append Gateway": "追加网关",
"Append Task": "追加任务",
"Append Intermediate/Boundary Event": "追加中间抛出事件/边界事件",
"Activate the global connect tool": "激活全局连接工具",
"Append {type}": "添加 {type}",
"Add Lane above": "在上面添加道",
"Divide into two Lanes": "分割成两个道",
"Divide into three Lanes": "分割成三个道",
"Add Lane below": "在下面添加道",
"Append compensation activity": "追加补偿活动",
"Change type": "修改类型",
"Connect using Association": "使用关联连接",
"Connect using Sequence/MessageFlow or Association": "使用顺序/消息流或者关联连接",
"Connect using DataInputAssociation": "使用数据输入关联连接",
Remove: "移除",
"Activate the hand tool": "激活抓手工具",
"Activate the lasso tool": "激活套索工具",
"Activate the create/remove space tool": "激活创建/删除空间工具",
"Create expanded SubProcess": "创建扩展子过程",
"Create IntermediateThrowEvent/BoundaryEvent": "创建中间抛出事件/边界事件",
"Create Pool/Participant": "创建池/参与者",
"Parallel Multi Instance": "并行多重事件",
"Sequential Multi Instance": "时序多重事件",
DataObjectReference: "数据对象参考",
DataStoreReference: "数据存储参考",
Loop: "循环",
"Ad-hoc": "即席",
"Create {type}": "创建 {type}",
Task: "任务",
"Send Task": "发送任务",
"Receive Task": "接收任务",
"User Task": "用户任务",
"Manual Task": "手工任务",
"Business Rule Task": "业务规则任务",
"Service Task": "服务任务",
"Script Task": "脚本任务",
"Call Activity": "调用活动",
"Sub Process (collapsed)": "子流程(折叠的)",
"Sub Process (expanded)": "子流程(展开的)",
"Start Event": "开始事件",
StartEvent: "开始事件",
"Intermediate Throw Event": "中间事件",
"End Event": "结束事件",
EndEvent: "结束事件",
"Create StartEvent": "创建开始事件",
"Create EndEvent": "创建结束事件",
"Create Task": "创建任务",
"Create User Task": "创建用户任务",
"Create Gateway": "创建网关",
"Create DataObjectReference": "创建数据对象",
"Create DataStoreReference": "创建数据存储",
"Create Group": "创建分组",
"Create Intermediate/Boundary Event": "创建中间/边界事件",
"Message Start Event": "消息开始事件",
"Timer Start Event": "定时开始事件",
"Conditional Start Event": "条件开始事件",
"Signal Start Event": "信号开始事件",
"Error Start Event": "错误开始事件",
"Escalation Start Event": "升级开始事件",
"Compensation Start Event": "补偿开始事件",
"Message Start Event (non-interrupting)": "消息开始事件(非中断)",
"Timer Start Event (non-interrupting)": "定时开始事件(非中断)",
"Conditional Start Event (non-interrupting)": "条件开始事件(非中断)",
"Signal Start Event (non-interrupting)": "信号开始事件(非中断)",
"Escalation Start Event (non-interrupting)": "升级开始事件(非中断)",
"Message Intermediate Catch Event": "消息中间捕获事件",
"Message Intermediate Throw Event": "消息中间抛出事件",
"Timer Intermediate Catch Event": "定时中间捕获事件",
"Escalation Intermediate Throw Event": "升级中间抛出事件",
"Conditional Intermediate Catch Event": "条件中间捕获事件",
"Link Intermediate Catch Event": "链接中间捕获事件",
"Link Intermediate Throw Event": "链接中间抛出事件",
"Compensation Intermediate Throw Event": "补偿中间抛出事件",
"Signal Intermediate Catch Event": "信号中间捕获事件",
"Signal Intermediate Throw Event": "信号中间抛出事件",
"Message End Event": "消息结束事件",
"Escalation End Event": "定时结束事件",
"Error End Event": "错误结束事件",
"Cancel End Event": "取消结束事件",
"Compensation End Event": "补偿结束事件",
"Signal End Event": "信号结束事件",
"Terminate End Event": "终止结束事件",
"Message Boundary Event": "消息边界事件",
"Message Boundary Event (non-interrupting)": "消息边界事件(非中断)",
"Timer Boundary Event": "定时边界事件",
"Timer Boundary Event (non-interrupting)": "定时边界事件(非中断)",
"Escalation Boundary Event": "升级边界事件",
"Escalation Boundary Event (non-interrupting)": "升级边界事件(非中断)",
"Conditional Boundary Event": "条件边界事件",
"Conditional Boundary Event (non-interrupting)": "条件边界事件(非中断)",
"Error Boundary Event": "错误边界事件",
"Cancel Boundary Event": "取消边界事件",
"Signal Boundary Event": "信号边界事件",
"Signal Boundary Event (non-interrupting)": "信号边界事件(非中断)",
"Compensation Boundary Event": "补偿边界事件",
"Exclusive Gateway": "互斥网关",
"Parallel Gateway": "并行网关",
"Inclusive Gateway": "相容网关",
"Complex Gateway": "复杂网关",
"Event based Gateway": "事件网关",
Transaction: "转运",
"Sub Process": "子流程",
"Event Sub Process": "事件子流程",
"Collapsed Pool": "折叠池",
"Expanded Pool": "展开池",
// Errors
"no parent for {element} in {parent}": "在{parent}里,{element}没有父类",
"no shape type specified": "没有指定的形状类型",
"flow elements must be children of pools/participants": "流元素必须是池/参与者的子类",
"out of bounds release": "out of bounds release",
"more than {count} child lanes": "子道大于{count} ",
"element required": "元素不能为空",
"diagram not part of bpmn:Definitions": "流程图不符合bpmn规范",
"no diagram to display": "没有可展示的流程图",
"no process or collaboration to display": "没有可展示的流程/协作",
"element {element} referenced by {referenced}#{property} not yet drawn": "由{referenced}#{property}引用的{element}元素仍未绘制",
"already rendered {element}": "{element} 已被渲染",
"failed to import {element}": "导入{element}失败",
//属性面板的参数
Id: "编号",
Name: "名称",
General: "常规",
Details: "详情",
"Message Name": "消息名称",
Message: "消息",
Initiator: "创建者",
"Asynchronous Continuations": "持续异步",
"Asynchronous Before": "异步前",
"Asynchronous After": "异步后",
"Job Configuration": "工作配置",
Exclusive: "排除",
"Job Priority": "工作优先级",
"Retry Time Cycle": "重试时间周期",
Documentation: "文档",
"Element Documentation": "元素文档",
"History Configuration": "历史配置",
"History Time To Live": "历史的生存时间",
Forms: "表单",
"Form Key": "表单key",
"Form Fields": "表单字段",
"Business Key": "业务key",
"Form Field": "表单字段",
ID: "编号",
Type: "类型",
Label: "名称",
"Default Value": "默认值",
"Default Flow": "默认流转路径",
"Conditional Flow": "条件流转路径",
"Sequence Flow": "普通流转路径",
Validation: "校验",
"Add Constraint": "添加约束",
Config: "配置",
Properties: "属性",
"Add Property": "添加属性",
Value: "值",
Listeners: "监听器",
"Execution Listener": "执行监听",
"Event Type": "事件类型",
"Listener Type": "监听器类型",
"Java Class": "Java类",
Expression: "表达式",
"Must provide a value": "必须提供一个值",
"Delegate Expression": "代理表达式",
Script: "脚本",
"Script Format": "脚本格式",
"Script Type": "脚本类型",
"Inline Script": "内联脚本",
"External Script": "外部脚本",
Resource: "资源",
"Field Injection": "字段注入",
Extensions: "扩展",
"Input/Output": "输入/输出",
"Input Parameters": "输入参数",
"Output Parameters": "输出参数",
Parameters: "参数",
"Output Parameter": "输出参数",
"Timer Definition Type": "定时器定义类型",
"Timer Definition": "定时器定义",
Date: "日期",
Duration: "持续",
Cycle: "循环",
Signal: "信号",
"Signal Name": "信号名称",
Escalation: "升级",
Error: "错误",
"Link Name": "链接名称",
Condition: "条件名称",
"Variable Name": "变量名称",
"Variable Event": "变量事件",
"Specify more than one variable change event as a comma separated list.": "多个变量事件以逗号隔开",
"Wait for Completion": "等待完成",
"Activity Ref": "活动参考",
"Version Tag": "版本标签",
Executable: "可执行文件",
"External Task Configuration": "扩展任务配置",
"Task Priority": "任务优先级",
External: "外部",
Connector: "连接器",
"Must configure Connector": "必须配置连接器",
"Connector Id": "连接器编号",
Implementation: "实现方式",
"Field Injections": "字段注入",
Fields: "字段",
"Result Variable": "结果变量",
Topic: "主题",
"Configure Connector": "配置连接器",
"Input Parameter": "输入参数",
Assignee: "代理人",
"Candidate Users": "候选用户",
"Candidate Groups": "候选组",
"Due Date": "到期时间",
"Follow Up Date": "跟踪日期",
Priority: "优先级",
"The follow up date as an EL expression (e.g. ${someDate} or an ISO date (e.g. 2015-06-26T09:54:00)":
"跟踪日期必须符合EL表达式 ${someDate} ,或者一个ISO标准日期2015-06-26T09:54:00",
"The due date as an EL expression (e.g. ${someDate} or an ISO date (e.g. 2015-06-26T09:54:00)":
"跟踪日期必须符合EL表达式 ${someDate} ,或者一个ISO标准日期2015-06-26T09:54:00",
Variables: "变量",
"Candidate Starter Configuration": "候选人起动器配置",
"Candidate Starter Groups": "候选人起动器组",
"This maps to the process definition key.": "这映射到流程定义键。",
"Candidate Starter Users": "候选人起动器的用户",
"Specify more than one user as a comma separated list.": "指定多个用户作为逗号分隔的列表。",
"Tasklist Configuration": "Tasklist配置",
Startable: "启动",
"Specify more than one group as a comma separated list.": "指定多个组作为逗号分隔的列表。"
};

View File

@ -0,0 +1,37 @@
import { App } from 'vue'
import MyProcessDesigner from './designer'
import MyProcessPenal from './penal'
import MyProcessViewer from './designer/index2'
const components = [MyProcessDesigner, MyProcessPenal, MyProcessViewer]
// const install = function (Vue) {
// components.forEach(component => {
// Vue.component(component.name, component)
// })
// }
// if (typeof window !== "undefined" && window.Vue) {
// install(window.Vue)
// }
// components.forEach(component => {
// Vue.component(component.name, component)
// })
const componentss = {
install: (Vue: App): void => {
components.forEach((component) => {
Vue.component(component.name, component)
})
}
}
// let version = "0.0.1"
export const MyPD = (app) => {
// export default {
// app.use(version)
// app.use(install)
// app.use(MyProcessDesigner)
// app.use(MyProcessPenal)
// app.use(MyProcessViewer)
// app.use(components)
app.use(componentss)
}

View File

@ -0,0 +1,41 @@
<template>
<div class="my-process-palette">
<div class="test-button" @click="addTask" @mousedown="addTask">测试任务</div>
<div class="test-container" id="palette-container">1</div>
</div>
</template>
<script setup lang="ts" name="MyProcessPalette">
import { assign } from 'min-dash'
const addTask = (event, options = {}) => {
const ElementFactory = window.bpmnInstances.elementFactory
const create = window.bpmnInstances.modeler.get('create')
console.log(ElementFactory, create)
const shape = ElementFactory.createShape(assign({ type: 'bpmn:UserTask' }, options))
if (options) {
shape.businessObject.di.isExpanded = options.isExpanded
}
console.log(event, 'event')
console.log(shape, 'shape')
create.start(event, shape)
}
</script>
<style scoped lang="scss">
.my-process-palette {
box-sizing: border-box;
padding: 80px 20px 20px 20px;
.test-button {
box-sizing: border-box;
padding: 8px 16px;
border-radius: 4px;
border: 1px solid rgba(24, 144, 255, 0.8);
cursor: pointer;
}
}
</style>

View File

@ -0,0 +1,204 @@
<template>
<div class="process-panel__container" :style="{ width: `${width}px` }">
<el-collapse v-model="activeTab">
<el-collapse-item name="base">
<!-- class="panel-tab__title" -->
<template #title>
<Icon icon="ep:info-filled" />
常规</template
>
<ElementBaseInfo
:id-edit-disabled="idEditDisabled"
:business-object="elementBusinessObject"
:type="elementType"
:model="model"
/>
</el-collapse-item>
<el-collapse-item name="condition" v-if="elementType === 'Process'" key="message">
<template #title><Icon icon="ep:comment" />消息与信号</template>
<signal-and-massage />
</el-collapse-item>
<el-collapse-item name="condition" v-if="conditionFormVisible" key="condition">
<template #title><Icon icon="ep:promotion" />流转条件</template>
<flow-condition :business-object="elementBusinessObject" :type="elementType" />
</el-collapse-item>
<el-collapse-item name="condition" v-if="formVisible" key="form">
<template #title><Icon icon="ep:list" />表单</template>
<!-- <element-form :id="elementId" :type="elementType" /> -->
友情提示使用
<router-link :to="{ path: '/bpm/manager/form' }"
><el-link type="danger">流程表单</el-link>
</router-link>
替代提供更好的表单设计功能
</el-collapse-item>
<el-collapse-item name="task" v-if="elementType.indexOf('Task') !== -1" key="task">
<template #title><Icon icon="ep:checked" />任务</template>
<element-task :id="elementId" :type="elementType" />
</el-collapse-item>
<el-collapse-item
name="multiInstance"
v-if="elementType.indexOf('Task') !== -1"
key="multiInstance"
>
<template #title><Icon icon="ep:help-filled" />多实例</template>
<element-multi-instance :business-object="elementBusinessObject" :type="elementType" />
</el-collapse-item>
<el-collapse-item name="listeners" key="listeners">
<template #title><Icon icon="ep:bell-filled" />执行监听器</template>
<element-listeners :id="elementId" :type="elementType" />
</el-collapse-item>
<el-collapse-item name="taskListeners" v-if="elementType === 'UserTask'" key="taskListeners">
<template #title><Icon icon="ep:bell-filled" />任务监听器</template>
<user-task-listeners :id="elementId" :type="elementType" />
</el-collapse-item>
<el-collapse-item name="extensions" key="extensions">
<template #title><Icon icon="ep:circle-plus-filled" />扩展属性</template>
<element-properties :id="elementId" :type="elementType" />
</el-collapse-item>
<el-collapse-item name="other" key="other">
<template #title><Icon icon="ep:promotion" />其他</template>
<element-other-config :id="elementId" />
</el-collapse-item>
</el-collapse>
</div>
</template>
<script setup lang="ts" name="MyPropertiesPanel">
import ElementBaseInfo from './base/ElementBaseInfo.vue'
import ElementOtherConfig from './other/ElementOtherConfig.vue'
import ElementTask from './task/ElementTask.vue'
import ElementMultiInstance from './multi-instance/ElementMultiInstance.vue'
import FlowCondition from './flow-condition/FlowCondition.vue'
import SignalAndMassage from './signal-message/SignalAndMessage.vue'
import ElementListeners from './listeners/ElementListeners.vue'
import ElementProperties from './properties/ElementProperties.vue'
// import ElementForm from './form/ElementForm.vue'
import UserTaskListeners from './listeners/UserTaskListeners.vue'
import { provide, ref, watch, onBeforeUnmount, onMounted } from 'vue'
import { ElCollapse, ElCollapseItem, ElLink } from 'element-plus'
/**
* 侧边栏
* @Author MiyueFE
* @Home https://github.com/miyuesc
* @Date 2021年3月31日18:57:51
*/
const props = defineProps({
bpmnModeler: Object,
prefix: {
type: String,
default: 'camunda'
},
width: {
type: Number,
default: 480
},
idEditDisabled: {
type: Boolean,
default: false
},
model: Object //
})
const activeTab = ref('base')
const elementId = ref('')
const elementType = ref('')
const elementBusinessObject = ref({}) // businessObject 使
const conditionFormVisible = ref(false) //
const formVisible = ref(false) //
const bpmnElement = ref()
const timer = ref()
provide('prefix', props.prefix)
provide('width', props.width)
const initModels = () => {
// console.log(props, 'props')
// console.log(props.bpmnModeler, 'sakdjjaskdsajdkasdjkadsjk')
// modeler moddle
// nextTick(() => {
if (!props.bpmnModeler) {
//
timer.value = setTimeout(() => initModels(), 10)
return
}
if (timer.value) {
clearTimeout(timer.value)
window.bpmnInstances = {
modeler: props.bpmnModeler,
modeling: props.bpmnModeler.get('modeling'),
moddle: props.bpmnModeler.get('moddle'),
eventBus: props.bpmnModeler.get('eventBus'),
bpmnFactory: props.bpmnModeler.get('bpmnFactory'),
elementFactory: props.bpmnModeler.get('elementFactory'),
elementRegistry: props.bpmnModeler.get('elementRegistry'),
replace: props.bpmnModeler.get('replace'),
selection: props.bpmnModeler.get('selection')
}
}
console.log(window.bpmnInstances, 'window.bpmnInstances')
getActiveElement()
// })
}
const getActiveElement = () => {
// bpmn:Process
initFormOnChanged(null)
props.bpmnModeler.on('import.done', (e) => {
console.log(e, 'eeeee')
initFormOnChanged(null)
})
//
props.bpmnModeler.on('selection.changed', ({ newSelection }) => {
initFormOnChanged(newSelection[0] || null)
})
props.bpmnModeler.on('element.changed', ({ element }) => {
// ""
if (element && element.id === elementId.value) {
initFormOnChanged(element)
}
})
}
//
const initFormOnChanged = (element) => {
let activatedElement = element
if (!activatedElement) {
activatedElement =
window.bpmnInstances.elementRegistry.find((el) => el.type === 'bpmn:Process') ??
window.bpmnInstances.elementRegistry.find((el) => el.type === 'bpmn:Collaboration')
}
if (!activatedElement) return
console.log(`
----------
select element changed:
id: ${activatedElement.id}
type: ${activatedElement.businessObject.$type}
----------
`)
console.log('businessObject: ', activatedElement.businessObject)
window.bpmnInstances.bpmnElement = activatedElement
bpmnElement.value = activatedElement
elementId.value = activatedElement.id
elementType.value = activatedElement.type.split(':')[1] || ''
elementBusinessObject.value = JSON.parse(JSON.stringify(activatedElement.businessObject))
conditionFormVisible.value = !!(
elementType.value === 'SequenceFlow' &&
activatedElement.source &&
activatedElement.source.type.indexOf('StartEvent') === -1
)
formVisible.value = elementType.value === 'UserTask' || elementType.value === 'StartEvent'
}
onMounted(() => {
setTimeout(() => {
initModels()
}, 100)
})
onBeforeUnmount(() => {
window.bpmnInstances = null
console.log(props, 'props1')
console.log(props.bpmnModeler, 'props.bpmnModeler1')
})
watch(
() => elementId.value,
() => {
activeTab.value = 'base'
}
)
</script>

View File

@ -0,0 +1,176 @@
<template>
<div class="panel-tab__content">
<el-form label-width="90px" :model="needProps" :rules="rules">
<div v-if="needProps.type == 'bpmn:Process'">
<!-- 如果是 Process 信息的时候使用自定义表单 -->
<el-link
href="https://doc.iocoder.cn/bpm/#_3-%E6%B5%81%E7%A8%8B%E5%9B%BE%E7%A4%BA%E4%BE%8B"
type="danger"
target="_blank"
>如何实现实现会签或签</el-link
>
<el-form-item label="流程标识" prop="id">
<el-input
v-model="needProps.id"
placeholder="请输入流标标识"
:disabled="needProps.id !== undefined && needProps.id.length > 0"
@change="handleKeyUpdate"
/>
</el-form-item>
<el-form-item label="流程名称" prop="name">
<el-input
v-model="needProps.name"
placeholder="请输入流程名称"
clearable
@change="handleNameUpdate"
/>
</el-form-item>
</div>
<div v-else>
<el-form-item label="ID">
<el-input v-model="elementBaseInfo.id" clearable @change="updateBaseInfo('id')" />
</el-form-item>
<el-form-item label="名称">
<el-input v-model="elementBaseInfo.name" clearable @change="updateBaseInfo('name')" />
</el-form-item>
</div>
</el-form>
</div>
</template>
<script setup lang="ts" name="ElementBaseInfo">
import { ref, reactive, watch, onMounted, onBeforeUnmount, toRaw } from 'vue'
import { ElLink, ElForm, ElFormItem, ElInput } from 'element-plus'
const props = defineProps({
businessObject: Object,
model: Object //
})
const needProps = ref({})
const bpmnElement = ref()
const elementBaseInfo = ref({})
//
// const forms = ref([])
//
const rules = reactive({
id: [{ required: true, message: '流程标识不能为空', trigger: 'blur' }],
name: [{ required: true, message: '流程名称不能为空', trigger: 'blur' }]
})
const resetBaseInfo = () => {
console.log(window, 'window')
console.log(bpmnElement.value, 'bpmnElement')
bpmnElement.value = window?.bpmnInstances?.bpmnElement
console.log(bpmnElement.value, 'resetBaseInfo11111111111')
elementBaseInfo.value = bpmnElement.value.businessObject
needProps.value['type'] = bpmnElement.value.businessObject.$type
// elementBaseInfo.value['typess'] = bpmnElement.value.businessObject.$type
// elementBaseInfo.value = JSON.parse(JSON.stringify(bpmnElement.value.businessObject))
console.log(elementBaseInfo.value, 'elementBaseInfo22222222222')
}
const handleKeyUpdate = (value) => {
// value XML NCName
if (!value) {
return
}
if (!value.match(/[a-zA-Z_][\-_.0-9a-zA-Z$]*/)) {
console.log('key 不满足 XML NCName 规则,所以不进行赋值')
return
}
console.log('key 满足 XML NCName 规则,所以进行赋值')
// BPMN XML key id
elementBaseInfo.value['id'] = value
setTimeout(() => {
updateBaseInfo('id')
}, 100)
}
const handleNameUpdate = (value) => {
console.log(elementBaseInfo, 'elementBaseInfo')
if (!value) {
return
}
elementBaseInfo.value['name'] = value
setTimeout(() => {
updateBaseInfo('name')
}, 100)
}
// const handleDescriptionUpdate=(value)=> {
// TODO documentation
// this.elementBaseInfo['documentation'] = value;
// this.updateBaseInfo('documentation');
// }
const updateBaseInfo = (key) => {
console.log(key, 'key')
// elementBaseInfo
const attrObj = Object.create(null)
// console.log(attrObj, 'attrObj')
attrObj[key] = elementBaseInfo.value[key]
// console.log(attrObj, 'attrObj111')
// const attrObj = {
// id: elementBaseInfo.value[key]
// // di: { id: `${elementBaseInfo.value[key]}_di` }
// }
console.log(elementBaseInfo, 'elementBaseInfo11111111111')
needProps.value = { ...elementBaseInfo.value, ...needProps.value }
if (key === 'id') {
console.log('jinru')
console.log(window, 'window')
console.log(bpmnElement.value, 'bpmnElement')
console.log(toRaw(bpmnElement.value), 'bpmnElement')
window.bpmnInstances.modeling.updateProperties(toRaw(bpmnElement.value), {
id: elementBaseInfo.value[key],
di: { id: `${elementBaseInfo.value[key]}_di` }
})
} else {
console.log(attrObj, 'attrObj')
window.bpmnInstances.modeling.updateProperties(toRaw(bpmnElement.value), attrObj)
}
}
onMounted(() => {
// bpmn 1 key name
setTimeout(() => {
console.log(props.model, 'props.model')
handleKeyUpdate(props.model.key)
handleNameUpdate(props.model.name)
console.log(props, 'propsssssssssssssssssssss')
}, 1000)
})
watch(
() => props.businessObject,
(val) => {
console.log(val, 'val11111111111111111111')
if (val) {
// nextTick(() => {
resetBaseInfo()
// })
}
}
)
// watch(
// () => ({ ...props }),
// (oldVal, newVal) => {
// console.log(oldVal, 'oldVal')
// console.log(newVal, 'newVal')
// if (newVal) {
// needProps.value = newVal
// }
// },
// {
// immediate: true
// }
// )
// 'model.key': {
// immediate: false,
// handler: function (val) {
// this.handleKeyUpdate(val)
// }
// }
onBeforeUnmount(() => {
bpmnElement.value = null
})
</script>

View File

@ -0,0 +1,188 @@
<template>
<div class="panel-tab__content">
<el-form :model="flowConditionForm" label-width="90px" size="small">
<el-form-item label="流转类型">
<el-select v-model="flowConditionForm.type" @change="updateFlowType">
<el-option label="普通流转路径" value="normal" />
<el-option label="默认流转路径" value="default" />
<el-option label="条件流转路径" value="condition" />
</el-select>
</el-form-item>
<el-form-item label="条件格式" v-if="flowConditionForm.type === 'condition'" key="condition">
<el-select v-model="flowConditionForm.conditionType">
<el-option label="表达式" value="expression" />
<el-option label="脚本" value="script" />
</el-select>
</el-form-item>
<el-form-item
label="表达式"
v-if="flowConditionForm.conditionType && flowConditionForm.conditionType === 'expression'"
key="express"
>
<el-input
v-model="flowConditionForm.body"
style="width: 192px"
clearable
@change="updateFlowCondition"
/>
</el-form-item>
<template
v-if="flowConditionForm.conditionType && flowConditionForm.conditionType === 'script'"
>
<el-form-item label="脚本语言" key="language">
<el-input v-model="flowConditionForm.language" clearable @change="updateFlowCondition" />
</el-form-item>
<el-form-item label="脚本类型" key="scriptType">
<el-select v-model="flowConditionForm.scriptType">
<el-option label="内联脚本" value="inlineScript" />
<el-option label="外部脚本" value="externalScript" />
</el-select>
</el-form-item>
<el-form-item
label="脚本"
v-if="flowConditionForm.scriptType === 'inlineScript'"
key="body"
>
<el-input
v-model="flowConditionForm.body"
type="textarea"
clearable
@change="updateFlowCondition"
/>
</el-form-item>
<el-form-item
label="资源地址"
v-if="flowConditionForm.scriptType === 'externalScript'"
key="resource"
>
<el-input v-model="flowConditionForm.resource" clearable @change="updateFlowCondition" />
</el-form-item>
</template>
</el-form>
</div>
</template>
<script setup lang="ts" name="FlowCondition">
import { ref, nextTick, watch, onBeforeUnmount, toRaw } from 'vue'
import { ElSelect, ElForm, ElFormItem, ElInput, ElOption } from 'element-plus'
const props = defineProps({
businessObject: Object,
type: String
})
const flowConditionForm = ref({})
const bpmnElement = ref()
const bpmnElementSource = ref()
const bpmnElementSourceRef = ref()
const flowConditionRef = ref()
const resetFlowCondition = () => {
bpmnElement.value = window.bpmnInstances.bpmnElement
bpmnElementSource.value = bpmnElement.value.source
bpmnElementSourceRef.value = bpmnElement.value.businessObject.sourceRef
if (
bpmnElementSourceRef.value &&
bpmnElementSourceRef.value.default &&
bpmnElementSourceRef.value.default.id === this.bpmnElement.id
) {
//
flowConditionForm.value = { type: 'default' }
} else if (!bpmnElement.value.businessObject.conditionExpression) {
//
flowConditionForm.value = { type: 'normal' }
} else {
//
const conditionExpression = bpmnElement.value.businessObject.conditionExpression
flowConditionForm.value = { ...conditionExpression, type: 'condition' }
// resource
if (flowConditionForm.value.resource) {
// this.$set(this.flowConditionForm, "conditionType", "script");
// this.$set(this.flowConditionForm, "scriptType", "externalScript");
flowConditionForm.value['conditionType'] = 'script'
flowConditionForm.value['scriptType'] = 'externalScript'
return
}
if (conditionExpression.language) {
// this.$set(this.flowConditionForm, "conditionType", "script");
// this.$set(this.flowConditionForm, "scriptType", "inlineScript");
flowConditionForm.value['conditionType'] = 'script'
flowConditionForm.value['scriptType'] = 'inlineScript'
return
}
// this.$set(this.flowConditionForm, "conditionType", "expression");
flowConditionForm.value['conditionType'] = 'expression'
}
}
const updateFlowType = (flowType) => {
//
if (flowType === 'condition') {
flowConditionRef.value = window.bpmnInstances.moddle.create('bpmn:FormalExpression')
window.bpmnInstances.modeling.updateProperties(toRaw(bpmnElement.value), {
conditionExpression: flowConditionRef.value
})
return
}
//
if (flowType === 'default') {
window.bpmnInstances.modeling.updateProperties(toRaw(bpmnElement.value), {
conditionExpression: null
})
window.bpmnInstances.modeling.updateProperties(toRaw(bpmnElementSource.value), {
default: bpmnElement.value
})
return
}
// 线
if (
bpmnElementSourceRef.value.default &&
bpmnElementSourceRef.value.default.id === bpmnElement.value.id
) {
window.bpmnInstances.modeling.updateProperties(toRaw(bpmnElementSource.value), {
default: null
})
}
window.bpmnInstances.modeling.updateProperties(toRaw(bpmnElement.value), {
conditionExpression: null
})
}
const updateFlowCondition = () => {
let { conditionType, scriptType, body, resource, language } = flowConditionForm.value
let condition
if (conditionType === 'expression') {
condition = window.bpmnInstances.moddle.create('bpmn:FormalExpression', { body })
} else {
if (scriptType === 'inlineScript') {
condition = window.bpmnInstances.moddle.create('bpmn:FormalExpression', { body, language })
// this.$set(this.flowConditionForm, "resource", "");
flowConditionForm.value['resource'] = ''
} else {
// this.$set(this.flowConditionForm, "body", "");
flowConditionForm.value['body'] = ''
condition = window.bpmnInstances.moddle.create('bpmn:FormalExpression', {
resource,
language
})
}
}
window.bpmnInstances.modeling.updateProperties(toRaw(bpmnElement.value), {
conditionExpression: condition
})
}
onBeforeUnmount(() => {
bpmnElement.value = null
bpmnElementSource.value = null
bpmnElementSourceRef.value = null
})
watch(
() => props.businessObject,
(val) => {
if (val) {
nextTick(() => {
resetFlowCondition()
})
}
}
)
</script>

View File

@ -0,0 +1,458 @@
<template>
<div class="panel-tab__content">
<el-form label-width="80px">
<el-form-item label="表单标识">
<el-input v-model="formKey" clearable @change="updateElementFormKey" />
</el-form-item>
<el-form-item label="业务标识">
<el-select v-model="businessKey" @change="updateElementBusinessKey">
<el-option v-for="i in fieldList" :key="i.id" :value="i.id" :label="i.label" />
<el-option label="无" value="" />
</el-select>
</el-form-item>
</el-form>
<!--字段列表-->
<div class="element-property list-property">
<el-divider><Icon icon="ep:coin" /> 表单字段</el-divider>
<el-table :data="fieldList" max-height="240" border fit>
<el-table-column label="序号" type="index" width="50px" />
<el-table-column label="字段名称" prop="label" min-width="80px" show-overflow-tooltip />
<el-table-column
label="字段类型"
prop="type"
min-width="80px"
:formatter="(row) => fieldType[row.type] || row.type"
show-overflow-tooltip
/>
<el-table-column
label="默认值"
prop="defaultValue"
min-width="80px"
show-overflow-tooltip
/>
<el-table-column label="操作" width="90px">
<template #default="scope">
<el-button type="text" @click="openFieldForm(scope, scope.$index)">编辑</el-button>
<el-divider direction="vertical" />
<el-button type="text" style="color: #ff4d4f" @click="removeField(scope, scope.$index)"
>移除</el-button
>
</template>
</el-table-column>
</el-table>
</div>
<div class="element-drawer__button">
<XButton type="primary" proIcon="ep:plus" title="添加字段" @click="openFieldForm(null, -1)" />
</div>
<!--字段配置侧边栏-->
<el-drawer
v-model="fieldModelVisible"
title="字段配置"
:size="`${width}px`"
append-to-body
destroy-on-close
>
<el-form :model="formFieldForm" label-width="90px">
<el-form-item label="字段ID">
<el-input v-model="formFieldForm.id" clearable />
</el-form-item>
<el-form-item label="类型">
<el-select
v-model="formFieldForm.typeType"
placeholder="请选择字段类型"
clearable
@change="changeFieldTypeType"
>
<el-option v-for="(value, key) of fieldType" :label="value" :value="key" :key="key" />
</el-select>
</el-form-item>
<el-form-item label="类型名称" v-if="formFieldForm.typeType === 'custom'">
<el-input v-model="formFieldForm.type" clearable />
</el-form-item>
<el-form-item label="名称">
<el-input v-model="formFieldForm.label" clearable />
</el-form-item>
<el-form-item label="时间格式" v-if="formFieldForm.typeType === 'date'">
<el-input v-model="formFieldForm.datePattern" clearable />
</el-form-item>
<el-form-item label="默认值">
<el-input v-model="formFieldForm.defaultValue" clearable />
</el-form-item>
</el-form>
<!-- 枚举值设置 -->
<template v-if="formFieldForm.type === 'enum'">
<el-divider key="enum-divider" />
<p class="listener-filed__title" key="enum-title">
<span><Icon icon="ep:menu" />枚举值列表</span>
<el-button type="primary" @click="openFieldOptionForm(null, -1, 'enum')"
>添加枚举值</el-button
>
</p>
<el-table :data="fieldEnumList" key="enum-table" max-height="240" border fit>
<el-table-column label="序号" width="50px" type="index" />
<el-table-column label="枚举值编号" prop="id" min-width="100px" show-overflow-tooltip />
<el-table-column label="枚举值名称" prop="name" min-width="100px" show-overflow-tooltip />
<el-table-column label="操作" width="90px">
<template #default="scope">
<el-button type="text" @click="openFieldOptionForm(scope, scope.$index, 'enum')"
>编辑</el-button
>
<el-divider direction="vertical" />
<el-button
type="text"
style="color: #ff4d4f"
@click="removeFieldOptionItem(scope, scope.$index, 'enum')"
>移除</el-button
>
</template>
</el-table-column>
</el-table>
</template>
<!-- 校验规则 -->
<el-divider key="validation-divider" />
<p class="listener-filed__title" key="validation-title">
<span><Icon icon="ep:menu" />约束条件列表</span>
<el-button type="primary" @click="openFieldOptionForm(null, -1, 'constraint')"
>添加约束</el-button
>
</p>
<el-table :data="fieldConstraintsList" key="validation-table" max-height="240" border fit>
<el-table-column label="序号" width="50px" type="index" />
<el-table-column label="约束名称" prop="name" min-width="100px" show-overflow-tooltip />
<el-table-column label="约束配置" prop="config" min-width="100px" show-overflow-tooltip />
<el-table-column label="操作" width="90px">
<template #default="scope">
<el-button type="text" @click="openFieldOptionForm(scope, scope.$index, 'constraint')"
>编辑</el-button
>
<el-divider direction="vertical" />
<el-button
type="text"
style="color: #ff4d4f"
@click="removeFieldOptionItem(scope, scope.$index, 'constraint')"
>移除</el-button
>
</template>
</el-table-column>
</el-table>
<!-- 表单属性 -->
<el-divider key="property-divider" />
<p class="listener-filed__title" key="property-title">
<span><Icon icon="ep:menu" />字段属性列表</span>
<el-button type="primary" @click="openFieldOptionForm(null, -1, 'property')"
>添加属性</el-button
>
</p>
<el-table :data="fieldPropertiesList" key="property-table" max-height="240" border fit>
<el-table-column label="序号" width="50px" type="index" />
<el-table-column label="属性编号" prop="id" min-width="100px" show-overflow-tooltip />
<el-table-column label="属性值" prop="value" min-width="100px" show-overflow-tooltip />
<el-table-column label="操作" width="90px">
<template #default="scope">
<el-button type="text" @click="openFieldOptionForm(scope, scope.$index, 'property')"
>编辑</el-button
>
<el-divider direction="vertical" />
<el-button
type="text"
style="color: #ff4d4f"
@click="removeFieldOptionItem(scope, scope.$index, 'property')"
>移除</el-button
>
</template>
</el-table-column>
</el-table>
<!-- 底部按钮 -->
<div class="element-drawer__button">
<el-button> </el-button>
<el-button type="primary" @click="saveField"> </el-button>
</div>
</el-drawer>
<el-dialog
v-model="fieldOptionModelVisible"
:title="optionModelTitle"
width="600px"
append-to-body
destroy-on-close
>
<el-form :model="fieldOptionForm" label-width="96px">
<el-form-item label="编号/ID" v-if="fieldOptionType !== 'constraint'" key="option-id">
<el-input v-model="fieldOptionForm.id" clearable />
</el-form-item>
<el-form-item label="名称" v-if="fieldOptionType !== 'property'" key="option-name">
<el-input v-model="fieldOptionForm.name" clearable />
</el-form-item>
<el-form-item label="配置" v-if="fieldOptionType === 'constraint'" key="option-config">
<el-input v-model="fieldOptionForm.config" clearable />
</el-form-item>
<el-form-item label="值" v-if="fieldOptionType === 'property'" key="option-value">
<el-input v-model="fieldOptionForm.value" clearable />
</el-form-item>
</el-form>
<template #footer>
<el-button @click="fieldOptionModelVisible = false"> </el-button>
<el-button type="primary" @click="saveFieldOption"> </el-button>
</template>
</el-dialog>
</div>
</template>
<script setup lang="ts" name="ElementForm">
import { ref, inject, watch, nextTick, toRaw } from 'vue'
import {
ElDialog,
ElForm,
ElFormItem,
ElSelect,
ElOption,
ElDivider,
ElTable,
ElTableColumn,
ElButton,
ElDrawer,
ElInput
} from 'element-plus'
const props = defineProps({
id: String,
type: String
})
const prefix = inject('prefix')
const width = inject('width')
const formKey = ref('')
const businessKey = ref('')
const optionModelTitle = ref('')
const fieldList = ref([])
const formFieldForm = ref({})
const fieldType = ref({
long: '长整型',
string: '字符串',
boolean: '布尔类',
date: '日期类',
enum: '枚举类',
custom: '自定义类型'
})
const formFieldIndex = ref(-1) // -1
const formFieldOptionIndex = ref(-1) // -1
const fieldModelVisible = ref(false)
const fieldOptionModelVisible = ref(false)
const fieldOptionForm = ref({}) //
const fieldOptionType = ref('') //
const fieldEnumList = ref([]) //
const fieldConstraintsList = ref([]) //
const fieldPropertiesList = ref([]) //
const bpmnELement = ref()
const elExtensionElements = ref()
const formData = ref()
const otherExtensions = ref()
const resetFormList = () => {
bpmnELement.value = window.bpmnInstances.bpmnElement
formKey.value = bpmnELement.value.businessObject.formKey
//
elExtensionElements.value =
bpmnELement.value.businessObject.get('extensionElements') ||
window.bpmnInstances.moddle.create('bpmn:ExtensionElements', { values: [] })
//
formData.value =
elExtensionElements.value.values.filter((ex) => ex.$type === `${prefix}:FormData`)?.[0] ||
window.bpmnInstances.moddle.create(`${prefix}:FormData`, { fields: [] })
// businessKey formData
businessKey.value = formData.value.businessKey
// 便
otherExtensions.value = elExtensionElements.value.values.filter(
(ex) => ex.$type !== `${prefix}:FormData`
)
//
fieldList.value = JSON.parse(JSON.stringify(formData.value.fields || []))
//
updateElementExtensions()
}
const updateElementFormKey = () => {
window.bpmnInstances.modeling.updateProperties(toRaw(bpmnELement.value), {
formKey: formKey.value
})
}
const updateElementBusinessKey = () => {
window.bpmnInstances.modeling.updateModdleProperties(toRaw(bpmnELement.value), formData.value, {
businessKey: businessKey.value
})
}
// type
const changeFieldTypeType = (type) => {
// this.$set(this.formFieldForm, "type", type === "custom" ? "" : type);
formFieldForm.value['type'] = type === 'custom' ? '' : type
}
//
const openFieldForm = (field, index) => {
formFieldIndex.value = index
if (index !== -1) {
const FieldObject = formData.value.fields[index]
formFieldForm.value = JSON.parse(JSON.stringify(field))
//
// this.$set(this.formFieldForm, "typeType", !this.fieldType[field.type] ? "custom" : field.type);
formFieldForm.value['typeType'] = !fieldType.value[field.type] ? 'custom' : field.type
//
field.type === 'enum' &&
(fieldEnumList.value = JSON.parse(JSON.stringify(FieldObject?.values || [])))
//
fieldConstraintsList.value = JSON.parse(
JSON.stringify(FieldObject?.validation?.constraints || [])
)
//
fieldPropertiesList.value = JSON.parse(JSON.stringify(FieldObject?.properties?.values || []))
} else {
formFieldForm.value = {}
//
fieldEnumList.value = []
//
fieldConstraintsList.value = []
//
fieldPropertiesList.value = []
}
fieldModelVisible.value = true
}
//
const openFieldOptionForm = (option, index, type) => {
fieldOptionModelVisible.value = true
fieldOptionType.value = type
formFieldOptionIndex.value = index
if (type === 'property') {
fieldOptionForm.value = option ? JSON.parse(JSON.stringify(option)) : {}
return (optionModelTitle.value = '属性配置')
}
if (type === 'enum') {
fieldOptionForm.value = option ? JSON.parse(JSON.stringify(option)) : {}
return (optionModelTitle.value = '枚举值配置')
}
fieldOptionForm.value = option ? JSON.parse(JSON.stringify(option)) : {}
return (optionModelTitle.value = '约束条件配置')
}
//
const saveFieldOption = () => {
if (formFieldOptionIndex.value === -1) {
if (fieldOptionType.value === 'property') {
fieldPropertiesList.value.push(fieldOptionForm.value)
}
if (fieldOptionType.value === 'constraint') {
fieldConstraintsList.value.push(fieldOptionForm.value)
}
if (fieldOptionType.value === 'enum') {
fieldEnumList.value.push(fieldOptionForm.value)
}
} else {
fieldOptionType.value === 'property' &&
fieldPropertiesList.value.splice(formFieldOptionIndex.value, 1, fieldOptionForm.value)
fieldOptionType.value === 'constraint' &&
fieldConstraintsList.value.splice(formFieldOptionIndex.value, 1, fieldOptionForm.value)
fieldOptionType.value === 'enum' &&
fieldEnumList.value.splice(formFieldOptionIndex.value, 1, fieldOptionForm.value)
}
fieldOptionModelVisible.value = false
fieldOptionForm.value = {}
}
//
const saveField = () => {
const { id, type, label, defaultValue, datePattern } = formFieldForm.value
const Field = window.bpmnInstances.moddle.create(`${prefix}:FormField`, { id, type, label })
defaultValue && (Field.defaultValue = defaultValue)
datePattern && (Field.datePattern = datePattern)
//
if (fieldPropertiesList.value && fieldPropertiesList.value.length) {
const fieldPropertyList = fieldPropertiesList.value.map((fp) => {
return window.bpmnInstances.moddle.create(`${prefix}:Property`, {
id: fp.id,
value: fp.value
})
})
Field.properties = window.bpmnInstances.moddle.create(`${this.prefix}:Properties`, {
values: fieldPropertyList
})
}
//
if (fieldConstraintsList.value && fieldConstraintsList.value.length) {
const fieldConstraintList = fieldConstraintsList.value.map((fc) => {
return window.bpmnInstances.moddle.create(`${prefix}:Constraint`, {
name: fc.name,
config: fc.config
})
})
Field.validation = window.bpmnInstances.moddle.create(`${prefix}:Validation`, {
constraints: fieldConstraintList
})
}
//
if (fieldEnumList.value && fieldEnumList.value.length) {
Field.values = fieldEnumList.value.map((fe) => {
return window.bpmnInstances.moddle.create(`${prefix}:Value`, { name: fe.name, id: fe.id })
})
}
//
if (formFieldIndex.value === -1) {
fieldList.value.push(formFieldForm.value)
formData.value.fields.push(Field)
} else {
fieldList.value.splice(formFieldIndex.value, 1, formFieldForm.value)
formData.value.fields.splice(formFieldIndex.value, 1, Field)
}
updateElementExtensions()
fieldModelVisible.value = false
}
//
const removeFieldOptionItem = (option, index, type) => {
console.log(option, 'option')
if (type === 'property') {
fieldPropertiesList.value.splice(index, 1)
return
}
if (type === 'enum') {
fieldEnumList.value.splice(index, 1)
return
}
fieldConstraintsList.value.splice(index, 1)
}
//
const removeField = (field, index) => {
console.log(field, 'field')
fieldList.value.splice(index, 1)
formData.value.fields.splice(index, 1)
updateElementExtensions()
}
const updateElementExtensions = () => {
//
const newElExtensionElements = window.bpmnInstances.moddle.create(`bpmn:ExtensionElements`, {
values: otherExtensions.value.concat(formData.value)
})
//
window.bpmnInstances.modeling.updateProperties(toRaw(bpmnELement.value), {
extensionElements: newElExtensionElements
})
}
watch(
() => props.id,
(val) => {
val &&
val.length &&
nextTick(() => {
resetFormList()
})
},
{ immediate: true }
)
</script>

View File

@ -0,0 +1,7 @@
import MyPropertiesPanel from "./PropertiesPanel.vue";
MyPropertiesPanel.install = function(Vue) {
Vue.component(MyPropertiesPanel.name, MyPropertiesPanel);
};
export default MyPropertiesPanel;

View File

@ -0,0 +1,416 @@
<template>
<div class="panel-tab__content">
<el-table :data="elementListenersList" size="small" border>
<el-table-column label="序号" width="50px" type="index" />
<el-table-column label="事件类型" min-width="100px" prop="event" />
<el-table-column
label="监听器类型"
min-width="100px"
show-overflow-tooltip
:formatter="(row) => listenerTypeObject[row.listenerType]"
/>
<el-table-column label="操作" width="100px">
<template #default="scope">
<el-button size="small" link @click="openListenerForm(scope.row, scope.$index)"
>编辑</el-button
>
<el-divider direction="vertical" />
<el-button
size="small"
link
style="color: #ff4d4f"
@click="removeListener(scope.row, scope.$index)"
>移除</el-button
>
</template>
</el-table-column>
</el-table>
<div class="element-drawer__button">
<XButton
type="primary"
preIcon="ep:plus"
title="添加监听器"
@click="openListenerForm(null)"
/>
</div>
<!-- 监听器 编辑/创建 部分 -->
<el-drawer
v-model="listenerFormModelVisible"
title="执行监听器"
:size="`${width}px`"
append-to-body
destroy-on-close
>
<el-form :model="listenerForm" label-width="96px" ref="listenerFormRef">
<el-form-item
label="事件类型"
prop="event"
:rules="{ required: true, trigger: ['blur', 'change'] }"
>
<el-select v-model="listenerForm.event">
<el-option label="start" value="start" />
<el-option label="end" value="end" />
</el-select>
</el-form-item>
<el-form-item
label="监听器类型"
prop="listenerType"
:rules="{ required: true, trigger: ['blur', 'change'] }"
>
<el-select v-model="listenerForm.listenerType">
<el-option
v-for="i in Object.keys(listenerTypeObject)"
:key="i"
:label="listenerTypeObject[i]"
:value="i"
/>
</el-select>
</el-form-item>
<el-form-item
v-if="listenerForm.listenerType === 'classListener'"
label="Java类"
prop="class"
key="listener-class"
:rules="{ required: true, trigger: ['blur', 'change'] }"
>
<el-input v-model="listenerForm.class" clearable />
</el-form-item>
<el-form-item
v-if="listenerForm.listenerType === 'expressionListener'"
label="表达式"
prop="expression"
key="listener-expression"
:rules="{ required: true, trigger: ['blur', 'change'] }"
>
<el-input v-model="listenerForm.expression" clearable />
</el-form-item>
<el-form-item
v-if="listenerForm.listenerType === 'delegateExpressionListener'"
label="代理表达式"
prop="delegateExpression"
key="listener-delegate"
:rules="{ required: true, trigger: ['blur', 'change'] }"
>
<el-input v-model="listenerForm.delegateExpression" clearable />
</el-form-item>
<template v-if="listenerForm.listenerType === 'scriptListener'">
<el-form-item
label="脚本格式"
prop="scriptFormat"
key="listener-script-format"
:rules="{ required: true, trigger: ['blur', 'change'], message: '请填写脚本格式' }"
>
<el-input v-model="listenerForm.scriptFormat" clearable />
</el-form-item>
<el-form-item
label="脚本类型"
prop="scriptType"
key="listener-script-type"
:rules="{ required: true, trigger: ['blur', 'change'], message: '请选择脚本类型' }"
>
<el-select v-model="listenerForm.scriptType">
<el-option label="内联脚本" value="inlineScript" />
<el-option label="外部脚本" value="externalScript" />
</el-select>
</el-form-item>
<el-form-item
v-if="listenerForm.scriptType === 'inlineScript'"
label="脚本内容"
prop="value"
key="listener-script"
:rules="{ required: true, trigger: ['blur', 'change'], message: '请填写脚本内容' }"
>
<el-input v-model="listenerForm.value" clearable />
</el-form-item>
<el-form-item
v-if="listenerForm.scriptType === 'externalScript'"
label="资源地址"
prop="resource"
key="listener-resource"
:rules="{ required: true, trigger: ['blur', 'change'], message: '请填写资源地址' }"
>
<el-input v-model="listenerForm.resource" clearable />
</el-form-item>
</template>
</el-form>
<el-divider />
<p class="listener-filed__title">
<span><Icon icon="ep:menu" />注入字段</span>
<XButton type="primary" @click="openListenerFieldForm(null)" title="添加字段" />
</p>
<el-table
:data="fieldsListOfListener"
size="small"
max-height="240"
border
fit
style="flex: none"
>
<el-table-column label="序号" width="50px" type="index" />
<el-table-column label="字段名称" min-width="100px" prop="name" />
<el-table-column
label="字段类型"
min-width="80px"
show-overflow-tooltip
:formatter="(row) => fieldTypeObject[row.fieldType]"
/>
<el-table-column
label="字段值/表达式"
min-width="100px"
show-overflow-tooltip
:formatter="(row) => row.string || row.expression"
/>
<el-table-column label="操作" width="130px">
<template #default="scope">
<el-button size="small" link @click="openListenerFieldForm(scope.row, scope.$index)"
>编辑</el-button
>
<el-divider direction="vertical" />
<el-button
size="small"
link
style="color: #ff4d4f"
@click="removeListenerField(scope.row, scope.$index)"
>移除</el-button
>
</template>
</el-table-column>
</el-table>
<div class="element-drawer__button">
<el-button @click="listenerFormModelVisible = false"> </el-button>
<el-button type="primary" @click="saveListenerConfig"> </el-button>
</div>
</el-drawer>
<!-- 注入西段 编辑/创建 部分 -->
<el-dialog
title="字段配置"
v-model="listenerFieldFormModelVisible"
width="600px"
append-to-body
destroy-on-close
>
<el-form
:model="listenerFieldForm"
label-width="96spx"
ref="listenerFieldFormRef"
style="height: 136px"
>
<el-form-item
label="字段名称:"
prop="name"
:rules="{ required: true, trigger: ['blur', 'change'] }"
>
<el-input v-model="listenerFieldForm.name" clearable />
</el-form-item>
<el-form-item
label="字段类型:"
prop="fieldType"
:rules="{ required: true, trigger: ['blur', 'change'] }"
>
<el-select v-model="listenerFieldForm.fieldType">
<el-option
v-for="i in Object.keys(fieldTypeObject)"
:key="i"
:label="fieldTypeObject[i]"
:value="i"
/>
</el-select>
</el-form-item>
<el-form-item
v-if="listenerFieldForm.fieldType === 'string'"
label="字段值:"
prop="string"
key="field-string"
:rules="{ required: true, trigger: ['blur', 'change'] }"
>
<el-input v-model="listenerFieldForm.string" clearable />
</el-form-item>
<el-form-item
v-if="listenerFieldForm.fieldType === 'expression'"
label="表达式:"
prop="expression"
key="field-expression"
:rules="{ required: true, trigger: ['blur', 'change'] }"
>
<el-input v-model="listenerFieldForm.expression" clearable />
</el-form-item>
</el-form>
<template #footer>
<el-button size="small" @click="listenerFieldFormModelVisible = false"> </el-button>
<el-button size="small" type="primary" @click="saveListenerFiled"> </el-button>
</template>
</el-dialog>
</div>
</template>
<script setup lang="ts" name="ElementListeners">
import { ref, inject, watch, nextTick } from 'vue'
import {
ElMessageBox,
ElTable,
ElTableColumn,
ElDivider,
ElOption,
ElSelect,
ElInput,
ElDrawer,
ElDialog,
ElForm,
ElFormItem
} from 'element-plus'
import { createListenerObject, updateElementExtensions } from '../../utils'
import { initListenerType, initListenerForm, listenerType, fieldType } from './utilSelf'
const props = defineProps({
id: String,
type: String
})
const prefix = inject('prefix')
const width = inject('width')
const elementListenersList = ref([]) //
const listenerForm = ref({}) //
const listenerFormModelVisible = ref(false) //
const fieldsListOfListener = ref([])
const listenerFieldForm = ref({}) //
const listenerFieldFormModelVisible = ref(false) //
const editingListenerIndex = ref(-1) // -1
const editingListenerFieldIndex = ref(-1) // -1
const listenerTypeObject = ref(listenerType)
const fieldTypeObject = ref(fieldType)
const bpmnElement = ref()
const otherExtensionList = ref()
const bpmnElementListeners = ref()
const listenerFormRef = ref()
const listenerFieldFormRef = ref()
const resetListenersList = () => {
bpmnElement.value = window.bpmnInstances.bpmnElement
otherExtensionList.value = []
bpmnElementListeners.value =
bpmnElement.value.businessObject?.extensionElements?.values?.filter(
(ex) => ex.$type === `${prefix}:ExecutionListener`
) ?? []
elementListenersList.value = bpmnElementListeners.value.map((listener) =>
initListenerType(listener)
)
}
//
const openListenerForm = (listener, index) => {
if (listener) {
listenerForm.value = initListenerForm(listener)
editingListenerIndex.value = index
} else {
listenerForm.value = {}
editingListenerIndex.value = -1 //
}
if (listener && listener.fields) {
fieldsListOfListener.value = listener.fields.map((field) => ({
...field,
fieldType: field.string ? 'string' : 'expression'
}))
} else {
fieldsListOfListener.value = []
listenerForm.value['fields'] = []
}
//
listenerFormModelVisible.value = true
nextTick(() => {
if (listenerFormRef.value) {
listenerFormRef.value.clearValidate()
}
})
}
//
const openListenerFieldForm = (field, index) => {
listenerFieldForm.value = field ? JSON.parse(JSON.stringify(field)) : {}
editingListenerFieldIndex.value = field ? index : -1
listenerFieldFormModelVisible.value = true
nextTick(() => {
if (listenerFieldFormRef.value) {
listenerFieldFormRef.value.clearValidate()
}
})
}
//
const saveListenerFiled = async () => {
let validateStatus = await listenerFieldFormRef.value.validate()
if (!validateStatus) return //
if (editingListenerFieldIndex.value === -1) {
fieldsListOfListener.value.push(listenerFieldForm.value)
listenerForm.value.fields.push(listenerFieldForm.value)
} else {
fieldsListOfListener.value.splice(editingListenerFieldIndex.value, 1, listenerFieldForm.value)
listenerForm.value.fields.splice(editingListenerFieldIndex.value, 1, listenerFieldForm.value)
}
listenerFieldFormModelVisible.value = false
nextTick(() => {
listenerFieldForm.value = {}
})
}
//
const removeListenerField = (index) => {
ElMessageBox.confirm('确认移除该字段吗?', '提示', {
confirmButtonText: '确 认',
cancelButtonText: '取 消'
})
.then(() => {
fieldsListOfListener.value.splice(index, 1)
listenerForm.value.fields.splice(index, 1)
})
.catch(() => console.info('操作取消'))
}
//
const removeListener = (index) => {
ElMessageBox.confirm('确认移除该监听器吗?', '提示', {
confirmButtonText: '确 认',
cancelButtonText: '取 消'
})
.then(() => {
bpmnElementListeners.value.splice(index, 1)
elementListenersList.value.splice(index, 1)
updateElementExtensions(
bpmnElement.value,
otherExtensionList.value.concat(bpmnElementListeners.value)
)
})
.catch(() => console.info('操作取消'))
}
//
const saveListenerConfig = async () => {
let validateStatus = await listenerFormRef.value.validate()
if (!validateStatus) return //
const listenerObject = createListenerObject(listenerForm.value, false, prefix)
if (editingListenerIndex.value === -1) {
bpmnElementListeners.value.push(listenerObject)
elementListenersList.value.push(listenerForm.value)
} else {
bpmnElementListeners.value.splice(editingListenerIndex.value, 1, listenerObject)
elementListenersList.value.splice(editingListenerIndex.value, 1, listenerForm.value)
}
//
otherExtensionList.value =
bpmnElement.value.businessObject?.extensionElements?.values?.filter(
(ex) => ex.$type !== `${prefix}:ExecutionListener`
) ?? []
updateElementExtensions(
bpmnElement.value,
otherExtensionList.value.concat(bpmnElementListeners.value)
)
// 4.
listenerFormModelVisible.value = false
listenerForm.value = {}
}
watch(
() => props.id,
(val) => {
val &&
val.length &&
nextTick(() => {
resetListenersList()
})
},
{ immediate: true }
)
</script>

View File

@ -0,0 +1,460 @@
<template>
<div class="panel-tab__content">
<el-table :data="elementListenersList" size="small" border>
<el-table-column label="序号" width="50px" type="index" />
<el-table-column
label="事件类型"
min-width="80px"
show-overflow-tooltip
:formatter="(row) => listenerEventTypeObject[row.event]"
/>
<el-table-column label="事件id" min-width="80px" prop="id" show-overflow-tooltip />
<el-table-column
label="监听器类型"
min-width="80px"
show-overflow-tooltip
:formatter="(row) => listenerTypeObject[row.listenerType]"
/>
<el-table-column label="操作" width="90px">
<template #default="scope">
<el-button size="small" link @click="openListenerForm(scope.row, scope.$index)"
>编辑</el-button
>
<el-divider direction="vertical" />
<el-button
size="small"
link
style="color: #ff4d4f"
@click="removeListener(scope.row, scope.$index)"
>移除</el-button
>
</template>
</el-table-column>
</el-table>
<div class="element-drawer__button">
<XButton
size="small"
type="primary"
preIcon="ep:plus"
title="添加监听器"
@click="openListenerForm(null)"
/>
</div>
<!-- 监听器 编辑/创建 部分 -->
<el-drawer
v-model="listenerFormModelVisible"
title="任务监听器"
:size="`${width}px`"
append-to-body
destroy-on-close
>
<el-form size="small" :model="listenerForm" label-width="96px" ref="listenerFormRef">
<el-form-item
label="事件类型"
prop="event"
:rules="{ required: true, trigger: ['blur', 'change'] }"
>
<el-select v-model="listenerForm.event">
<el-option
v-for="i in Object.keys(listenerEventTypeObject)"
:key="i"
:label="listenerEventTypeObject[i]"
:value="i"
/>
</el-select>
</el-form-item>
<el-form-item
label="监听器ID"
prop="id"
:rules="{ required: true, trigger: ['blur', 'change'] }"
>
<el-input v-model="listenerForm.id" clearable />
</el-form-item>
<el-form-item
label="监听器类型"
prop="listenerType"
:rules="{ required: true, trigger: ['blur', 'change'] }"
>
<el-select v-model="listenerForm.listenerType">
<el-option
v-for="i in Object.keys(listenerTypeObject)"
:key="i"
:label="listenerTypeObject[i]"
:value="i"
/>
</el-select>
</el-form-item>
<el-form-item
v-if="listenerForm.listenerType === 'classListener'"
label="Java类"
prop="class"
key="listener-class"
:rules="{ required: true, trigger: ['blur', 'change'] }"
>
<el-input v-model="listenerForm.class" clearable />
</el-form-item>
<el-form-item
v-if="listenerForm.listenerType === 'expressionListener'"
label="表达式"
prop="expression"
key="listener-expression"
:rules="{ required: true, trigger: ['blur', 'change'] }"
>
<el-input v-model="listenerForm.expression" clearable />
</el-form-item>
<el-form-item
v-if="listenerForm.listenerType === 'delegateExpressionListener'"
label="代理表达式"
prop="delegateExpression"
key="listener-delegate"
:rules="{ required: true, trigger: ['blur', 'change'] }"
>
<el-input v-model="listenerForm.delegateExpression" clearable />
</el-form-item>
<template v-if="listenerForm.listenerType === 'scriptListener'">
<el-form-item
label="脚本格式"
prop="scriptFormat"
key="listener-script-format"
:rules="{ required: true, trigger: ['blur', 'change'], message: '请填写脚本格式' }"
>
<el-input v-model="listenerForm.scriptFormat" clearable />
</el-form-item>
<el-form-item
label="脚本类型"
prop="scriptType"
key="listener-script-type"
:rules="{ required: true, trigger: ['blur', 'change'], message: '请选择脚本类型' }"
>
<el-select v-model="listenerForm.scriptType">
<el-option label="内联脚本" value="inlineScript" />
<el-option label="外部脚本" value="externalScript" />
</el-select>
</el-form-item>
<el-form-item
v-if="listenerForm.scriptType === 'inlineScript'"
label="脚本内容"
prop="value"
key="listener-script"
:rules="{ required: true, trigger: ['blur', 'change'], message: '请填写脚本内容' }"
>
<el-input v-model="listenerForm.value" clearable />
</el-form-item>
<el-form-item
v-if="listenerForm.scriptType === 'externalScript'"
label="资源地址"
prop="resource"
key="listener-resource"
:rules="{ required: true, trigger: ['blur', 'change'], message: '请填写资源地址' }"
>
<el-input v-model="listenerForm.resource" clearable />
</el-form-item>
</template>
<template v-if="listenerForm.event === 'timeout'">
<el-form-item label="定时器类型" prop="eventDefinitionType" key="eventDefinitionType">
<el-select v-model="listenerForm.eventDefinitionType">
<el-option label="日期" value="date" />
<el-option label="持续时长" value="duration" />
<el-option label="循环" value="cycle" />
<el-option label="无" value="null" />
</el-select>
</el-form-item>
<el-form-item
v-if="!!listenerForm.eventDefinitionType && listenerForm.eventDefinitionType !== 'null'"
label="定时器"
prop="eventTimeDefinitions"
key="eventTimeDefinitions"
:rules="{ required: true, trigger: ['blur', 'change'], message: '请填写定时器配置' }"
>
<el-input v-model="listenerForm.eventTimeDefinitions" clearable />
</el-form-item>
</template>
</el-form>
<el-divider />
<p class="listener-filed__title">
<span><Icon icon="ep:menu" />注入字段</span>
<el-button size="small" type="primary" @click="openListenerFieldForm(null)"
>添加字段</el-button
>
</p>
<el-table
:data="fieldsListOfListener"
size="small"
max-height="240"
border
fit
style="flex: none"
>
<el-table-column label="序号" width="50px" type="index" />
<el-table-column label="字段名称" min-width="100px" prop="name" />
<el-table-column
label="字段类型"
min-width="80px"
show-overflow-tooltip
:formatter="(row) => fieldTypeObject[row.fieldType]"
/>
<el-table-column
label="字段值/表达式"
min-width="100px"
show-overflow-tooltip
:formatter="(row) => row.string || row.expression"
/>
<el-table-column label="操作" width="100px">
<template #default="scope">
<el-button size="small" link @click="openListenerFieldForm(scope.row, scope.$index)"
>编辑</el-button
>
<el-divider direction="vertical" />
<el-button
size="small"
link
style="color: #ff4d4f"
@click="removeListenerField(scope.row, scope.$index)"
>移除</el-button
>
</template>
</el-table-column>
</el-table>
<div class="element-drawer__button">
<el-button size="small" @click="listenerFormModelVisible = false"> </el-button>
<el-button size="small" type="primary" @click="saveListenerConfig"> </el-button>
</div>
</el-drawer>
<!-- 注入西段 编辑/创建 部分 -->
<el-dialog
title="字段配置"
v-model="listenerFieldFormModelVisible"
width="600px"
append-to-body
destroy-on-close
>
<el-form
:model="listenerFieldForm"
size="small"
label-width="96px"
ref="listenerFieldFormRef"
style="height: 136px"
>
<el-form-item
label="字段名称:"
prop="name"
:rules="{ required: true, trigger: ['blur', 'change'] }"
>
<el-input v-model="listenerFieldForm.name" clearable />
</el-form-item>
<el-form-item
label="字段类型:"
prop="fieldType"
:rules="{ required: true, trigger: ['blur', 'change'] }"
>
<el-select v-model="listenerFieldForm.fieldType">
<el-option
v-for="i in Object.keys(fieldTypeObject)"
:key="i"
:label="fieldTypeObject[i]"
:value="i"
/>
</el-select>
</el-form-item>
<el-form-item
v-if="listenerFieldForm.fieldType === 'string'"
label="字段值:"
prop="string"
key="field-string"
:rules="{ required: true, trigger: ['blur', 'change'] }"
>
<el-input v-model="listenerFieldForm.string" clearable />
</el-form-item>
<el-form-item
v-if="listenerFieldForm.fieldType === 'expression'"
label="表达式:"
prop="expression"
key="field-expression"
:rules="{ required: true, trigger: ['blur', 'change'] }"
>
<el-input v-model="listenerFieldForm.expression" clearable />
</el-form-item>
</el-form>
<template #footer>
<el-button size="small" @click="listenerFieldFormModelVisible = false"> </el-button>
<el-button size="small" type="primary" @click="saveListenerFiled"> </el-button>
</template>
</el-dialog>
</div>
</template>
<script lang="ts" setup name="UserTaskListeners">
import { ref, inject, watch, nextTick } from 'vue'
import {
ElDialog,
ElForm,
ElFormItem,
ElSelect,
ElOption,
ElDivider,
ElTable,
ElTableColumn,
ElMessageBox,
ElButton,
ElDrawer
} from 'element-plus'
import { createListenerObject, updateElementExtensions } from '../../utils'
import { initListenerForm, initListenerType, eventType, listenerType, fieldType } from './utilSelf'
const props = defineProps({
id: String,
type: String
})
const prefix = inject('prefix')
const width = inject('width')
const elementListenersList = ref([])
const listenerEventTypeObject = ref(eventType)
const listenerTypeObject = ref(listenerType)
const listenerFormModelVisible = ref(false)
const listenerForm = ref({})
const fieldTypeObject = ref(fieldType)
const fieldsListOfListener = ref([])
const listenerFieldFormModelVisible = ref(false) //
const editingListenerIndex = ref(-1) // -1
const editingListenerFieldIndex = ref(-1) // -1
const listenerFieldForm = ref({}) //
const bpmnElement = ref()
const bpmnElementListeners = ref()
const otherExtensionList = ref()
const listenerFormRef = ref()
const listenerFieldFormRef = ref()
const resetListenersList = () => {
console.log(
window.bpmnInstances.bpmnElement,
'window.bpmnInstances.bpmnElementwindow.bpmnInstances.bpmnElementwindow.bpmnInstances.bpmnElementwindow.bpmnInstances.bpmnElementwindow.bpmnInstances.bpmnElementwindow.bpmnInstances.bpmnElement'
)
bpmnElement.value = window.bpmnInstances.bpmnElement
otherExtensionList.value = []
bpmnElementListeners.value =
bpmnElement.value.businessObject?.extensionElements?.values.filter(
(ex) => ex.$type === `${prefix}:TaskListener`
) ?? []
elementListenersList.value = bpmnElementListeners.value.map((listener) =>
initListenerType(listener)
)
}
const openListenerForm = (listener, index) => {
if (listener) {
listenerForm.value = initListenerForm(listener)
editingListenerIndex.value = index
} else {
listenerForm.value = {}
editingListenerIndex.value = -1 //
}
if (listener && listener.fields) {
fieldsListOfListener.value = listener.fields.map((field) => ({
...field,
fieldType: field.string ? 'string' : 'expression'
}))
} else {
fieldsListOfListener.value = []
listenerForm.value['fields'] = []
}
//
listenerFormModelVisible.value = true
nextTick(() => {
if (listenerFormRef.value) listenerFormRef.value.clearValidate()
})
}
//
const removeListener = (listener, index) => {
console.log(listener, 'listener')
ElMessageBox.confirm('确认移除该监听器吗?', '提示', {
confirmButtonText: '确 认',
cancelButtonText: '取 消'
})
.then(() => {
bpmnElementListeners.value.splice(index, 1)
elementListenersList.value.splice(index, 1)
updateElementExtensions(
bpmnElement.value,
otherExtensionList.value.concat(bpmnElementListeners.value)
)
})
.catch(() => console.info('操作取消'))
}
//
const saveListenerConfig = async () => {
let validateStatus = await listenerFormRef.value.validate()
if (!validateStatus) return //
const listenerObject = createListenerObject(listenerForm.value, true, prefix)
if (editingListenerIndex.value === -1) {
bpmnElementListeners.value.push(listenerObject)
elementListenersList.value.push(listenerForm.value)
} else {
bpmnElementListeners.value.splice(editingListenerIndex.value, 1, listenerObject)
elementListenersList.value.splice(editingListenerIndex.value, 1, listenerForm.value)
}
//
otherExtensionList.value =
bpmnElement.value.businessObject?.extensionElements?.values?.filter(
(ex) => ex.$type !== `${prefix}:TaskListener`
) ?? []
updateElementExtensions(
bpmnElement.value,
otherExtensionList.value.concat(bpmnElementListeners.value)
)
// 4.
listenerFormModelVisible.value = false
listenerForm.value = {}
}
//
const openListenerFieldForm = (field, index) => {
listenerFieldForm.value = field ? JSON.parse(JSON.stringify(field)) : {}
editingListenerFieldIndex.value = field ? index : -1
listenerFieldFormModelVisible.value = true
nextTick(() => {
if (listenerFieldFormRef.value) listenerFieldFormRef.value.clearValidate()
})
}
//
const saveListenerFiled = async () => {
let validateStatus = await listenerFieldFormRef.value.validate()
if (!validateStatus) return //
if (editingListenerFieldIndex.value === -1) {
fieldsListOfListener.value.push(listenerFieldForm.value)
listenerForm.value.fields.push(listenerFieldForm.value)
} else {
fieldsListOfListener.value.splice(editingListenerFieldIndex.value, 1, listenerFieldForm.value)
listenerForm.value.fields.splice(editingListenerFieldIndex.value, 1, listenerFieldForm.value)
}
listenerFieldFormModelVisible.value = false
nextTick(() => {
listenerFieldForm.value = {}
})
}
//
const removeListenerField = (field, index) => {
console.log(field, 'field')
ElMessageBox.confirm('确认移除该字段吗?', '提示', {
confirmButtonText: '确 认',
cancelButtonText: '取 消'
})
.then(() => {
fieldsListOfListener.value.splice(index, 1)
listenerForm.value.fields.splice(index, 1)
})
.catch(() => console.info('操作取消'))
}
watch(
() => props.id,
(val) => {
val &&
val.length &&
nextTick(() => {
resetListenersList()
})
},
{ immediate: true }
)
</script>

View File

@ -0,0 +1,177 @@
export const template = isTaskListener => {
return `
<div class="panel-tab__content">
<el-table :data="elementListenersList" size="small" border>
<el-table-column label="序号" width="50px" type="index" />
<el-table-column label="事件类型" min-width="100px" prop="event" />
<el-table-column label="监听器类型" min-width="100px" show-overflow-tooltip :formatter="row => listenerTypeObject[row.listenerType]" />
<el-table-column label="操作" width="90px">
<template #default="scope">
<el-button size="small" type="text" @click="openListenerForm(scope, scope.$index)">编辑</el-button>
<el-divider direction="vertical" />
<el-button size="small" type="text" style="color: #ff4d4f" @click="removeListener(scope, scope.$index)">移除</el-button>
</template>
</el-table-column>
</el-table>
<div class="element-drawer__button">
<el-button size="small" type="primary" icon="el-icon-plus" @click="openListenerForm(null)">添加监听器</el-button>
</div>
<!-- 监听器 编辑/创建 部分 -->
<el-drawer :visible.sync="listenerFormModelVisible" title="执行监听器" :size="width + 'px'" append-to-body destroy-on-close>
<el-form size="small" :model="listenerForm" label-width="96px" ref="listenerFormRef" @submit.native.prevent>
<el-form-item label="事件类型" prop="event" :rules="{ required: true, trigger: ['blur', 'change'] }">
<el-select v-model="listenerForm.event">
<el-option label="start" value="start" />
<el-option label="end" value="end" />
</el-select>
</el-form-item>
<el-form-item label="监听器类型" prop="listenerType" :rules="{ required: true, trigger: ['blur', 'change'] }">
<el-select v-model="listenerForm.listenerType">
<el-option v-for="i in Object.keys(listenerTypeObject)" :key="i" :label="listenerTypeObject[i]" :value="i" />
</el-select>
</el-form-item>
<el-form-item
v-if="listenerForm.listenerType === 'classListener'"
label="Java类"
prop="class"
key="listener-class"
:rules="{ required: true, trigger: ['blur', 'change'] }"
>
<el-input v-model="listenerForm.class" clearable />
</el-form-item>
<el-form-item
v-if="listenerForm.listenerType === 'expressionListener'"
label="表达式"
prop="expression"
key="listener-expression"
:rules="{ required: true, trigger: ['blur', 'change'] }"
>
<el-input v-model="listenerForm.expression" clearable />
</el-form-item>
<el-form-item
v-if="listenerForm.listenerType === 'delegateExpressionListener'"
label="代理表达式"
prop="delegateExpression"
key="listener-delegate"
:rules="{ required: true, trigger: ['blur', 'change'] }"
>
<el-input v-model="listenerForm.delegateExpression" clearable />
</el-form-item>
<template v-if="listenerForm.listenerType === 'scriptListener'">
<el-form-item
label="脚本格式"
prop="scriptFormat"
key="listener-script-format"
:rules="{ required: true, trigger: ['blur', 'change'], message: '请填写脚本格式' }"
>
<el-input v-model="listenerForm.scriptFormat" clearable />
</el-form-item>
<el-form-item
label="脚本类型"
prop="scriptType"
key="listener-script-type"
:rules="{ required: true, trigger: ['blur', 'change'], message: '请选择脚本类型' }"
>
<el-select v-model="listenerForm.scriptType">
<el-option label="内联脚本" value="inlineScript" />
<el-option label="外部脚本" value="externalScript" />
</el-select>
</el-form-item>
<el-form-item
v-if="listenerForm.scriptType === 'inlineScript'"
label="脚本内容"
prop="value"
key="listener-script"
:rules="{ required: true, trigger: ['blur', 'change'], message: '请填写脚本内容' }"
>
<el-input v-model="listenerForm.value" clearable />
</el-form-item>
<el-form-item
v-if="listenerForm.scriptType === 'externalScript'"
label="资源地址"
prop="resource"
key="listener-resource"
:rules="{ required: true, trigger: ['blur', 'change'], message: '请填写资源地址' }"
>
<el-input v-model="listenerForm.resource" clearable />
</el-form-item>
</template>
${isTaskListener
? "<el-form-item label='定时器类型' prop='eventDefinitionType' key='eventDefinitionType'>" +
"<el-select v-model='listenerForm.eventDefinitionType'>" +
"<el-option label='日期' value='date' />" +
"<el-option label='持续时长' value='duration' />" +
"<el-option label='循环' value='cycle' />" +
"<el-option label='无' value='' />" +
"</el-select>" +
"</el-form-item>" +
"<el-form-item v-if='!!listenerForm.eventDefinitionType' label='定时器' prop='eventDefinitions' key='eventDefinitions'>" +
"<el-input v-model='listenerForm.eventDefinitions' clearable />" +
"</el-form-item>"
: ""
}
</el-form>
<el-divider />
<p class="listener-filed__title">
<span><i class="el-icon-menu"></i></span>
<el-button size="small" type="primary" @click="openListenerFieldForm(null)">添加字段</el-button>
</p>
<el-table :data="fieldsListOfListener" size="small" max-height="240" border fit style="flex: none">
<el-table-column label="序号" width="50px" type="index" />
<el-table-column label="字段名称" min-width="100px" prop="name" />
<el-table-column label="字段类型" min-width="80px" show-overflow-tooltip :formatter="row => fieldTypeObject[row.fieldType]" />
<el-table-column label="字段值/表达式" min-width="100px" show-overflow-tooltip :formatter="row => row.string || row.expression" />
<el-table-column label="操作" width="100px">
<template #default="scope">
<el-button size="small" type="text" @click="openListenerFieldForm(scope, scope.$index)">编辑</el-button>
<el-divider direction="vertical" />
<el-button size="small" type="text" style="color: #ff4d4f" @click="removeListenerField(scope, scope.$index)">移除</el-button>
</template>
</el-table-column>
</el-table>
<div class="element-drawer__button">
<el-button size="small" @click="listenerFormModelVisible = false"> </el-button>
<el-button size="small" type="primary" @click="saveListenerConfig"> </el-button>
</div>
</el-drawer>
<!-- 注入西段 编辑/创建 部分 -->
<el-dialog title="字段配置" :visible.sync="listenerFieldFormModelVisible" width="600px" append-to-body destroy-on-close>
<el-form :model="listenerFieldForm" size="small" label-width="96px" ref="listenerFieldFormRef" style="height: 136px" @submit.native.prevent>
<el-form-item label="字段名称:" prop="name" :rules="{ required: true, trigger: ['blur', 'change'] }">
<el-input v-model="listenerFieldForm.name" clearable />
</el-form-item>
<el-form-item label="字段类型:" prop="fieldType" :rules="{ required: true, trigger: ['blur', 'change'] }">
<el-select v-model="listenerFieldForm.fieldType">
<el-option v-for="i in Object.keys(fieldTypeObject)" :key="i" :label="fieldTypeObject[i]" :value="i" />
</el-select>
</el-form-item>
<el-form-item
v-if="listenerFieldForm.fieldType === 'string'"
label="字段值:"
prop="string"
key="field-string"
:rules="{ required: true, trigger: ['blur', 'change'] }"
>
<el-input v-model="listenerFieldForm.string" clearable />
</el-form-item>
<el-form-item
v-if="listenerFieldForm.fieldType === 'expression'"
label="表达式:"
prop="expression"
key="field-expression"
:rules="{ required: true, trigger: ['blur', 'change'] }"
>
<el-input v-model="listenerFieldForm.expression" clearable />
</el-form-item>
</el-form>
<template #footer>
<el-button size="small" @click="listenerFieldFormModelVisible = false"> </el-button>
<el-button size="small" type="primary" @click="saveListenerFiled"> </el-button>
</template>
</el-dialog>
</div>
`
}

View File

@ -0,0 +1,62 @@
// 初始化表单数据
export function initListenerForm(listener) {
let self = {
...listener
}
if (listener.script) {
self = {
...listener,
...listener.script,
scriptType: listener.script.resource ? 'externalScript' : 'inlineScript'
}
}
if (listener.event === 'timeout' && listener.eventDefinitions) {
if (listener.eventDefinitions.length) {
let k = ''
for (const key in listener.eventDefinitions[0]) {
console.log(listener.eventDefinitions, key)
if (key.indexOf('time') !== -1) {
k = key
self.eventDefinitionType = key.replace('time', '').toLowerCase()
}
}
console.log(k)
self.eventTimeDefinitions = listener.eventDefinitions[0][k].body
}
}
return self
}
export function initListenerType(listener) {
let listenerType
if (listener.class) listenerType = 'classListener'
if (listener.expression) listenerType = 'expressionListener'
if (listener.delegateExpression) listenerType = 'delegateExpressionListener'
if (listener.script) listenerType = 'scriptListener'
return {
...JSON.parse(JSON.stringify(listener)),
...(listener.script ?? {}),
listenerType: listenerType
}
}
export const listenerType = {
classListener: 'Java 类',
expressionListener: '表达式',
delegateExpressionListener: '代理表达式',
scriptListener: '脚本'
}
export const eventType = {
create: '创建',
assignment: '指派',
complete: '完成',
delete: '删除',
update: '更新',
timeout: '超时'
}
export const fieldType = {
string: '字符串',
expression: '表达式'
}

View File

@ -0,0 +1,255 @@
<template>
<div class="panel-tab__content">
<el-form label-width="90px">
<el-form-item label="回路特性">
<el-select v-model="loopCharacteristics" @change="changeLoopCharacteristicsType">
<!--bpmn:MultiInstanceLoopCharacteristics-->
<el-option label="并行多重事件" value="ParallelMultiInstance" />
<el-option label="时序多重事件" value="SequentialMultiInstance" />
<!--bpmn:StandardLoopCharacteristics-->
<el-option label="循环事件" value="StandardLoop" />
<el-option label="无" value="Null" />
</el-select>
</el-form-item>
<template
v-if="
loopCharacteristics === 'ParallelMultiInstance' ||
loopCharacteristics === 'SequentialMultiInstance'
"
>
<el-form-item label="循环基数" key="loopCardinality">
<el-input
v-model="loopInstanceForm.loopCardinality"
clearable
@change="updateLoopCardinality"
/>
</el-form-item>
<el-form-item label="集合" key="collection" v-show="false">
<el-input v-model="loopInstanceForm.collection" clearable @change="updateLoopBase" />
</el-form-item>
<el-form-item label="元素变量" key="elementVariable">
<el-input v-model="loopInstanceForm.elementVariable" clearable @change="updateLoopBase" />
</el-form-item>
<el-form-item label="完成条件" key="completionCondition">
<el-input
v-model="loopInstanceForm.completionCondition"
clearable
@change="updateLoopCondition"
/>
</el-form-item>
<el-form-item label="异步状态" key="async">
<el-checkbox
v-model="loopInstanceForm.asyncBefore"
label="异步前"
@change="updateLoopAsync('asyncBefore')"
/>
<el-checkbox
v-model="loopInstanceForm.asyncAfter"
label="异步后"
@change="updateLoopAsync('asyncAfter')"
/>
<el-checkbox
v-model="loopInstanceForm.exclusive"
v-if="loopInstanceForm.asyncAfter || loopInstanceForm.asyncBefore"
label="排除"
@change="updateLoopAsync('exclusive')"
/>
</el-form-item>
<el-form-item
label="重试周期"
prop="timeCycle"
v-if="loopInstanceForm.asyncAfter || loopInstanceForm.asyncBefore"
key="timeCycle"
>
<el-input v-model="loopInstanceForm.timeCycle" clearable @change="updateLoopTimeCycle" />
</el-form-item>
</template>
</el-form>
</div>
</template>
<script setup lang="ts" name="ElementMultiInstance">
import { inject, ref, onBeforeUnmount, watch, toRaw } from 'vue'
import { ElForm, ElFormItem, ElSelect, ElOption, ElCheckbox, ElInput } from 'element-plus'
const props = defineProps({
businessObject: Object,
type: String
})
const prefix = inject('prefix')
const loopCharacteristics = ref('')
//
const defaultLoopInstanceForm = ref({
completionCondition: '',
loopCardinality: '',
extensionElements: [],
asyncAfter: false,
asyncBefore: false,
exclusive: false
})
const loopInstanceForm = ref({})
const bpmnElement = ref(null)
const multiLoopInstance = ref(null)
const getElementLoop = (businessObject) => {
if (!businessObject.loopCharacteristics) {
loopCharacteristics.value = 'Null'
loopInstanceForm.value = {}
return
}
if (businessObject.loopCharacteristics.$type === 'bpmn:StandardLoopCharacteristics') {
loopCharacteristics.value = 'StandardLoop'
loopInstanceForm.value = {}
return
}
if (businessObject.loopCharacteristics.isSequential) {
loopCharacteristics.value = 'SequentialMultiInstance'
} else {
loopCharacteristics.value = 'ParallelMultiInstance'
}
//
loopInstanceForm.value = {
...defaultLoopInstanceForm.value,
...businessObject.loopCharacteristics,
completionCondition: businessObject.loopCharacteristics?.completionCondition?.body ?? '',
loopCardinality: businessObject.loopCharacteristics?.loopCardinality?.body ?? ''
}
// businessObject loopCharacteristics
multiLoopInstance.value = window.bpmnInstances.bpmnElement.businessObject.loopCharacteristics
//
if (
businessObject.loopCharacteristics.extensionElements &&
businessObject.loopCharacteristics.extensionElements.values &&
businessObject.loopCharacteristics.extensionElements.values.length
) {
loopInstanceForm.value['timeCycle'] =
businessObject.loopCharacteristics.extensionElements.values[0].body
}
}
const changeLoopCharacteristicsType = (type) => {
// this.loopInstanceForm = { ...this.defaultLoopInstanceForm }; //
//
if (type === 'Null') {
window.bpmnInstances.modeling.updateProperties(toRaw(bpmnElement.value), {
loopCharacteristics: null
})
return
}
//
if (type === 'StandardLoop') {
const loopCharacteristicsObject = window.bpmnInstances.moddle.create(
'bpmn:StandardLoopCharacteristics'
)
window.bpmnInstances.modeling.updateProperties(toRaw(bpmnElement.value), {
loopCharacteristics: loopCharacteristicsObject
})
multiLoopInstance.value = null
return
}
//
if (type === 'SequentialMultiInstance') {
multiLoopInstance.value = window.bpmnInstances.moddle.create(
'bpmn:MultiInstanceLoopCharacteristics',
{ isSequential: true }
)
} else {
multiLoopInstance.value = window.bpmnInstances.moddle.create(
'bpmn:MultiInstanceLoopCharacteristics',
{ collection: '${coll_userList}' }
)
}
window.bpmnInstances.modeling.updateProperties(toRaw(bpmnElement.value), {
loopCharacteristics: toRaw(multiLoopInstance.value)
})
}
//
const updateLoopCardinality = (cardinality) => {
let loopCardinality = null
if (cardinality && cardinality.length) {
loopCardinality = window.bpmnInstances.moddle.create('bpmn:FormalExpression', {
body: cardinality
})
}
window.bpmnInstances.modeling.updateModdleProperties(
toRaw(bpmnElement.value),
multiLoopInstance.value,
{
loopCardinality
}
)
}
//
const updateLoopCondition = (condition) => {
let completionCondition = null
if (condition && condition.length) {
completionCondition = window.bpmnInstances.moddle.create('bpmn:FormalExpression', {
body: condition
})
}
window.bpmnInstances.modeling.updateModdleProperties(
toRaw(bpmnElement.value),
multiLoopInstance.value,
{
completionCondition
}
)
}
//
const updateLoopTimeCycle = (timeCycle) => {
const extensionElements = window.bpmnInstances.moddle.create('bpmn:ExtensionElements', {
values: [
window.bpmnInstances.moddle.create(`${prefix}:FailedJobRetryTimeCycle`, {
body: timeCycle
})
]
})
window.bpmnInstances.modeling.updateModdleProperties(
toRaw(bpmnElement.value),
multiLoopInstance.value,
{
extensionElements
}
)
}
//
const updateLoopBase = () => {
window.bpmnInstances.modeling.updateModdleProperties(
toRaw(bpmnElement.value),
multiLoopInstance.value,
{
collection: loopInstanceForm.value.collection || null,
elementVariable: loopInstanceForm.value.elementVariable || null
}
)
}
//
const updateLoopAsync = (key) => {
const { asyncBefore, asyncAfter } = loopInstanceForm.value
let asyncAttr = Object.create(null)
if (!asyncBefore && !asyncAfter) {
// this.$set(this.loopInstanceForm, "exclusive", false);
loopInstanceForm.value['exclusive'] = false
asyncAttr = { asyncBefore: false, asyncAfter: false, exclusive: false, extensionElements: null }
} else {
asyncAttr[key] = loopInstanceForm.value[key]
}
window.bpmnInstances.modeling.updateModdleProperties(
toRaw(bpmnElement.value),
multiLoopInstance.value,
asyncAttr
)
}
onBeforeUnmount(() => {
multiLoopInstance.value = null
bpmnElement.value = null
})
watch(
() => props.businessObject,
(val) => {
bpmnElement.value = window.bpmnInstances.bpmnElement
getElementLoop(val)
},
{ immediate: true }
)
</script>

View File

@ -0,0 +1,55 @@
<template>
<div class="panel-tab__content">
<div class="element-property input-property">
<div class="element-property__label">元素文档</div>
<div class="element-property__value">
<el-input
type="textarea"
v-model="documentation"
resize="vertical"
:autosize="{ minRows: 2, maxRows: 4 }"
@input="updateDocumentation"
@blur="updateDocumentation"
/>
</div>
</div>
</div>
</template>
<script setup lang="ts" name="ElementOtherConfig">
import { ref, watch, nextTick, onBeforeUnmount, toRaw } from 'vue'
import { ElInput } from 'element-plus'
const props = defineProps({
id: String
})
const documentation = ref('')
const bpmnElement = ref()
const updateDocumentation = () => {
;(bpmnElement.value && bpmnElement.value.id === props.id) ||
(bpmnElement.value = (window as any).bpmnInstances.elementRegistry.get(props.id))
const documentations = window.bpmnInstances.bpmnFactory.create('bpmn:Documentation', {
text: documentation.value
})
window.bpmnInstances.modeling.updateProperties(toRaw(bpmnElement.value), {
documentation: [documentations]
})
}
onBeforeUnmount(() => {
bpmnElement.value = null
})
watch(
() => props.id,
(id) => {
if (id && id.length) {
nextTick(() => {
const documentations = window.bpmnInstances.bpmnElement.businessObject?.documentation
documentation.value = documentations && documentations.length ? documentations[0].text : ''
})
} else {
documentation.value = ''
}
},
{ immediate: true }
)
</script>

View File

@ -0,0 +1,177 @@
<template>
<div class="panel-tab__content">
<el-table :data="elementPropertyList" max-height="240" border fit>
<el-table-column label="序号" width="50px" type="index" />
<el-table-column label="属性名" prop="name" min-width="100px" show-overflow-tooltip />
<el-table-column label="属性值" prop="value" min-width="100px" show-overflow-tooltip />
<el-table-column label="操作" width="110px">
<template #default="scope">
<el-button link @click="openAttributesForm(scope.row, scope.$index)" size="small"
>编辑</el-button
>
<el-divider direction="vertical" />
<el-button
link
size="small"
style="color: #ff4d4f"
@click="removeAttributes(scope.row, scope.$index)"
>移除</el-button
>
</template>
</el-table-column>
</el-table>
<div class="element-drawer__button">
<XButton
type="primary"
preIcon="ep:plus"
title="添加属性"
@click="openAttributesForm(null, -1)"
/>
</div>
<el-dialog
v-model="propertyFormModelVisible"
title="属性配置"
width="600px"
append-to-body
destroy-on-close
>
<el-form :model="propertyForm" label-width="80px" ref="attributeFormRef">
<el-form-item label="属性名:" prop="name">
<el-input v-model="propertyForm.name" clearable />
</el-form-item>
<el-form-item label="属性值:" prop="value">
<el-input v-model="propertyForm.value" clearable />
</el-form-item>
</el-form>
<template #footer>
<el-button @click="propertyFormModelVisible = false"> </el-button>
<el-button type="primary" @click="saveAttribute"> </el-button>
</template>
</el-dialog>
</div>
</template>
<script setup lang="ts" name="ElementProperties">
import { ref, inject, nextTick, watch, toRaw } from 'vue'
import {
ElMessageBox,
ElDialog,
ElButton,
ElForm,
ElFormItem,
ElTable,
ElTableColumn,
ElDivider,
ElInput
} from 'element-plus'
const props = defineProps({
id: String,
type: String
})
const prefix = inject('prefix')
// const width = inject('width')
const elementPropertyList = ref([])
const propertyForm = ref({})
const editingPropertyIndex = ref(-1)
const propertyFormModelVisible = ref(false)
const bpmnElement = ref()
const otherExtensionList = ref()
const bpmnElementProperties = ref()
const bpmnElementPropertyList = ref()
const attributeFormRef = ref()
const resetAttributesList = () => {
console.log(window, 'windowwindowwindowwindowwindowwindowwindow')
bpmnElement.value = window.bpmnInstances.bpmnElement
otherExtensionList.value = [] //
bpmnElementProperties.value =
// bpmnElement.value.businessObject?.extensionElements?.filter((ex) => {
bpmnElement.value.businessObject?.extensionElements?.values.filter((ex) => {
if (ex.$type !== `${prefix}:Properties`) {
otherExtensionList.value.push(ex)
}
return ex.$type === `${prefix}:Properties`
}) ?? []
//
bpmnElementPropertyList.value = bpmnElementProperties.value.reduce(
(pre, current) => pre.concat(current.values),
[]
)
//
elementPropertyList.value = JSON.parse(JSON.stringify(bpmnElementPropertyList.value ?? []))
}
const openAttributesForm = (attr, index) => {
editingPropertyIndex.value = index
propertyForm.value = index === -1 ? {} : JSON.parse(JSON.stringify(attr))
propertyFormModelVisible.value = true
nextTick(() => {
if (attributeFormRef.value) attributeFormRef.value.clearValidate()
})
}
const removeAttributes = (attr, index) => {
console.log(attr, 'attr')
ElMessageBox.confirm('确认移除该属性吗?', '提示', {
confirmButtonText: '确 认',
cancelButtonText: '取 消'
})
.then(() => {
elementPropertyList.value.splice(index, 1)
bpmnElementPropertyList.value.splice(index, 1)
//
const propertiesObject = window.bpmnInstances.moddle.create(`${prefix}:Properties`, {
values: bpmnElementPropertyList.value
})
updateElementExtensions(propertiesObject)
resetAttributesList()
})
.catch(() => console.info('操作取消'))
}
const saveAttribute = () => {
console.log(propertyForm.value, 'propertyForm.value')
const { name, value } = propertyForm.value
if (editingPropertyIndex.value !== -1) {
window.bpmnInstances.modeling.updateModdleProperties(
toRaw(bpmnElement.value),
toRaw(bpmnElementPropertyList.value)[toRaw(editingPropertyIndex.value)],
{
name,
value
}
)
} else {
//
const newPropertyObject = window.bpmnInstances.moddle.create(`${prefix}:Property`, {
name,
value
})
//
const propertiesObject = window.bpmnInstances.moddle.create(`${prefix}:Properties`, {
values: bpmnElementPropertyList.value.concat([newPropertyObject])
})
updateElementExtensions(propertiesObject)
}
propertyFormModelVisible.value = false
resetAttributesList()
}
const updateElementExtensions = (properties) => {
const extensions = window.bpmnInstances.moddle.create('bpmn:ExtensionElements', {
values: otherExtensionList.value.concat([properties])
})
window.bpmnInstances.modeling.updateProperties(toRaw(bpmnElement.value), {
extensionElements: extensions
})
}
watch(
() => props.id,
(val) => {
if (val) {
val && val.length && resetAttributesList()
}
},
{ immediate: true }
)
</script>

View File

@ -0,0 +1,120 @@
<template>
<div class="panel-tab__content">
<div class="panel-tab__content--title">
<span><Icon icon="ep:menu" style="margin-right: 8px; color: #555555" />消息列表</span>
<XButton type="primary" title="创建新消息" preIcon="ep:plus" @click="openModel('message')" />
</div>
<el-table :data="messageList" border>
<el-table-column type="index" label="序号" width="60px" />
<el-table-column label="消息ID" prop="id" max-width="300px" show-overflow-tooltip />
<el-table-column label="消息名称" prop="name" max-width="300px" show-overflow-tooltip />
</el-table>
<div
class="panel-tab__content--title"
style="padding-top: 8px; margin-top: 8px; border-top: 1px solid #eeeeee"
>
<span><Icon icon="ep:menu" style="margin-right: 8px; color: #555555" />信号列表</span>
<XButton type="primary" title="创建新信号" preIcon="ep:plus" @click="openModel('signal')" />
</div>
<el-table :data="signalList" border>
<el-table-column type="index" label="序号" width="60px" />
<el-table-column label="信号ID" prop="id" max-width="300px" show-overflow-tooltip />
<el-table-column label="信号名称" prop="name" max-width="300px" show-overflow-tooltip />
</el-table>
<el-dialog
v-model="modelVisible"
:title="modelConfig.title"
:close-on-click-modal="false"
width="400px"
append-to-body
destroy-on-close
>
<el-form :model="modelObjectForm" label-width="90px">
<el-form-item :label="modelConfig.idLabel">
<el-input v-model="modelObjectForm.id" clearable />
</el-form-item>
<el-form-item :label="modelConfig.nameLabel">
<el-input v-model="modelObjectForm.name" clearable />
</el-form-item>
</el-form>
<template #footer>
<el-button @click="modelVisible = false"> </el-button>
<el-button type="primary" @click="addNewObject"> </el-button>
</template>
</el-dialog>
</div>
</template>
<script setup lang="ts" name="SignalAndMassage">
import {
ElMessage,
ElDialog,
ElForm,
ElFormItem,
ElTable,
ElTableColumn,
ElButton,
ElInput
} from 'element-plus'
import { ref, computed, onMounted } from 'vue'
const signalList = ref([])
const messageList = ref([])
const modelVisible = ref(false)
const modelType = ref('')
const modelObjectForm = ref({})
const rootElements = ref()
const messageIdMap = ref()
const signalIdMap = ref()
const modelConfig = computed(() => {
if (modelType.value === 'message') {
return { title: '创建消息', idLabel: '消息ID', nameLabel: '消息名称' }
} else {
return { title: '创建信号', idLabel: '信号ID', nameLabel: '信号名称' }
}
})
const initDataList = () => {
console.log(window, 'window')
rootElements.value = window.bpmnInstances.modeler.getDefinitions().rootElements
messageIdMap.value = {}
signalIdMap.value = {}
messageList.value = []
signalList.value = []
rootElements.value.forEach((el) => {
if (el.$type === 'bpmn:Message') {
messageIdMap.value[el.id] = true
messageList.value.push({ ...el })
}
if (el.$type === 'bpmn:Signal') {
signalIdMap.value[el.id] = true
signalList.value.push({ ...el })
}
})
}
const openModel = (type) => {
modelType.value = type
modelObjectForm.value = {}
modelVisible.value = true
}
const addNewObject = () => {
if (modelType.value === 'message') {
if (messageIdMap.value[modelObjectForm.value.id]) {
ElMessage.error('该消息已存在请修改id后重新保存')
}
const messageRef = window.bpmnInstances.moddle.create('bpmn:Message', modelObjectForm.value)
rootElements.value.push(messageRef)
} else {
if (signalIdMap.value[modelObjectForm.value.id]) {
ElMessage.error('该信号已存在请修改id后重新保存')
}
const signalRef = window.bpmnInstances.moddle.create('bpmn:Signal', modelObjectForm.value)
rootElements.value.push(signalRef)
}
modelVisible.value = false
initDataList()
}
onMounted(() => {
initDataList()
})
</script>

View File

@ -0,0 +1,85 @@
<template>
<div class="panel-tab__content">
<el-form size="small" label-width="90px">
<el-form-item label="异步延续">
<el-checkbox
v-model="taskConfigForm.asyncBefore"
label="异步前"
@change="changeTaskAsync"
/>
<el-checkbox v-model="taskConfigForm.asyncAfter" label="异步后" @change="changeTaskAsync" />
<el-checkbox
v-model="taskConfigForm.exclusive"
v-if="taskConfigForm.asyncAfter || taskConfigForm.asyncBefore"
label="排除"
@change="changeTaskAsync"
/>
</el-form-item>
<component :is="witchTaskComponent" v-bind="$props" />
</el-form>
</div>
</template>
<script setup lang="ts" name="ElementTaskConfig">
import { ref, watch } from 'vue'
import { ElForm, ElFormItem, ElCheckbox } from 'element-plus'
import UserTask from './task-components/UserTask.vue'
import ScriptTask from './task-components/ScriptTask.vue'
import ReceiveTask from './task-components/ReceiveTask.vue'
const props = defineProps({
id: String,
type: String
})
const taskConfigForm = ref({
asyncAfter: false,
asyncBefore: false,
exclusive: false
})
const witchTaskComponent = ref()
const installedComponent = ref({
//
// messageRef
//
UserTask: 'UserTask', //
ScriptTask: 'ScriptTask', //
ReceiveTask: 'ReceiveTask' //
})
const bpmnElement = ref()
const changeTaskAsync = () => {
if (!taskConfigForm.value.asyncBefore && !taskConfigForm.value.asyncAfter) {
taskConfigForm.value.exclusive = false
}
window.bpmnInstances.modeling.updateProperties(window.bpmnInstances.bpmnElement, {
...taskConfigForm.value
})
}
watch(
() => props.id,
() => {
bpmnElement.value = window.bpmnInstances.bpmnElement
taskConfigForm.value.asyncBefore = bpmnElement.value?.businessObject?.asyncBefore
taskConfigForm.value.asyncAfter = bpmnElement.value?.businessObject?.asyncAfter
taskConfigForm.value.exclusive = bpmnElement.value?.businessObject?.exclusive
},
{ immediate: true }
)
watch(
() => props.type,
() => {
// witchTaskComponent.value = installedComponent.value[props.type]
if (props.type == installedComponent.value.UserTask) {
witchTaskComponent.value = UserTask
}
if (props.type == installedComponent.value.ScriptTask) {
witchTaskComponent.value = ScriptTask
}
if (props.type == installedComponent.value.ReceiveTask) {
witchTaskComponent.value = ReceiveTask
}
},
{ immediate: true }
)
</script>

View File

@ -0,0 +1,122 @@
<template>
<div style="margin-top: 16px">
<el-form-item label="消息实例">
<div
style="
display: flex;
align-items: center;
justify-content: space-between;
flex-wrap: nowrap;
"
>
<el-select v-model="bindMessageId" @change="updateTaskMessage">
<el-option
v-for="id in Object.keys(messageMap)"
:value="id"
:label="messageMap[id]"
:key="id"
/>
</el-select>
<XButton
type="primary"
preIcon="ep:plus"
style="margin-left: 8px"
@click="openMessageModel"
/>
</div>
</el-form-item>
<el-dialog
v-model="messageModelVisible"
:close-on-click-modal="false"
title="创建新消息"
width="400px"
append-to-body
destroy-on-close
>
<el-form :model="newMessageForm" size="small" label-width="90px">
<el-form-item label="消息ID">
<el-input v-model="newMessageForm.id" clearable />
</el-form-item>
<el-form-item label="消息名称">
<el-input v-model="newMessageForm.name" clearable />
</el-form-item>
</el-form>
<template #footer>
<el-button size="small" type="primary" @click="createNewMessage"> </el-button>
</template>
</el-dialog>
</div>
</template>
<script setup lang="ts" name="ReceiveTask">
import { ref, watch, onBeforeUnmount, onMounted, nextTick, toRaw } from 'vue'
import { ElMessage, ElFormItem, ElDialog, ElForm, ElSelect, ElOption } from 'element-plus'
const props = defineProps({
id: String,
type: String
})
const bindMessageId = ref('')
const newMessageForm = ref({})
const messageMap = ref({})
const messageModelVisible = ref(false)
const bpmnElement = ref()
const bpmnMessageRefsMap = ref()
const bpmnRootElements = ref()
const getBindMessage = () => {
bpmnElement.value = window.bpmnInstances.bpmnElement
bindMessageId.value = bpmnElement.value.businessObject?.messageRef?.id || '-1'
}
const openMessageModel = () => {
messageModelVisible.value = true
newMessageForm.value = {}
}
const createNewMessage = () => {
if (messageMap.value[newMessageForm.value.id]) {
ElMessage.error('该消息已存在请修改id后重新保存')
return
}
const newMessage = window.bpmnInstances.moddle.create('bpmn:Message', newMessageForm.value)
bpmnRootElements.value.push(newMessage)
messageMap.value[newMessageForm.value.id] = newMessageForm.value.name
bpmnMessageRefsMap.value[newMessageForm.value.id] = newMessage
messageModelVisible.value = false
}
const updateTaskMessage = (messageId) => {
if (messageId === '-1') {
window.bpmnInstances.modeling.updateProperties(toRaw(bpmnElement.value), {
messageRef: null
})
} else {
window.bpmnInstances.modeling.updateProperties(toRaw(bpmnElement.value), {
messageRef: bpmnMessageRefsMap.value[messageId]
})
}
}
onMounted(() => {
bpmnMessageRefsMap.value = Object.create(null)
bpmnRootElements.value = window.bpmnInstances.modeler.getDefinitions().rootElements
bpmnRootElements.value
.filter((el) => el.$type === 'bpmn:Message')
.forEach((m) => {
bpmnMessageRefsMap.value[m.id] = m
messageMap.value[m.id] = m.name
})
messageMap.value['-1'] = '无'
})
onBeforeUnmount(() => {
bpmnElement.value = null
})
watch(
() => props.id,
() => {
// bpmnElement.value = window.bpmnInstances.bpmnElement
nextTick(() => {
getBindMessage()
})
},
{ immediate: true }
)
</script>

View File

@ -0,0 +1,98 @@
<template>
<div style="margin-top: 16px">
<el-form-item label="脚本格式">
<el-input
v-model="scriptTaskForm.scriptFormat"
clearable
@input="updateElementTask()"
@change="updateElementTask()"
/>
</el-form-item>
<el-form-item label="脚本类型">
<el-select v-model="scriptTaskForm.scriptType">
<el-option label="内联脚本" value="inline" />
<el-option label="外部资源" value="external" />
</el-select>
</el-form-item>
<el-form-item label="脚本" v-show="scriptTaskForm.scriptType === 'inline'">
<el-input
v-model="scriptTaskForm.script"
type="textarea"
resize="vertical"
:autosize="{ minRows: 2, maxRows: 4 }"
clearable
@input="updateElementTask()"
@change="updateElementTask()"
/>
</el-form-item>
<el-form-item label="资源地址" v-show="scriptTaskForm.scriptType === 'external'">
<el-input
v-model="scriptTaskForm.resource"
clearable
@input="updateElementTask()"
@change="updateElementTask()"
/>
</el-form-item>
<el-form-item label="结果变量">
<el-input
v-model="scriptTaskForm.resultVariable"
clearable
@input="updateElementTask()"
@change="updateElementTask()"
/>
</el-form-item>
</div>
</template>
<script setup lang="ts" name="ScriptTask">
import { ref, watch, nextTick, onBeforeUnmount, toRaw } from 'vue'
import { ElInput, ElFormItem } from 'element-plus'
const props = defineProps({
id: String,
type: String
})
const defaultTaskForm = ref({
scriptFormat: '',
script: '',
resource: '',
resultVariable: ''
})
const scriptTaskForm = ref({})
const bpmnElement = ref()
const resetTaskForm = () => {
for (let key in defaultTaskForm.value) {
let value = bpmnElement.value?.businessObject[key] || defaultTaskForm.value[key]
scriptTaskForm.value[key] = value
}
scriptTaskForm.value.scriptType = scriptTaskForm.value.script ? 'inline' : 'external'
}
const updateElementTask = () => {
let taskAttr = Object.create(null)
taskAttr.scriptFormat = scriptTaskForm.value.scriptFormat || null
taskAttr.resultVariable = scriptTaskForm.value.resultVariable || null
if (scriptTaskForm.value.scriptType === 'inline') {
taskAttr.script = scriptTaskForm.value.script || null
taskAttr.resource = null
} else {
taskAttr.resource = scriptTaskForm.value.resource || null
taskAttr.script = null
}
window.bpmnInstances.modeling.updateProperties(toRaw(bpmnElement.value), taskAttr)
}
onBeforeUnmount(() => {
bpmnElement.value = null
})
watch(
() => props.id,
() => {
bpmnElement.value = window.bpmnInstances.bpmnElement
nextTick(() => {
resetTaskForm()
})
},
{ immediate: true }
)
</script>

View File

@ -0,0 +1,97 @@
<template>
<div style="margin-top: 16px">
<!-- <el-form-item label="处理用户">-->
<!-- <el-select v-model="userTaskForm.assignee" @change="updateElementTask('assignee')">-->
<!-- <el-option v-for="ak in mockData" :key="'ass-' + ak" :label="`用户${ak}`" :value="`user${ak}`" />-->
<!-- </el-select>-->
<!-- </el-form-item>-->
<!-- <el-form-item label="候选用户">-->
<!-- <el-select v-model="userTaskForm.candidateUsers" multiple collapse-tags @change="updateElementTask('candidateUsers')">-->
<!-- <el-option v-for="uk in mockData" :key="'user-' + uk" :label="`用户${uk}`" :value="`user${uk}`" />-->
<!-- </el-select>-->
<!-- </el-form-item>-->
<!-- <el-form-item label="候选分组">-->
<!-- <el-select v-model="userTaskForm.candidateGroups" multiple collapse-tags @change="updateElementTask('candidateGroups')">-->
<!-- <el-option v-for="gk in mockData" :key="'ass-' + gk" :label="`分组${gk}`" :value="`group${gk}`" />-->
<!-- </el-select>-->
<!-- </el-form-item>-->
<el-form-item label="到期时间">
<el-input v-model="userTaskForm.dueDate" clearable @change="updateElementTask('dueDate')" />
</el-form-item>
<el-form-item label="跟踪时间">
<el-input
v-model="userTaskForm.followUpDate"
clearable
@change="updateElementTask('followUpDate')"
/>
</el-form-item>
<el-form-item label="优先级">
<el-input v-model="userTaskForm.priority" clearable @change="updateElementTask('priority')" />
</el-form-item>
友情提示任务的分配规则使用
<router-link target="_blank" :to="{ path: '/bpm/manager/model' }"
><el-link type="danger">流程模型</el-link>
</router-link>
下的分配规则替代提供指定角色部门负责人部门成员岗位工作组自定义脚本等 7
种维护的任务分配维度更加灵活
</div>
</template>
<script setup lang="ts" name="UserTask">
import { ref, watch, nextTick, onBeforeUnmount, toRaw } from 'vue'
import { ElLink, ElFormItem, ElInput } from 'element-plus'
const props = defineProps({
id: String,
type: String
})
const defaultTaskForm = ref({
assignee: '',
candidateUsers: [],
candidateGroups: [],
dueDate: '',
followUpDate: '',
priority: ''
})
const userTaskForm = ref({})
// const mockData=ref([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
const bpmnElement = ref()
const resetTaskForm = () => {
for (let key in defaultTaskForm.value) {
let value
if (key === 'candidateUsers' || key === 'candidateGroups') {
value = bpmnElement.value?.businessObject[key]
? bpmnElement.value.businessObject[key].split(',')
: []
} else {
value = bpmnElement.value?.businessObject[key] || defaultTaskForm.value[key]
}
userTaskForm.value[key] = value
}
}
const updateElementTask = (key) => {
const taskAttr = Object.create(null)
if (key === 'candidateUsers' || key === 'candidateGroups') {
taskAttr[key] =
userTaskForm.value[key] && userTaskForm.value[key].length
? userTaskForm.value[key].join()
: null
} else {
taskAttr[key] = userTaskForm.value[key] || null
}
window.bpmnInstances.modeling.updateProperties(toRaw(bpmnElement.value), taskAttr)
}
watch(
() => props.id,
() => {
bpmnElement.value = window.bpmnInstances.bpmnElement
nextTick(() => {
resetTaskForm()
})
},
{ immediate: true }
)
onBeforeUnmount(() => {
bpmnElement.value = null
})
</script>

View File

@ -0,0 +1,70 @@
/* 改变主题色变量 */
$--color-primary: #1890ff;
$--color-danger: #ff4d4f;
/* 改变 icon 字体路径变量,必需 */
$--font-path: '~element-ui/lib/theme-chalk/fonts';
@import "~element-ui/packages/theme-chalk/src/index";
.el-table td,
.el-table th {
color: #333;
}
.el-drawer__header {
padding: 16px 16px 8px 16px;
margin: 0;
line-height: 24px;
font-size: 18px;
color: #303133;
box-sizing: border-box;
border-bottom: 1px solid #e8e8e8;
}
div[class^="el-drawer"]:focus,
span:focus {
outline: none;
}
.el-drawer__body {
box-sizing: border-box;
padding: 16px;
width: 100%;
overflow-y: auto;
}
.el-dialog {
margin-top: 50vh !important;
transform: translateY(-50%);
overflow: hidden;
}
.el-dialog__wrapper {
overflow: hidden;
max-height: 100vh;
}
.el-dialog__header {
padding: 16px 16px 8px 16px;
box-sizing: border-box;
border-bottom: 1px solid #e8e8e8;
}
.el-dialog__body {
padding: 16px;
max-height: 80vh;
box-sizing: border-box;
overflow-y: auto;
}
.el-dialog__footer {
padding: 16px;
box-sizing: border-box;
border-top: 1px solid #e8e8e8;
}
.el-dialog__close {
font-weight: 600;
}
.el-select {
width: 100%;
}
.el-divider:not(.el-divider--horizontal) {
margin: 0 8px ;
}
.el-divider.el-divider--horizontal {
margin: 16px 0;
}

View File

@ -0,0 +1,2 @@
@import "./process-designer.scss";
@import "./process-panel.scss";

View File

@ -0,0 +1,161 @@
@import 'bpmn-js-token-simulation/assets/css/bpmn-js-token-simulation.css';
@import 'bpmn-js-token-simulation/assets/css/font-awesome.min.css';
@import 'bpmn-js-token-simulation/assets/css/normalize.css';
// 边框被 token-simulation 样式覆盖了
.djs-palette {
background: var(--palette-background-color);
border: solid 1px var(--palette-border-color) !important;
border-radius: 2px;
}
.my-process-designer {
display: flex;
flex-direction: column;
width: 100%;
height: 100%;
box-sizing: border-box;
.my-process-designer__header {
width: 100%;
min-height: 36px;
.el-button {
text-align: center;
}
.el-button-group {
margin: 4px;
}
.el-tooltip__popper {
.el-button {
width: 100%;
text-align: left;
padding-left: 8px;
padding-right: 8px;
}
.el-button:hover {
background: rgba(64, 158, 255, 0.8);
color: #ffffff;
}
}
.align {
position: relative;
i {
&:after {
content: '|';
position: absolute;
// transform: rotate(90deg) translate(200%, 60%);
transform: rotate(180deg) translate(271%, -10%);
}
}
}
.align.align-left i {
transform: rotate(90deg);
}
.align.align-right i {
transform: rotate(-90deg);
}
.align.align-top i {
transform: rotate(180deg);
}
.align.align-bottom i {
transform: rotate(0deg);
}
.align.align-center i {
transform: rotate(0deg);
&:after {
// transform: rotate(90deg) translate(0, 60%);
transform: rotate(0deg) translate(-0%, -5%);
}
}
.align.align-middle i {
transform: rotate(-90deg);
&:after {
// transform: rotate(90deg) translate(0, 60%);
transform: rotate(0deg) translate(0, -10%);
}
}
}
.my-process-designer__container {
display: inline-flex;
width: 100%;
flex: 1;
.my-process-designer__canvas {
flex: 1;
height: 100%;
position: relative;
background: url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDAiIGhlaWdodD0iNDAiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PGRlZnM+PHBhdHRlcm4gaWQ9ImEiIHdpZHRoPSI0MCIgaGVpZ2h0PSI0MCIgcGF0dGVyblVuaXRzPSJ1c2VyU3BhY2VPblVzZSI+PHBhdGggZD0iTTAgMTBoNDBNMTAgMHY0ME0wIDIwaDQwTTIwIDB2NDBNMCAzMGg0ME0zMCAwdjQwIiBmaWxsPSJub25lIiBzdHJva2U9IiNlMGUwZTAiIG9wYWNpdHk9Ii4yIi8+PHBhdGggZD0iTTQwIDBIMHY0MCIgZmlsbD0ibm9uZSIgc3Ryb2tlPSIjZTBlMGUwIi8+PC9wYXR0ZXJuPjwvZGVmcz48cmVjdCB3aWR0aD0iMTAwJSIgaGVpZ2h0PSIxMDAlIiBmaWxsPSJ1cmwoI2EpIi8+PC9zdmc+')
repeat !important;
div.toggle-mode {
display: none;
}
}
.my-process-designer__property-panel {
height: 100%;
overflow: scroll;
overflow-y: auto;
z-index: 10;
* {
box-sizing: border-box;
}
}
svg {
width: 100%;
height: 100%;
min-height: 100%;
overflow: hidden;
}
}
}
//侧边栏配置
// .djs-palette .two-column .open {
.open {
// .djs-palette.open {
.djs-palette-entries {
div[class^='bpmn-icon-']:before,
div[class*='bpmn-icon-']:before {
line-height: unset;
}
div.entry {
position: relative;
}
div.entry:hover {
&::after {
width: max-content;
content: attr(title);
vertical-align: text-bottom;
position: absolute;
right: -10px;
top: 0;
bottom: 0;
overflow: hidden;
transform: translateX(100%);
font-size: 0.5em;
display: inline-block;
text-decoration: inherit;
font-variant: normal;
text-transform: none;
background: #fafafa;
box-shadow: 0 0 6px #eeeeee;
border: 1px solid #cccccc;
box-sizing: border-box;
padding: 0 16px;
border-radius: 4px;
z-index: 100;
}
}
}
}
pre {
margin: 0;
height: 100%;
overflow: hidden;
max-height: calc(80vh - 32px);
overflow-y: auto;
}
.hljs {
word-break: break-word;
white-space: pre-wrap;
}
.hljs * {
font-family: Consolas, Monaco, monospace;
}

View File

@ -0,0 +1,107 @@
.process-panel__container {
box-sizing: border-box;
padding: 0 8px;
border-left: 1px solid #eeeeee;
box-shadow: 0 0 8px #cccccc;
max-height: 100%;
overflow-y: scroll;
}
.panel-tab__title {
font-weight: 600;
padding: 0 8px;
font-size: 1.1em;
line-height: 1.2em;
i {
margin-right: 8px;
font-size: 1.2em;
}
}
.panel-tab__content {
width: 100%;
box-sizing: border-box;
border-top: 1px solid #eeeeee;
padding: 8px 16px;
.panel-tab__content--title {
display: flex;
justify-content: space-between;
padding-bottom: 8px;
span {
flex: 1;
text-align: left;
}
}
}
.element-property {
width: 100%;
display: flex;
align-items: flex-start;
margin: 8px 0;
.element-property__label {
display: block;
width: 90px;
text-align: right;
overflow: hidden;
padding-right: 12px;
line-height: 32px;
font-size: 14px;
box-sizing: border-box;
}
.element-property__value {
flex: 1;
line-height: 32px;
}
.el-form-item {
width: 100%;
margin-bottom: 0;
padding-bottom: 18px;
}
}
.list-property {
flex-direction: column;
.element-listener-item {
width: 100%;
display: inline-grid;
grid-template-columns: 16px auto 32px 32px;
grid-column-gap: 8px;
}
.element-listener-item + .element-listener-item {
margin-top: 8px;
}
}
.listener-filed__title {
display: inline-flex;
width: 100%;
justify-content: space-between;
align-items: center;
margin-top: 0;
span {
width: 200px;
text-align: left;
font-size: 14px;
}
i {
margin-right: 8px;
}
}
.element-drawer__button {
margin-top: 8px;
width: 100%;
display: inline-flex;
justify-content: space-around;
}
.element-drawer__button > .el-button {
width: 100%;
}
.el-collapse-item__content {
padding-bottom: 0;
}
.el-input.is-disabled .el-input__inner {
color: #999999;
}
.el-form-item.el-form-item--mini {
margin-bottom: 0;
& + .el-form-item {
margin-top: 16px;
}
}

View File

@ -0,0 +1,76 @@
import { toRaw } from 'vue'
// 创建监听器实例
export function createListenerObject(options, isTask, prefix) {
const listenerObj = Object.create(null)
listenerObj.event = options.event
isTask && (listenerObj.id = options.id) // 任务监听器特有的 id 字段
switch (options.listenerType) {
case 'scriptListener':
listenerObj.script = createScriptObject(options, prefix)
break
case 'expressionListener':
listenerObj.expression = options.expression
break
case 'delegateExpressionListener':
listenerObj.delegateExpression = options.delegateExpression
break
default:
listenerObj.class = options.class
}
// 注入字段
if (options.fields) {
listenerObj.fields = options.fields.map((field) => {
return createFieldObject(field, prefix)
})
}
// 任务监听器的 定时器 设置
if (isTask && options.event === 'timeout' && !!options.eventDefinitionType) {
const timeDefinition = window.bpmnInstances.moddle.create('bpmn:FormalExpression', {
body: options.eventTimeDefinitions
})
const TimerEventDefinition = window.bpmnInstances.moddle.create('bpmn:TimerEventDefinition', {
id: `TimerEventDefinition_${uuid(8)}`,
[`time${options.eventDefinitionType.replace(/^\S/, (s) => s.toUpperCase())}`]: timeDefinition
})
listenerObj.eventDefinitions = [TimerEventDefinition]
}
return window.bpmnInstances.moddle.create(
`${prefix}:${isTask ? 'TaskListener' : 'ExecutionListener'}`,
listenerObj
)
}
// 创建 监听器的注入字段 实例
export function createFieldObject(option, prefix) {
const { name, fieldType, string, expression } = option
const fieldConfig = fieldType === 'string' ? { name, string } : { name, expression }
return window.bpmnInstances.moddle.create(`${prefix}:Field`, fieldConfig)
}
// 创建脚本实例
export function createScriptObject(options, prefix) {
const { scriptType, scriptFormat, value, resource } = options
const scriptConfig =
scriptType === 'inlineScript' ? { scriptFormat, value } : { scriptFormat, resource }
return window.bpmnInstances.moddle.create(`${prefix}:Script`, scriptConfig)
}
// 更新元素扩展属性
export function updateElementExtensions(element, extensionList) {
const extensions = window.bpmnInstances.moddle.create('bpmn:ExtensionElements', {
values: extensionList
})
window.bpmnInstances.modeling.updateProperties(toRaw(element), {
extensionElements: extensions
})
}
// 创建一个id
export function uuid(length = 8, chars) {
let result = ''
const charsString = chars || '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
for (let i = length; i > 0; --i) {
result += charsString[Math.floor(Math.random() * charsString.length)]
}
return result
}

View File

@ -0,0 +1,5 @@
const hljs = require("highlight.js/lib/core");
hljs.registerLanguage("xml", require("highlight.js/lib/languages/xml"));
hljs.registerLanguage("json", require("highlight.js/lib/languages/json"));
module.exports = hljs;

View File

@ -0,0 +1,14 @@
import BpmnRenderer from "bpmn-js/lib/draw/BpmnRenderer";
export default function CustomRenderer(config, eventBus, styles, pathMap, canvas, textRenderer) {
BpmnRenderer.call(this, config, eventBus, styles, pathMap, canvas, textRenderer, 2000);
this.handlers["label"] = function() {
return null;
};
}
const F = function() {}; // 核心,利用空对象作为中介;
F.prototype = BpmnRenderer.prototype; // 核心将父类的原型赋值给空对象F
CustomRenderer.prototype = new F(); // 核心,将 F的实例赋值给子类
CustomRenderer.prototype.constructor = CustomRenderer; // 修复子类CustomRenderer的构造器指向防止原型链的混乱

View File

@ -0,0 +1,6 @@
import CustomRenderer from "./CustomRenderer";
export default {
__init__: ["customRenderer"],
customRenderer: ["type", CustomRenderer]
};

View File

@ -0,0 +1,16 @@
import BpmnRules from "bpmn-js/lib/features/rules/BpmnRules";
import inherits from "inherits";
export default function CustomRules(eventBus) {
BpmnRules.call(this, eventBus);
}
inherits(CustomRules, BpmnRules);
CustomRules.prototype.canDrop = function() {
return false;
};
CustomRules.prototype.canMove = function() {
return false;
};

View File

@ -0,0 +1,6 @@
import CustomRules from "./CustomRules";
export default {
__init__: ["customRules"],
customRules: ["type", CustomRules]
};

View File

@ -0,0 +1,25 @@
/**
* This is a sample file that should be replaced with the actual translation.
*
* Checkout https://github.com/bpmn-io/bpmn-js-i18n for a list of available
* translations and labels to translate.
*/
export default {
'Exclusive Gateway': 'Exklusives Gateway',
'Parallel Gateway': 'Paralleles Gateway',
'Inclusive Gateway': 'Inklusives Gateway',
'Complex Gateway': 'Komplexes Gateway',
'Event based Gateway': 'Ereignis-basiertes Gateway',
'Message Start Event': '消息启动事件',
'Timer Start Event': '定时启动事件',
'Conditional Start Event': '条件启动事件',
'Signal Start Event': '信号启动事件',
'Error Start Event': '错误启动事件',
'Escalation Start Event': '升级启动事件',
'Compensation Start Event': '补偿启动事件',
'Message Start Event (non-interrupting)': '消息启动事件 (非中断)',
'Timer Start Event (non-interrupting)': '定时启动事件 (非中断)',
'Conditional Start Event (non-interrupting)': '条件启动事件 (非中断)',
'Signal Start Event (non-interrupting)': '信号启动事件 (非中断)',
'Escalation Start Event (non-interrupting)': '升级启动事件 (非中断)'
}

View File

@ -0,0 +1,39 @@
//outside.js
const ctx = "@@clickoutsideContext";
export default {
bind(el, binding, vnode) {
const ele = el;
const documentHandler = e => {
if (!vnode.context || ele.contains(e.target)) {
return false;
}
// 调用指令回调
if (binding.expression) {
vnode.context[el[ctx].methodName](e);
} else {
el[ctx].bindingFn(e);
}
};
// 将方法添加到ele
ele[ctx] = {
documentHandler,
methodName: binding.expression,
bindingFn: binding.value
};
setTimeout(() => {
document.addEventListener("touchstart", documentHandler); // 为document绑定事件
});
},
update(el, binding) {
const ele = el;
ele[ctx].methodName = binding.expression;
ele[ctx].bindingFn = binding.value;
},
unbind(el) {
document.removeEventListener("touchstart", el[ctx].documentHandler); // 解绑
delete el[ctx];
}
};

View File

@ -0,0 +1,10 @@
export function debounce(fn, delay = 500) {
let timer;
return function(...args) {
if (timer) {
clearTimeout(timer);
timer = null;
}
timer = setTimeout(fn.bind(this, ...args), delay);
};
}

View File

@ -0,0 +1,63 @@
class Log {
static type = ["primary", "success", "warn", "error", "info"];
static typeColor(type = "default") {
let color = "";
switch (type) {
case "primary":
color = "#2d8cf0";
break;
case "success":
color = "#19be6b";
break;
case "info":
color = "#909399";
break;
case "warn":
color = "#ff9900";
break;
case "error":
color = "#f03f14";
break;
case "default":
color = "#35495E";
break;
default:
color = type;
break;
}
return color;
}
static print(text, type = "default", back = false) {
if (typeof text === "object") {
// 如果是對象則調用打印對象方式
console.dir(text);
return;
}
if (back) {
// 如果是打印帶背景圖的
console.log(`%c ${text} `, `background:${this.typeColor(type)}; padding: 2px; border-radius: 4px;color: #fff;`);
} else {
console.log(`%c ${text} `, `color: ${this.typeColor(type)};`);
}
}
static pretty(title, text, type = "primary") {
if (typeof text === "object") {
console.log(
`%c ${title} %c`,
`background:${this.typeColor(type)};border:1px solid ${this.typeColor(type)}; padding: 1px; border-radius: 4px 0 0 4px; color: #fff;`
);
console.dir(text);
return;
}
console.log(
`%c ${title} %c ${text} %c`,
`background:${this.typeColor(type)};border:1px solid ${this.typeColor(type)}; padding: 1px; border-radius: 4px 0 0 4px; color: #fff;`,
`border:1px solid ${this.typeColor(type)}; padding: 1px; border-radius: 0 4px 4px 0; color: ${this.typeColor(type)};`,
"background:transparent"
);
}
}
export default Log;

View File

@ -0,0 +1,50 @@
function xmlStr2XmlObj(xmlStr) {
let xmlObj = {};
if (document.all) {
const xmlDom = new window.ActiveXObject("Microsoft.XMLDOM");
xmlDom.loadXML(xmlStr);
xmlObj = xmlDom;
} else {
xmlObj = new DOMParser().parseFromString(xmlStr, "text/xml");
}
return xmlObj;
}
function xml2json(xml) {
try {
let obj = {};
if (xml.children.length > 0) {
for (let i = 0; i < xml.children.length; i++) {
const item = xml.children.item(i);
const nodeName = item.nodeName;
if (typeof obj[nodeName] == "undefined") {
obj[nodeName] = xml2json(item);
} else {
if (typeof obj[nodeName].push == "undefined") {
const old = obj[nodeName];
obj[nodeName] = [];
obj[nodeName].push(old);
}
obj[nodeName].push(xml2json(item));
}
}
} else {
obj = xml.textContent;
}
return obj;
} catch (e) {
console.log(e.message);
}
}
function xmlObj2json(xml) {
const xmlObj = xmlStr2XmlObj(xml);
console.log(xmlObj);
let jsonObj = {};
if (xmlObj.childNodes.length > 0) {
jsonObj = xml2json(xmlObj);
}
return jsonObj;
}
export default xmlObj2json;

View File

@ -13,12 +13,15 @@ import { setupStore } from '@/store'
// 全局组件
import { setupGlobCom } from '@/components'
// 引入element-plus
// 引入 element-plus
import { setupElementPlus } from '@/plugins/elementPlus'
// 引入vxe-table
// 引入 vxe-table
import { setupVxeTable } from '@/plugins/vxeTable'
// 引入 form-create
import { setupFormCreate } from '@/plugins/formCreate'
// 引入全局样式
import '@/styles/index.scss'
@ -39,6 +42,17 @@ import './permission'
import { isDevMode } from '@/utils/env'
import { MyPD } from '@/components/bpmnProcessDesigner/package/index.js'
import '@/components/bpmnProcessDesigner/package/theme/index.scss'
import 'bpmn-js/dist/assets/diagram-js.css'
import 'bpmn-js/dist/assets/bpmn-font/css/bpmn.css'
import 'bpmn-js/dist/assets/bpmn-font/css/bpmn-codes.css'
import 'bpmn-js/dist/assets/bpmn-font/css/bpmn-embedded.css'
import hljs from 'highlight.js' //导入代码高亮文件
import 'highlight.js/styles/github.css' //导入代码高亮样式 新版
// 本地开发模式 全局引入 element-plus 样式,加快第一次进入速度
if (isDevMode()) {
console.info(isDevMode())
import('element-plus/dist/index.css')
@ -48,8 +62,18 @@ if (isDevMode()) {
const setupAll = async () => {
const app = createApp(App)
//自定义一个代码高亮指令
app.directive('highlight', function (el) {
const blocks = el.querySelectorAll('code')
blocks.forEach((block: any) => {
hljs.highlightElement(block)
})
})
await setupI18n(app)
MyPD(app)
setupStore(app)
setupGlobCom(app)
@ -58,6 +82,8 @@ const setupAll = async () => {
setupVxeTable(app)
setupFormCreate(app)
setupRouter(app)
setupAuth(app)

View File

@ -0,0 +1,43 @@
import type { App } from 'vue'
// 👇使用 form-create 需额外全局引入 element plus 组件
import {
ElAside,
ElPopconfirm,
ElHeader,
ElMain,
ElContainer,
ElDivider,
ElTransfer,
ElAlert,
ElTabs,
ElTabPane
} from 'element-plus'
import formCreate from '@form-create/element-ui'
import install from '@form-create/element-ui/auto-import'
import FcDesigner from '@form-create/designer'
const components = [
ElAside,
ElPopconfirm,
ElHeader,
ElMain,
ElContainer,
ElDivider,
ElTransfer,
ElAlert,
ElTabs,
ElTabPane
]
export const setupFormCreate = (app: App<Element>) => {
components.forEach((component) => {
app.component(component.name, component)
})
formCreate.use(install)
app.use(formCreate)
app.use(FcDesigner)
}

View File

@ -135,7 +135,15 @@ VXETable.setup({
})
// 自定义全局的格式化处理函数
VXETable.formats.mixin({
// 格式日期,默认 yyyy-MM-dd HH:mm:ss
// 格式精简日期,默认 yyyy-MM-dd HH:mm:ss
formatDay({ cellValue }, format) {
if (cellValue != null) {
return XEUtils.toDateString(cellValue, format || 'yyyy-MM-dd')
} else {
return ''
}
},
// 格式完整日期,默认 yyyy-MM-dd HH:mm:ss
formatDate({ cellValue }, format) {
if (cellValue != null) {
return XEUtils.toDateString(cellValue, format || 'yyyy-MM-dd HH:mm:ss')

View File

@ -189,6 +189,111 @@ const remainingRouter: AppRouteRecordRaw[] = [
title: '500',
noTagsView: true
}
},
{
path: '/bpm',
component: Layout,
name: 'bpm',
meta: {
hidden: true
},
children: [
{
path: '/manager/form/edit',
component: () => import('@/views/bpm/form/formEditor.vue'),
name: 'bpmFormEditor',
meta: {
noCache: true,
hidden: true,
canTo: true,
title: '设计流程表单',
activeMenu: 'bpm/manager/form/formEditor'
}
},
{
path: '/manager/model/edit',
component: () => import('@/views/bpm/model/modelEditor.vue'),
name: 'modelEditor',
meta: {
noCache: true,
hidden: true,
canTo: true,
title: '设计流程',
activeMenu: 'bpm/manager/model/design'
}
},
{
path: '/manager/definition',
component: () => import('@/views/bpm/definition/index.vue'),
name: 'BpmProcessDefinitionList',
meta: {
noCache: true,
hidden: true,
canTo: true,
title: '流程定义',
activeMenu: 'bpm/definition/index'
}
},
{
path: '/manager/task-assign-rule',
component: () => import('@/views/bpm/taskAssignRule/index.vue'),
name: 'BpmTaskAssignRuleList',
meta: {
noCache: true,
hidden: true,
canTo: true,
title: '任务分配规则'
}
},
{
path: '/process-instance/create',
component: () => import('@/views/bpm/processInstance/create.vue'),
name: 'BpmProcessInstanceCreate',
meta: {
noCache: true,
hidden: true,
canTo: true,
title: '发起流程',
activeMenu: 'bpm/processInstance/create'
}
},
{
path: '/process-instance/detail',
component: () => import('@/views/bpm/processInstance/detail.vue'),
name: 'BpmProcessInstanceDetail',
meta: {
noCache: true,
hidden: true,
canTo: true,
title: '流程详情',
activeMenu: 'bpm/processInstance/detail'
}
},
{
path: '/bpm/oa/leave/create',
component: () => import('@/views/bpm/oa/leave/create.vue'),
name: 'OALeaveCreate',
meta: {
noCache: true,
hidden: true,
canTo: true,
title: '发起 OA 请假',
activeMenu: 'bpm/oa/leave/create'
}
},
{
path: '/bpm/oa/leave/detail',
component: () => import('@/views/bpm/oa/leave/detail.vue'),
name: 'OALeaveDetail',
meta: {
noCache: true,
hidden: true,
canTo: true,
title: '查看 OA 请假',
activeMenu: 'bpm/oa/leave/detail'
}
}
]
}
]

View File

@ -21,7 +21,6 @@ declare module '@vue/runtime-core' {
DictTag: typeof import('./../components/DictTag/src/DictTag.vue')['default']
Echart: typeof import('./../components/Echart/src/Echart.vue')['default']
Editor: typeof import('./../components/Editor/src/Editor.vue')['default']
ElAvatar: typeof import('element-plus/es')['ElAvatar']
ElBadge: typeof import('element-plus/es')['ElBadge']
ElButton: typeof import('element-plus/es')['ElButton']
ElCard: typeof import('element-plus/es')['ElCard']
@ -31,16 +30,21 @@ declare module '@vue/runtime-core' {
ElConfigProvider: typeof import('element-plus/es')['ElConfigProvider']
ElDescriptions: typeof import('element-plus/es')['ElDescriptions']
ElDescriptionsItem: typeof import('element-plus/es')['ElDescriptionsItem']
ElDialog: typeof import('element-plus/es')['ElDialog']
ElDivider: typeof import('element-plus/es')['ElDivider']
ElDrawer: typeof import('element-plus/es')['ElDrawer']
ElDropdown: typeof import('element-plus/es')['ElDropdown']
ElDropdownItem: typeof import('element-plus/es')['ElDropdownItem']
ElDropdownMenu: typeof import('element-plus/es')['ElDropdownMenu']
ElementBaseInfo: typeof import('./../components/bpmnProcessDesigner/package/penal/base/ElementBaseInfo.vue')['default']
ElementForm: typeof import('./../components/bpmnProcessDesigner/package/penal/form/ElementForm.vue')['default']
ElementListeners: typeof import('./../components/bpmnProcessDesigner/package/penal/listeners/ElementListeners.vue')['default']
ElementMultiInstance: typeof import('./../components/bpmnProcessDesigner/package/penal/multi-instance/ElementMultiInstance.vue')['default']
ElementOtherConfig: typeof import('./../components/bpmnProcessDesigner/package/penal/other/ElementOtherConfig.vue')['default']
ElementProperties: typeof import('./../components/bpmnProcessDesigner/package/penal/properties/ElementProperties.vue')['default']
ElementTask: typeof import('./../components/bpmnProcessDesigner/package/penal/task/ElementTask.vue')['default']
ElForm: typeof import('element-plus/es')['ElForm']
ElFormItem: typeof import('element-plus/es')['ElFormItem']
ElIcon: typeof import('element-plus/es')['ElIcon']
ElImage: typeof import('element-plus/es')['ElImage']
ElImageViewer: typeof import('element-plus/es')['ElImageViewer']
ElInput: typeof import('element-plus/es')['ElInput']
ElInputNumber: typeof import('element-plus/es')['ElInputNumber']
@ -51,23 +55,21 @@ declare module '@vue/runtime-core' {
ElRadioButton: typeof import('element-plus/es')['ElRadioButton']
ElRadioGroup: typeof import('element-plus/es')['ElRadioGroup']
ElRow: typeof import('element-plus/es')['ElRow']
ElScroll: typeof import('element-plus/es')['ElScroll']
ElScrollbar: typeof import('element-plus/es')['ElScrollbar']
ElSelect: typeof import('element-plus/es')['ElSelect']
ElSkeleton: typeof import('element-plus/es')['ElSkeleton']
ElSpace: typeof import('element-plus/es')['ElSpace']
ElSwitch: typeof import('element-plus/es')['ElSwitch']
ElTable: typeof import('element-plus/es')['ElTable']
ElTableColumn: typeof import('element-plus/es')['ElTableColumn']
ElTabPane: typeof import('element-plus/es')['ElTabPane']
ElTabs: typeof import('element-plus/es')['ElTabs']
ElTag: typeof import('element-plus/es')['ElTag']
ElTimeline: typeof import('element-plus/es')['ElTimeline']
ElTimelineItem: typeof import('element-plus/es')['ElTimelineItem']
ElTooltip: typeof import('element-plus/es')['ElTooltip']
ElTransfer: typeof import('element-plus/es')['ElTransfer']
ElTree: typeof import('element-plus/es')['ElTree']
ElTreeSelect: typeof import('element-plus/es')['ElTreeSelect']
ElUpload: typeof import('element-plus/es')['ElUpload']
Error: typeof import('./../components/Error/src/Error.vue')['default']
FlowCondition: typeof import('./../components/bpmnProcessDesigner/package/penal/flow-condition/FlowCondition.vue')['default']
Form: typeof import('./../components/Form/src/Form.vue')['default']
Highlight: typeof import('./../components/Highlight/src/Highlight.vue')['default']
Icon: typeof import('./../components/Icon/src/Icon.vue')['default']
@ -76,16 +78,25 @@ declare module '@vue/runtime-core' {
ImageViewer: typeof import('./../components/ImageViewer/src/ImageViewer.vue')['default']
Infotip: typeof import('./../components/Infotip/src/Infotip.vue')['default']
InputPassword: typeof import('./../components/InputPassword/src/InputPassword.vue')['default']
ProcessDesigner: typeof import('./../components/bpmnProcessDesigner/package/designer/ProcessDesigner.vue')['default']
ProcessPalette: typeof import('./../components/bpmnProcessDesigner/package/palette/ProcessPalette.vue')['default']
ProcessViewer: typeof import('./../components/bpmnProcessDesigner/package/designer/ProcessViewer.vue')['default']
PropertiesPanel: typeof import('./../components/bpmnProcessDesigner/package/penal/PropertiesPanel.vue')['default']
Qrcode: typeof import('./../components/Qrcode/src/Qrcode.vue')['default']
ReceiveTask: typeof import('./../components/bpmnProcessDesigner/package/penal/task/task-components/ReceiveTask.vue')['default']
RouterLink: typeof import('vue-router')['RouterLink']
RouterView: typeof import('vue-router')['RouterView']
ScriptTask: typeof import('./../components/bpmnProcessDesigner/package/penal/task/task-components/ScriptTask.vue')['default']
Search: typeof import('./../components/Search/src/Search.vue')['default']
SignalAndMessage: typeof import('./../components/bpmnProcessDesigner/package/penal/signal-message/SignalAndMessage.vue')['default']
Sticky: typeof import('./../components/Sticky/src/Sticky.vue')['default']
Table: typeof import('./../components/Table/src/Table.vue')['default']
Tooltip: typeof import('./../components/Tooltip/src/Tooltip.vue')['default']
UploadFile: typeof import('./../components/UploadFile/src/UploadFile.vue')['default']
UploadImg: typeof import('./../components/UploadFile/src/UploadImg.vue')['default']
UploadImgs: typeof import('./../components/UploadFile/src/UploadImgs.vue')['default']
UserTask: typeof import('./../components/bpmnProcessDesigner/package/penal/task/task-components/UserTask.vue')['default']
UserTaskListeners: typeof import('./../components/bpmnProcessDesigner/package/penal/listeners/UserTaskListeners.vue')['default']
Verify: typeof import('./../components/Verifition/src/Verify.vue')['default']
VerifyPoints: typeof import('./../components/Verifition/src/Verify/VerifyPoints.vue')['default']
VerifySlide: typeof import('./../components/Verifition/src/Verify/VerifySlide.vue')['default']

View File

@ -0,0 +1,54 @@
/**
* https://github.com/xaboy/form-create-designer 封装的工具类
*/
// 编码表单 Conf
export const encodeConf = (designerRef: object) => {
// @ts-ignore
return JSON.stringify(designerRef.value.getOption())
}
// 编码表单 Fields
export const encodeFields = (designerRef: object) => {
// @ts-ignore
const rule = designerRef.value.getRule()
const fields: string[] = []
rule.forEach((item) => {
fields.push(JSON.stringify(item))
})
return fields
}
// 解码表单 Fields
export const decodeFields = (fields: string[]) => {
const rule: object[] = []
fields.forEach((item) => {
rule.push(JSON.parse(item))
})
return rule
}
// 设置表单的 Conf 和 Fields
export const setConfAndFields = (designerRef: object, conf: string, fields: string) => {
// @ts-ignore
designerRef.value.setOption(JSON.parse(conf))
// @ts-ignore
designerRef.value.setRule(decodeFields(fields))
}
// 设置表单的 Conf 和 Fields
export const setConfAndFields2 = (
detailPreview: object,
conf: string,
fields: string,
value?: object
) => {
// @ts-ignore
detailPreview.value.option = JSON.parse(conf)
// @ts-ignore
detailPreview.value.rule = decodeFields(fields)
if (value) {
// @ts-ignore
detailPreview.value.value = value
}
}

View File

@ -147,3 +147,30 @@ export function formatAxis(param: Date): string {
else if (hour < 22) return '晚上好'
else return '夜里好'
}
/**
* xx
*
* @param ms
* @returns {string}
*/
export function formatPast2(ms) {
const day = Math.floor(ms / (24 * 60 * 60 * 1000))
const hour = Math.floor(ms / (60 * 60 * 1000) - day * 24)
const minute = Math.floor(ms / (60 * 1000) - day * 24 * 60 - hour * 60)
const second = Math.floor(ms / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - minute * 60)
if (day > 0) {
return day + '天' + hour + '小时' + minute + '分钟'
}
if (hour > 0) {
return hour + '小时' + minute + '分钟'
}
if (minute > 0) {
return minute + '分钟'
}
if (second > 0) {
return second + '秒'
} else {
return 0 + '秒'
}
}

View File

@ -0,0 +1,76 @@
import { reactive } from 'vue'
import { VxeCrudSchema, useVxeCrudSchemas } from '@/hooks/web/useVxeCrudSchemas'
import { DICT_TYPE } from '@/utils/dict'
// CrudSchema
const crudSchemas = reactive<VxeCrudSchema>({
primaryKey: 'id',
primaryType: null,
action: true,
columns: [
{
title: '定义编号',
field: 'id',
table: {
width: 360
}
},
{
title: '定义名称',
field: 'name',
table: {
width: 120,
slots: {
default: 'name_default'
}
}
},
{
title: '流程分类',
field: 'category',
dictType: DICT_TYPE.BPM_MODEL_CATEGORY,
dictClass: 'number'
},
{
title: '表单信息',
field: 'formId',
table: {
width: 120,
slots: {
default: 'formId_default'
}
}
},
{
title: '流程版本',
field: 'version',
table: {
width: 80,
slots: {
default: 'version_default'
}
}
},
{
title: '激活状态',
field: 'suspensionState',
table: {
width: 80,
slots: {
default: 'suspensionState_default'
}
}
},
{
title: '部署时间',
field: 'deploymentTime',
isForm: false,
formatter: 'formatDate',
table: {
width: 180
}
}
]
})
export const { allSchemas } = useVxeCrudSchemas(crudSchemas)

View File

@ -0,0 +1,108 @@
<template>
<ContentWrap>
<!-- 列表 -->
<XTable @register="registerTable">
<!-- 流程名称 -->
<template #name_default="{ row }">
<XTextButton :title="row.name" @click="handleBpmnDetail(row.id)" />
</template>
<!-- 表单信息 -->
<template #formId_default="{ row }">
<XTextButton
v-if="row.formType === 10"
:title="row.formName"
@click="handleFormDetail(row)"
/>
<XTextButton v-else :title="row.formCustomCreatePath" @click="handleFormDetail(row)" />
</template>
<!-- 流程版本 -->
<template #version_default="{ row }">
<el-tag>v{{ row.version }}</el-tag>
</template>
<!-- 激活状态 -->
<template #suspensionState_default="{ row }">
<el-tag type="success" v-if="row.suspensionState === 1">激活</el-tag>
<el-tag type="warning" v-if="row.suspensionState === 2">挂起</el-tag>
</template>
<!-- 操作 -->
<template #actionbtns_default="{ row }">
<XTextButton
preIcon="ep:user"
title="分配规则"
v-hasPermi="['bpm:task-assign-rule:query']"
@click="handleAssignRule(row)"
/>
</template>
</XTable>
<!-- 表单详情的弹窗 -->
<XModal v-model="formDetailVisible" width="800" title="表单详情" :show-footer="false">
<form-create
:rule="formDetailPreview.rule"
:option="formDetailPreview.option"
v-if="formDetailVisible"
/>
</XModal>
</ContentWrap>
</template>
<script setup lang="ts">
// import
import { ref } from 'vue'
// import
import * as DefinitionApi from '@/api/bpm/definition'
// import * as ModelApi from '@/api/bpm/model'
import { allSchemas } from './definition.data'
const message = useMessage() //
const router = useRouter() //
const { query } = useRoute() //
import { setConfAndFields2 } from '@/utils/formCreate'
// ========== ==========
const queryParams = reactive({
key: query.key
})
const [registerTable] = useXTable({
allSchemas: allSchemas,
getListApi: DefinitionApi.getProcessDefinitionPageApi,
params: queryParams
})
//
const formDetailVisible = ref(false)
const formDetailPreview = ref({
rule: [],
option: {}
})
const handleFormDetail = async (row) => {
if (row.formType == 10) {
//
setConfAndFields2(formDetailPreview, row.formConf, row.formFields)
//
formDetailVisible.value = true
} else {
await router.push({
path: row.formCustomCreatePath
})
}
}
//
const handleBpmnDetail = (row) => {
// TODO
console.log(row)
message.success('流程组件开发中,预计 2 月底完成')
}
//
const handleAssignRule = (row) => {
router.push({
name: 'BpmTaskAssignRuleList',
query: {
modelId: row.id
}
})
}
</script>

View File

@ -1,4 +1,5 @@
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { VxeCrudSchema } from '@/hooks/web/useVxeCrudSchemas'
const { t } = useI18n() // 国际化
// 表单校验
@ -7,52 +8,36 @@ export const rules = reactive({
})
// CrudSchema
const crudSchemas = reactive<CrudSchema[]>([
{
label: t('common.index'),
field: 'id',
type: 'index',
form: {
show: false
const crudSchemas = reactive<VxeCrudSchema>({
primaryKey: 'id',
primaryType: 'seq',
primaryTitle: '表单编号',
action: true,
columns: [
{
title: '表单名',
field: 'name',
isSearch: true
},
detail: {
show: false
}
},
{
label: '表单名',
field: 'name',
search: {
show: true
}
},
{
label: t('common.status'),
field: 'status',
dictType: DICT_TYPE.COMMON_STATUS,
dictClass: 'number'
},
{
label: '备注',
field: 'remark'
},
{
label: t('common.createTime'),
field: 'createTime',
form: {
show: false
}
},
{
label: t('table.action'),
field: 'action',
width: '240px',
form: {
show: false
{
title: t('common.status'),
field: 'status',
dictType: DICT_TYPE.COMMON_STATUS,
dictClass: 'number'
},
detail: {
show: false
{
title: '备注',
field: 'remark'
},
{
title: t('common.createTime'),
field: 'createTime',
formatter: 'formatDate',
isForm: false,
table: {
width: 180
}
}
}
])
export const { allSchemas } = useCrudSchemas(crudSchemas)
]
})
export const { allSchemas } = useVxeCrudSchemas(crudSchemas)

View File

@ -0,0 +1,115 @@
<template>
<ContentWrap>
<!-- 表单设计器 -->
<fc-designer ref="designer" height="780px">
<template #handle>
<XButton type="primary" :title="t('action.save')" @click="handleSave" />
</template>
</fc-designer>
<!-- 表单保存的弹窗 -->
<XModal v-model="dialogVisible" title="保存表单">
<el-form ref="formRef" :model="formValues" :rules="formRules" label-width="80px">
<el-form-item label="表单名" prop="name">
<el-input v-model="formValues.name" placeholder="请输入表单名" />
</el-form-item>
<el-form-item label="开启状态" prop="status">
<el-radio-group v-model="formValues.status">
<el-radio
v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
:key="dict.value"
:label="dict.value"
>
{{ dict.label }}
</el-radio>
</el-radio-group>
</el-form-item>
<el-form-item label="备注" prop="remark">
<el-input v-model="formValues.remark" type="textarea" placeholder="请输入备注" />
</el-form-item>
</el-form>
<!-- 操作按钮 -->
<template #footer>
<!-- 按钮保存 -->
<XButton
type="primary"
:title="t('action.save')"
:loading="dialogLoading"
@click="submitForm"
/>
<!-- 按钮关闭 -->
<XButton :title="t('dialog.close')" @click="dialogVisible = false" />
</template>
</XModal>
</ContentWrap>
</template>
<script setup lang="ts" name="BpmFormEditor">
import { FormInstance } from 'element-plus'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { CommonStatusEnum } from '@/utils/constants'
import * as FormApi from '@/api/bpm/form'
import { encodeConf, encodeFields, setConfAndFields } from '@/utils/formCreate'
const { t } = useI18n() //
const message = useMessage() //
const { query } = useRoute() //
const designer = ref() //
const dialogVisible = ref(false) //
const dialogLoading = ref(false) //
const formRef = ref<FormInstance>()
const formRules = reactive({
name: [{ required: true, message: '表单名不能为空', trigger: 'blur' }],
status: [{ required: true, message: '开启状态不能为空', trigger: 'blur' }]
})
const formValues = ref({
name: '',
status: CommonStatusEnum.ENABLE,
remark: ''
})
//
const handleSave = () => {
dialogVisible.value = true
}
//
const submitForm = async () => {
//
const elForm = unref(formRef)
if (!elForm) return
const valid = await elForm.validate()
if (!valid) return
//
dialogLoading.value = true
try {
const data = formValues.value as FormApi.FormVO
data.conf = encodeConf(designer) //
data.fields = encodeFields(designer) //
if (!data.id) {
await FormApi.createFormApi(data)
message.success(t('common.createSuccess'))
} else {
await FormApi.updateFormApi(data)
message.success(t('common.updateSuccess'))
}
dialogVisible.value = false
} finally {
dialogLoading.value = false
}
}
// ========== ==========
onMounted(() => {
//
const id = query.id as unknown as number
if (!id) {
return
}
//
FormApi.getFormApi(id).then((data) => {
formValues.value = data
setConfAndFields(designer, data.conf, data.fields)
})
})
</script>

View File

@ -1,165 +1,96 @@
<script setup lang="ts" name="Form">
import dayjs from 'dayjs'
import { DICT_TYPE } from '@/utils/dict'
import type { FormExpose } from '@/components/Form'
import type { FormVO } from '@/api/bpm/form/types'
import { rules, allSchemas } from './form.data'
<template>
<ContentWrap>
<!-- 列表 -->
<div>
<XTable @register="registerTable">
<!-- 操作新增 -->
<template #toolbar_buttons>
<XButton
type="primary"
preIcon="ep:zoom-in"
:title="t('action.add')"
v-hasPermi="['system:post:create']"
@click="handleCreate()"
/>
</template>
<template #actionbtns_default="{ row }">
<!-- 操作修改 -->
<XTextButton
preIcon="ep:edit"
:title="t('action.edit')"
v-hasPermi="['bpm:form:update']"
@click="handleUpdate(row.id)"
/>
<!-- 操作详情 -->
<XTextButton
preIcon="ep:view"
:title="t('action.detail')"
v-hasPermi="['bpm:form:query']"
@click="handleDetail(row.id)"
/>
<!-- 操作删除 -->
<XTextButton
preIcon="ep:delete"
:title="t('action.del')"
v-hasPermi="['bpm:form:delete']"
@click="deleteData(row.id)"
/>
</template>
</XTable>
<!-- 表单详情的弹窗 -->
<XModal v-model="detailOpen" width="800" title="表单详情">
<form-create :rule="detailPreview.rule" :option="detailPreview.option" v-if="detailOpen" />
</XModal>
</div>
</ContentWrap>
</template>
<script setup lang="ts" name="BpmForm">
// import
// import
import * as FormApi from '@/api/bpm/form'
import { useTable } from '@/hooks/web/useTable'
import { allSchemas } from './form.data'
// import
import { setConfAndFields2 } from '@/utils/formCreate'
const { t } = useI18n() //
const message = useMessage()
const router = useRouter() //
// ========== ==========
const { register, tableObject, methods } = useTable<FormVO>({
//
const [registerTable, { deleteData }] = useXTable({
allSchemas: allSchemas,
getListApi: FormApi.getFormPageApi,
delListApi: FormApi.deleteFormApi
deleteApi: FormApi.deleteFormApi
})
const { getList, setSearchParams, delList } = methods
// ========== CRUD ==========
const actionLoading = ref(false) //
const actionType = ref('') //
const dialogVisible = ref(false) //
const dialogTitle = ref('edit') //
const formRef = ref<FormExpose>() // Ref
//
const setDialogTile = (type: string) => {
dialogTitle.value = t('action.' + type)
actionType.value = type
dialogVisible.value = true
}
//
const handleCreate = () => {
setDialogTile('create')
router.push({
name: 'bpmFormEditor'
})
}
//
const handleUpdate = async (row: FormVO) => {
setDialogTile('update')
//
const res = await FormApi.getFormApi(row.id)
unref(formRef)?.setValues(res)
}
//
const submitForm = async () => {
const elForm = unref(formRef)?.getElFormRef()
if (!elForm) return
elForm.validate(async (valid) => {
if (valid) {
actionLoading.value = true
//
try {
const data = unref(formRef)?.formModel as FormVO
if (actionType.value === 'create') {
await FormApi.createFormApi(data)
message.success(t('common.createSuccess'))
} else {
await FormApi.updateFormApi(data)
message.success(t('common.updateSuccess'))
}
//
dialogVisible.value = false
await getList()
} finally {
actionLoading.value = false
}
const handleUpdate = async (rowId: number) => {
await router.push({
name: 'bpmFormEditor',
query: {
id: rowId
}
})
}
// ========== ==========
const detailData = ref() // Ref
//
const handleDetail = async (row: FormVO) => {
//
detailData.value = row
setDialogTile('detail')
const detailOpen = ref(false)
const detailPreview = ref({
rule: [],
option: {}
})
const handleDetail = async (rowId: number) => {
//
const data = await FormApi.getFormApi(rowId)
setConfAndFields2(detailPreview, data.conf, data.fields)
//
detailOpen.value = true
}
// ========== ==========
getList()
</script>
<template>
<!-- 搜索工作区 -->
<ContentWrap>
<Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />
</ContentWrap>
<ContentWrap>
<!-- 操作工具栏 -->
<div class="mb-10px">
<el-button type="primary" v-hasPermi="['bpm:form:create']" @click="handleCreate()">
<Icon icon="ep:zoom-in" class="mr-5px" /> {{ t('action.add') }}
</el-button>
</div>
<!-- 列表 -->
<Table
:columns="allSchemas.tableColumns"
:selection="false"
:data="tableObject.tableList"
:loading="tableObject.loading"
:pagination="{
total: tableObject.total
}"
v-model:pageSize="tableObject.pageSize"
v-model:currentPage="tableObject.currentPage"
@register="register"
>
<template #status="{ row }">
<DictTag :type="DICT_TYPE.COMMON_STATUS" :value="row.status" />
</template>
<template #createTime="{ row }">
<span>{{ dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss') }}</span>
</template>
<template #action="{ row }">
<el-button link type="primary" v-hasPermi="['bpm:form:update']" @click="handleUpdate(row)">
<Icon icon="ep:edit" class="mr-1px" /> {{ t('action.edit') }}
</el-button>
<el-button link type="primary" v-hasPermi="['bpm:form:update']" @click="handleDetail(row)">
<Icon icon="ep:view" class="mr-1px" /> {{ t('action.detail') }}
</el-button>
<el-button
link
type="primary"
v-hasPermi="['bpm:form:delete']"
@click="delList(row.id, false)"
>
<Icon icon="ep:delete" class="mr-1px" /> {{ t('action.del') }}
</el-button>
</template>
</Table>
</ContentWrap>
<XModal v-model="dialogVisible" :title="dialogTitle">
<!-- 对话框(添加 / 修改) -->
<Form
v-if="['create', 'update'].includes(actionType)"
:schema="allSchemas.formSchema"
:rules="rules"
ref="formRef"
/>
<!-- 对话框(详情) -->
<Descriptions
v-if="actionType === 'detail'"
:schema="allSchemas.detailSchema"
:data="detailData"
/>
<!-- 操作按钮 -->
<template #footer>
<!-- 按钮保存 -->
<XButton
v-if="['create', 'update'].includes(actionType)"
type="primary"
:title="t('action.save')"
:loading="actionLoading"
@click="submitForm()"
/>
<!-- 按钮关闭 -->
<XButton :loading="actionLoading" :title="t('dialog.close')" @click="dialogVisible = false" />
</template>
</XModal>
</template>

View File

@ -1,69 +1,63 @@
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { VxeCrudSchema } from '@/hooks/web/useVxeCrudSchemas'
const { t } = useI18n() // 国际化
// 表单校验
export const rules = reactive({
name: [required]
name: [required],
description: [required],
memberUserIds: [required],
status: [required]
})
// CrudSchema
const crudSchemas = reactive<CrudSchema[]>([
{
label: t('common.index'),
field: 'id',
type: 'index',
form: {
show: false
const crudSchemas = reactive<VxeCrudSchema>({
primaryKey: 'id',
primaryType: 'id',
primaryTitle: '编号',
action: true,
columns: [
{
title: '组名',
field: 'name',
isSearch: true
},
detail: {
show: false
}
},
{
label: '组名',
field: 'name',
search: {
show: true
}
},
{
label: '成员',
field: 'memberUserIds'
},
{
label: '描述',
field: 'description'
},
{
label: t('common.status'),
field: 'status',
dictType: DICT_TYPE.COMMON_STATUS,
dictClass: 'number'
},
{
label: '备注',
field: 'remark',
table: {
show: false
}
},
{
label: t('common.createTime'),
field: 'createTime',
form: {
show: false
}
},
{
label: t('table.action'),
field: 'action',
width: '240px',
form: {
show: false
{
title: '成员',
field: 'memberUserIds',
table: {
slots: {
default: 'memberUserIds_default'
}
}
},
detail: {
show: false
{
title: '描述',
field: 'description'
},
{
title: t('common.status'),
field: 'status',
dictType: DICT_TYPE.COMMON_STATUS,
dictClass: 'number',
isSearch: true
},
{
title: t('common.createTime'),
field: 'createTime',
formatter: 'formatDate',
isForm: false,
isSearch: true,
search: {
show: true,
itemRender: {
name: 'XDataTimePicker'
}
},
table: {
width: 180
}
}
}
])
export const { allSchemas } = useCrudSchemas(crudSchemas)
]
})
export const { allSchemas } = useVxeCrudSchemas(crudSchemas)

View File

@ -1,23 +1,116 @@
<script setup lang="ts" name="Group">
import dayjs from 'dayjs'
import { DICT_TYPE } from '@/utils/dict'
import { useTable } from '@/hooks/web/useTable'
import type { FormExpose } from '@/components/Form'
import type { UserGroupVO } from '@/api/bpm/userGroup/types'
import { rules, allSchemas } from './group.data'
<template>
<ContentWrap>
<!-- 列表 -->
<XTable @register="registerTable">
<template #toolbar_buttons>
<!-- 操作新增 -->
<XButton
type="primary"
preIcon="ep:zoom-in"
:title="t('action.add')"
v-hasPermi="['bpm:user-group:create']"
@click="handleCreate()"
/>
</template>
<template #memberUserIds_default="{ row }">
<span v-for="userId in row.memberUserIds" :key="userId">
{{ getUserNickname(userId) }} &nbsp;
</span>
</template>
<template #actionbtns_default="{ row }">
<!-- 操作修改 -->
<XTextButton
preIcon="ep:edit"
:title="t('action.edit')"
v-hasPermi="['bpm:user-group:update']"
@click="handleUpdate(row.id)"
/>
<!-- 操作详情 -->
<XTextButton
preIcon="ep:view"
:title="t('action.detail')"
v-hasPermi="['bpm:user-group:query']"
@click="handleDetail(row.id)"
/>
<!-- 操作删除 -->
<XTextButton
preIcon="ep:delete"
:title="t('action.del')"
v-hasPermi="['bpm:user-group:delete']"
@click="deleteData(row.id)"
/>
</template>
</XTable>
</ContentWrap>
<XModal v-model="dialogVisible" :title="dialogTitle">
<!-- 对话框(添加 / 修改) -->
<Form
v-if="['create', 'update'].includes(actionType)"
:schema="allSchemas.formSchema"
:rules="rules"
ref="formRef"
>
<template #memberUserIds="form">
<el-select v-model="form.memberUserIds" multiple>
<el-option v-for="item in users" :key="item.id" :label="item.nickname" :value="item.id" />
</el-select>
</template>
</Form>
<!-- 对话框(详情) -->
<Descriptions
v-if="actionType === 'detail'"
:schema="allSchemas.detailSchema"
:data="detailData"
>
<template #memberUserIds="{ row }">
<span v-for="userId in row.memberUserIds" :key="userId">
{{ getUserNickname(userId) }} &nbsp;
</span>
</template>
</Descriptions>
<!-- 操作按钮 -->
<template #footer>
<!-- 按钮保存 -->
<XButton
v-if="['create', 'update'].includes(actionType)"
type="primary"
:title="t('action.save')"
:loading="actionLoading"
@click="submitForm"
/>
<!-- 按钮关闭 -->
<XButton :loading="actionLoading" :title="t('dialog.close')" @click="dialogVisible = false" />
</template>
</XModal>
</template>
<script setup lang="ts">
// import
import * as UserGroupApi from '@/api/bpm/userGroup'
import { getListSimpleUsersApi } from '@/api/system/user'
import { UserVO } from '@/api/system/user'
import { getListSimpleUsersApi, UserVO } from '@/api/system/user'
import { allSchemas, rules } from './group.data'
import { FormExpose } from '@/components/Form'
const { t } = useI18n() //
const message = useMessage()
// ========== ==========
const { register, tableObject, methods } = useTable<UserGroupVO>({
const message = useMessage() //
//
const [registerTable, { reload, deleteData }] = useXTable({
allSchemas: allSchemas,
getListApi: UserGroupApi.getUserGroupPageApi,
delListApi: UserGroupApi.deleteUserGroupApi
deleteApi: UserGroupApi.deleteUserGroupApi
})
const { getList, setSearchParams, delList } = methods
//
const users = ref<UserVO[]>([])
const getUserNickname = (userId) => {
for (const user of users.value) {
if (user.id === userId) {
return user.nickname
}
}
return '未知(' + userId + ')'
}
// ========== CRUD ==========
const actionLoading = ref(false) //
@ -25,13 +118,7 @@ const actionType = ref('') // 操作按钮的类型
const dialogVisible = ref(false) //
const dialogTitle = ref('edit') //
const formRef = ref<FormExpose>() // Ref
// ========== ==========
const userOptions = ref<UserVO[]>([])
const getUserOptions = async () => {
const res = await getListSimpleUsersApi()
userOptions.value.push(...res)
}
const detailData = ref() // Ref
//
const setDialogTile = (type: string) => {
@ -46,13 +133,19 @@ const handleCreate = () => {
}
//
const handleUpdate = async (row: UserGroupVO) => {
const handleUpdate = async (rowId: number) => {
setDialogTile('update')
//
const res = await UserGroupApi.getUserGroupApi(row.id)
const res = await UserGroupApi.getUserGroupApi(rowId)
unref(formRef)?.setValues(res)
}
//
const handleDetail = async (rowId: number) => {
setDialogTile('detail')
detailData.value = await UserGroupApi.getUserGroupApi(rowId)
}
//
const submitForm = async () => {
const elForm = unref(formRef)?.getElFormRef()
@ -62,7 +155,7 @@ const submitForm = async () => {
actionLoading.value = true
//
try {
const data = unref(formRef)?.formModel as UserGroupVO
const data = unref(formRef)?.formModel as UserGroupApi.UserGroupVO
if (actionType.value === 'create') {
await UserGroupApi.createUserGroupApi(data)
message.success(t('common.createSuccess'))
@ -70,147 +163,20 @@ const submitForm = async () => {
await UserGroupApi.updateUserGroupApi(data)
message.success(t('common.updateSuccess'))
}
//
dialogVisible.value = false
await getList()
} finally {
actionLoading.value = false
//
await reload()
}
}
})
}
//
const getUserNickName = (userId: number) => {
for (const user of userOptions.value) {
if (user.id === userId) return user.nickname
}
return '未知(' + userId + ')'
}
// ========== ==========
const detailData = ref() // Ref
//
const handleDetail = async (row: UserGroupVO) => {
//
detailData.value = row
setDialogTile('detail')
}
// ========== ==========
onMounted(async () => {
await getList()
await getUserOptions()
onMounted(() => {
getListSimpleUsersApi().then((data) => {
users.value = data
})
})
</script>
<template>
<!-- 搜索工作区 -->
<ContentWrap>
<Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />
</ContentWrap>
<ContentWrap>
<!-- 操作工具栏 -->
<div class="mb-10px">
<el-button type="primary" v-hasPermi="['bpm:user-group:create']" @click="handleCreate()">
<Icon icon="ep:zoom-in" class="mr-5px" /> {{ t('action.add') }}
</el-button>
</div>
<!-- 列表 -->
<Table
:columns="allSchemas.tableColumns"
:selection="false"
:data="tableObject.tableList"
:loading="tableObject.loading"
:pagination="{
total: tableObject.total
}"
v-model:pageSize="tableObject.pageSize"
v-model:currentPage="tableObject.currentPage"
@register="register"
>
<template #status="{ row }">
<DictTag :type="DICT_TYPE.COMMON_STATUS" :value="row.status" />
</template>
<template #memberUserIds="{ row }">
<span v-for="userId in row.memberUserIds" :key="userId">
{{ getUserNickName(userId) + ' ' }}
</span>
</template>
<template #createTime="{ row }">
<span>{{ dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss') }}</span>
</template>
<template #action="{ row }">
<el-button
link
type="primary"
v-hasPermi="['bpm:user-group:update']"
@click="handleUpdate(row)"
>
<Icon icon="ep:edit" class="mr-1px" /> {{ t('action.edit') }}
</el-button>
<el-button
link
type="primary"
v-hasPermi="['bpm:user-group:update']"
@click="handleDetail(row)"
>
<Icon icon="ep:view" class="mr-1px" /> {{ t('action.detail') }}
</el-button>
<el-button
link
type="primary"
v-hasPermi="['bpm:user-group:delete']"
@click="delList(row.id, false)"
>
<Icon icon="ep:delete" class="mr-1px" /> {{ t('action.del') }}
</el-button>
</template>
</Table>
</ContentWrap>
<XModal v-model="dialogVisible" :title="dialogTitle">
<!-- 对话框(添加 / 修改) -->
<Form
v-if="['create', 'update'].includes(actionType)"
:schema="allSchemas.formSchema"
:rules="rules"
ref="formRef"
>
<template #memberUserIds="form">
<el-select v-model="form['memberUserIds']" multiple>
<el-option
v-for="item in userOptions"
:key="item.id"
:label="item.nickname"
:value="item.id"
/>
</el-select>
</template>
</Form>
<!-- 对话框(详情) -->
<Descriptions
v-if="actionType === 'detail'"
:schema="allSchemas.detailSchema"
:data="detailData"
>
<template #memberUserIds="{ row }">
<span v-for="userId in row.memberUserIds" :key="userId">
{{ getUserNickName(userId) + ' ' }}
</span>
</template>
</Descriptions>
<template #footer>
<!-- 按钮保存 -->
<XButton
v-if="['create', 'update'].includes(actionType)"
type="primary"
:title="t('action.save')"
:loading="actionLoading"
@click="submitForm()"
/>
<!-- 按钮关闭 -->
<XButton :loading="actionLoading" :title="t('dialog.close')" @click="dialogVisible = false" />
</template>
</XModal>
</template>

View File

@ -1,214 +1,586 @@
<script setup lang="ts" name="Model">
import dayjs from 'dayjs'
import { DICT_TYPE } from '@/utils/dict'
import { useTable } from '@/hooks/web/useTable'
import type { FormExpose } from '@/components/Form'
import type { ModelVO } from '@/api/bpm/model/types'
import { rules, allSchemas } from './model.data'
<template>
<ContentWrap>
<!-- 列表 -->
<XTable @register="registerTable">
<template #toolbar_buttons>
<!-- 操作新增 -->
<XButton
type="primary"
preIcon="ep:zoom-in"
title="新建流程"
v-hasPermi="['bpm:model:create']"
@click="handleCreate"
/>
<!-- 操作导入 -->
<XButton
type="warning"
preIcon="ep:upload"
:title="'导入流程'"
@click="handleImport"
style="margin-left: 10px"
/>
</template>
<!-- 流程名称 -->
<template #name_default="{ row }">
<XTextButton :title="row.name" @click="handleBpmnDetail(row.id)" />
</template>
<!-- 表单信息 -->
<template #formId_default="{ row }">
<XTextButton
v-if="row.formType === 10"
:title="forms.find((form) => form.id === row.formId)?.name || row.formId"
@click="handleFormDetail(row)"
/>
<XTextButton v-else :title="row.formCustomCreatePath" @click="handleFormDetail(row)" />
</template>
<!-- 流程版本 -->
<template #version_default="{ row }">
<el-tag v-if="row.processDefinition">v{{ row.processDefinition.version }}</el-tag>
<el-tag type="warning" v-else>未部署</el-tag>
</template>
<!-- 激活状态 -->
<template #status_default="{ row }">
<el-switch
v-if="row.processDefinition"
v-model="row.processDefinition.suspensionState"
:active-value="1"
:inactive-value="2"
@change="handleChangeState(row)"
/>
</template>
<!-- 操作 -->
<template #actionbtns_default="{ row }">
<XTextButton
preIcon="ep:edit"
title="修改流程"
v-hasPermi="['bpm:model:update']"
@click="handleUpdate(row.id)"
/>
<XTextButton
preIcon="ep:setting"
title="设计流程"
v-hasPermi="['bpm:model:update']"
@click="handleDesign(row)"
/>
<XTextButton
preIcon="ep:user"
title="分配规则"
v-hasPermi="['bpm:task-assign-rule:query']"
@click="handleAssignRule(row)"
/>
<XTextButton
preIcon="ep:position"
title="发布流程"
v-hasPermi="['bpm:model:deploy']"
@click="handleDeploy(row)"
/>
<XTextButton
preIcon="ep:aim"
title="流程定义"
v-hasPermi="['bpm:process-definition:query']"
@click="handleDefinitionList(row)"
/>
<!-- 操作删除 -->
<XTextButton
preIcon="ep:delete"
:title="t('action.del')"
v-hasPermi="['bpm:model:delete']"
@click="handleDelete(row.id)"
/>
</template>
</XTable>
<!-- 对话框(添加 / 修改流程) -->
<XModal v-model="dialogVisible" :title="dialogTitle" width="600">
<el-form
:loading="dialogLoading"
el-form
ref="saveFormRef"
:model="saveForm"
:rules="rules"
label-width="110px"
>
<el-form-item label="流程标识" prop="key">
<el-input
v-model="saveForm.key"
placeholder="请输入流标标识"
style="width: 330px"
:disabled="!!saveForm.id"
/>
<el-tooltip
v-if="!saveForm.id"
class="item"
effect="light"
content="新建后,流程标识不可修改!"
placement="top"
>
<i style="padding-left: 5px" class="el-icon-question"></i>
</el-tooltip>
<el-tooltip
v-else
class="item"
effect="light"
content="流程标识不可修改!"
placement="top"
>
<i style="padding-left: 5px" class="el-icon-question"></i>
</el-tooltip>
</el-form-item>
<el-form-item label="流程名称" prop="name">
<el-input
v-model="saveForm.name"
placeholder="请输入流程名称"
:disabled="!!saveForm.id"
clearable
/>
</el-form-item>
<el-form-item v-if="saveForm.id" label="流程分类" prop="category">
<el-select
v-model="saveForm.category"
placeholder="请选择流程分类"
clearable
style="width: 100%"
>
<el-option
v-for="dict in getDictOptions(DICT_TYPE.BPM_MODEL_CATEGORY)"
:key="dict.value"
:label="dict.label"
:value="dict.value"
/>
</el-select>
</el-form-item>
<el-form-item label="流程描述" prop="description">
<el-input type="textarea" v-model="saveForm.description" clearable />
</el-form-item>
<div v-if="saveForm.id">
<el-form-item label="表单类型" prop="formType">
<el-radio-group v-model="saveForm.formType">
<el-radio
v-for="dict in getDictOptions(DICT_TYPE.BPM_MODEL_FORM_TYPE)"
:key="parseInt(dict.value)"
:label="parseInt(dict.value)"
>
{{ dict.label }}
</el-radio>
</el-radio-group>
</el-form-item>
<el-form-item v-if="saveForm.formType === 10" label="流程表单" prop="formId">
<el-select v-model="saveForm.formId" clearable style="width: 100%">
<el-option v-for="form in forms" :key="form.id" :label="form.name" :value="form.id" />
</el-select>
</el-form-item>
<el-form-item
v-if="saveForm.formType === 20"
label="表单提交路由"
prop="formCustomCreatePath"
>
<el-input
v-model="saveForm.formCustomCreatePath"
placeholder="请输入表单提交路由"
style="width: 330px"
/>
<el-tooltip
class="item"
effect="light"
content="自定义表单的提交路径,使用 Vue 的路由地址例如说bpm/oa/leave/create"
placement="top"
>
<i style="padding-left: 5px" class="el-icon-question"></i>
</el-tooltip>
</el-form-item>
<el-form-item
v-if="saveForm.formType === 20"
label="表单查看路由"
prop="formCustomViewPath"
>
<el-input
v-model="saveForm.formCustomViewPath"
placeholder="请输入表单查看路由"
style="width: 330px"
/>
<el-tooltip
class="item"
effect="light"
content="自定义表单的查看路径,使用 Vue 的路由地址例如说bpm/oa/leave/view"
placement="top"
>
<i style="padding-left: 5px" class="el-icon-question"></i>
</el-tooltip>
</el-form-item>
</div>
</el-form>
<template #footer>
<!-- 按钮保存 -->
<XButton
type="primary"
:loading="dialogLoading"
@click="submitForm"
:title="t('action.save')"
/>
<!-- 按钮关闭 -->
<XButton
:loading="dialogLoading"
@click="dialogVisible = false"
:title="t('dialog.close')"
/>
</template>
</XModal>
<!-- 导入流程 -->
<XModal v-model="importDialogVisible" width="400" title="导入流程">
<div>
<el-upload
ref="uploadRef"
:action="importUrl"
:headers="uploadHeaders"
:drag="true"
:limit="1"
:multiple="true"
:show-file-list="true"
:disabled="uploadDisabled"
:on-exceed="handleExceed"
:on-success="handleFileSuccess"
:on-error="excelUploadError"
:auto-upload="false"
accept=".bpmn, .xml"
name="bpmnFile"
:data="importForm"
>
<el-icon class="el-icon--upload"><upload-filled /></el-icon>
<div class="el-upload__text"> 将文件拖到此处 <em>点击上传</em> </div>
<template #tip>
<div class="el-upload__tip" style="color: red">
提示仅允许导入bpmxml格式文件
</div>
<div>
<el-form
ref="importFormRef"
:model="importForm"
:rules="rules"
label-width="120px"
status-icon
>
<el-form-item label="流程标识" prop="key">
<el-input
v-model="importForm.key"
placeholder="请输入流标标识"
style="width: 250px"
/>
</el-form-item>
<el-form-item label="流程名称" prop="name">
<el-input v-model="importForm.name" placeholder="请输入流程名称" clearable />
</el-form-item>
<el-form-item label="流程描述" prop="description">
<el-input type="textarea" v-model="importForm.description" clearable />
</el-form-item>
</el-form>
</div>
</template>
</el-upload>
</div>
<template #footer>
<!-- 按钮保存 -->
<XButton
type="warning"
preIcon="ep:upload-filled"
:title="t('action.save')"
@click="submitFileForm"
/>
<XButton title="取 消" @click="uploadClose" />
</template>
</XModal>
<!-- 表单详情的弹窗 -->
<XModal v-model="formDetailVisible" width="800" title="表单详情" :show-footer="false">
<form-create
:rule="formDetailPreview.rule"
:option="formDetailPreview.option"
v-if="formDetailVisible"
/>
</XModal>
<!-- 流程模型图的预览 -->
<XModal title="流程图" v-model="showBpmnOpen" width="80%" height="90%">
<my-process-viewer
key="designer"
v-model="bpmnXML"
:value="bpmnXML"
v-bind="bpmnControlForm"
:prefix="bpmnControlForm.prefix"
/>
</XModal>
</ContentWrap>
</template>
<script setup lang="ts">
// import
import { DICT_TYPE, getDictOptions } from '@/utils/dict'
import { FormInstance, UploadInstance } from 'element-plus'
// import
import { getAccessToken, getTenantId } from '@/utils/auth'
import * as FormApi from '@/api/bpm/form'
import * as ModelApi from '@/api/bpm/model'
import { allSchemas, rules } from './model.data'
import { setConfAndFields2 } from '@/utils/formCreate'
const { t } = useI18n() //
const message = useMessage()
const message = useMessage() //
const router = useRouter() //
// ========== ==========
const { register, tableObject, methods } = useTable<ModelVO>({
getListApi: ModelApi.getModelPageApi,
delListApi: ModelApi.deleteModelApi
const showBpmnOpen = ref(false)
const bpmnXML = ref(null)
const bpmnControlForm = ref({
prefix: 'flowable'
})
const { getList, setSearchParams, delList } = methods
// ========== ==========
const [registerTable, { reload }] = useXTable({
allSchemas: allSchemas,
getListApi: ModelApi.getModelPageApi
})
const forms = ref() //
// ========== CRUD ==========
const actionLoading = ref(false) //
const actionType = ref('') //
const dialogVisible = ref(false) //
const dialogTitle = ref('edit') //
const formRef = ref<FormExpose>() // Ref
//
const setDialogTile = (type: string) => {
dialogTitle.value = t('action.' + type)
actionType.value = type
dialogVisible.value = true
}
//
const handleCreate = () => {
setDialogTile('create')
}
//
const handleUpdate = async (row: ModelVO) => {
setDialogTile('update')
//
const res = await ModelApi.getModelApi(row.id)
unref(formRef)?.setValues(res)
}
//
const submitForm = async () => {
const elForm = unref(formRef)?.getElFormRef()
if (!elForm) return
elForm.validate(async (valid) => {
if (valid) {
actionLoading.value = true
//
try {
const data = unref(formRef)?.formModel as ModelVO
if (actionType.value === 'create') {
await ModelApi.createModelApi(data)
message.success(t('common.createSuccess'))
} else {
await ModelApi.updateModelApi(data)
message.success(t('common.updateSuccess'))
}
//
dialogVisible.value = false
await getList()
} finally {
actionLoading.value = false
}
//
const handleDesign = (row) => {
console.log(row, '设计流程')
router.push({
name: 'modelEditor',
query: {
modelId: row.id
}
})
}
/** 流程表单的详情按钮操作 */
const handleChangeState = async (row: ModelVO) => {
//
const handleDefinitionList = (row) => {
router.push({
name: 'BpmProcessDefinitionList',
query: {
key: row.key
}
})
}
//
const formDetailVisible = ref(false)
const formDetailPreview = ref({
rule: [],
option: {}
})
const handleFormDetail = async (row) => {
if (row.formType == 10) {
//
const data = await FormApi.getFormApi(row.formId)
setConfAndFields2(formDetailPreview, data.conf, data.fields)
//
formDetailVisible.value = true
} else {
await router.push({
path: row.formCustomCreatePath
})
}
}
//
const handleBpmnDetail = (row) => {
// TODO
console.log(row)
ModelApi.getModelApi(row).then((response) => {
console.log(response, 'response')
bpmnXML.value = response.bpmnXml
//
showBpmnOpen.value = true
})
// message.success(' 2 ')
}
//
const handleAssignRule = (row) => {
router.push({
name: 'BpmTaskAssignRuleList',
query: {
modelId: row.id
}
})
}
// ========== / ==========
const dialogVisible = ref(false)
const dialogTitle = ref('新建模型')
const dialogLoading = ref(false)
const saveForm = ref()
const saveFormRef = ref<FormInstance>()
//
const setDialogTile = async (type: string) => {
dialogTitle.value = t('action.' + type)
dialogVisible.value = true
}
//
const handleCreate = async () => {
resetForm()
await setDialogTile('create')
}
//
const handleUpdate = async (rowId: number) => {
resetForm()
await setDialogTile('edit')
//
saveForm.value = await ModelApi.getModelApi(rowId)
}
//
const submitForm = async () => {
//
const elForm = unref(saveFormRef)
if (!elForm) return
const valid = await elForm.validate()
if (!valid) return
//
dialogLoading.value = true
try {
const data = saveForm.value as ModelApi.ModelVO
if (!data.id) {
await ModelApi.createModelApi(data)
message.success(t('common.createSuccess'))
} else {
await ModelApi.updateModelApi(data)
message.success(t('common.updateSuccess'))
}
dialogVisible.value = false
} finally {
//
await reload()
dialogLoading.value = false
}
}
//
const resetForm = () => {
saveForm.value = {
formType: 10,
name: '',
courseSort: '',
description: '',
formId: '',
formCustomCreatePath: '',
formCustomViewPath: ''
}
saveFormRef.value?.resetFields()
}
// ========== / / ==========
//
const handleDelete = (rowId) => {
message.delConfirm('是否删除该流程!!').then(async () => {
await ModelApi.deleteModelApi(rowId)
message.success(t('common.delSuccess'))
//
reload()
})
}
//
const handleChangeState = (row) => {
const id = row.id
const state = row.processDefinition.suspensionState
const statusState = state === 1 ? '激活' : '挂起'
const content = '是否确认' + statusState + '流程名字为"' + row.name + '"的数据项?'
message
.confirm(
'是否确认' + statusState + '流程名字为"' + row.name + '"的数据项?',
t('common.reminder')
)
.confirm(content)
.then(async () => {
ModelApi.updateModelStateApi(row.id, state).then(() => {
message.success(t('common.updateSuccess'))
getList()
})
await ModelApi.updateModelStateApi(id, state)
message.success(t('部署成功'))
//
reload()
})
.catch(() => {
//
row.processDefinition.suspensionState = state === 1 ? 2 : 1
})
.catch(() => {})
}
// ========== ==========
const detailData = ref() // Ref
//
const handleDetail = async (row: ModelVO) => {
//
detailData.value = row
setDialogTile('detail')
//
const handleDeploy = (row) => {
message.confirm('是否部署该流程!!').then(async () => {
await ModelApi.deployModelApi(row.id)
message.success(t('部署成功'))
//
reload()
})
}
// ========== ==========
const uploadRef = ref<UploadInstance>()
let importUrl = import.meta.env.VITE_BASE_URL + import.meta.env.VITE_API_URL + '/bpm/model/import'
const uploadHeaders = ref()
const importDialogVisible = ref(false)
const uploadDisabled = ref(false)
const importFormRef = ref<FormInstance>()
const importForm = ref({
key: '',
name: '',
description: ''
})
//
const handleImport = () => {
importDialogVisible.value = true
}
//
const handleExceed = (): void => {
message.error('最多只能上传一个文件!')
}
//
const excelUploadError = (): void => {
message.error('导入流程失败,请您重新上传!')
}
//
const submitFileForm = () => {
uploadHeaders.value = {
Authorization: 'Bearer ' + getAccessToken(),
'tenant-id': getTenantId()
}
uploadDisabled.value = true
uploadRef.value!.submit()
}
//
const handleFileSuccess = async (response: any): Promise<void> => {
if (response.code !== 0) {
message.error(response.msg)
return
}
//
uploadClose()
//
message.success('导入流程成功!请点击【设计流程】按钮,进行编辑保存后,才可以进行【发布流程】')
await reload()
}
//
const uploadClose = () => {
//
importDialogVisible.value = false
//
uploadDisabled.value = false
uploadRef.value!.clearFiles()
//
importForm.value = {
key: '',
name: '',
description: ''
}
importFormRef.value?.resetFields()
}
// ========== ==========
getList()
onMounted(() => {
//
FormApi.getSimpleFormsApi().then((data) => {
forms.value = data
})
})
</script>
<template>
<!-- 搜索工作区 -->
<ContentWrap>
<Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />
</ContentWrap>
<ContentWrap>
<!-- 操作工具栏 -->
<div class="mb-10px">
<el-button type="primary" v-hasPermi="['bpm:model:create']" @click="handleCreate()">
<Icon icon="ep:zoom-in" class="mr-5px" /> {{ t('action.add') }}
</el-button>
</div>
<!-- 列表 -->
<Table
:columns="allSchemas.tableColumns"
:selection="false"
:data="tableObject.tableList"
:loading="tableObject.loading"
:pagination="{
total: tableObject.total
}"
v-model:pageSize="tableObject.pageSize"
v-model:currentPage="tableObject.currentPage"
@register="register"
>
<template #category="{ row }">
<DictTag :type="DICT_TYPE.BPM_MODEL_CATEGORY" :value="row.category" />
</template>
<template #formId="{ row }">
<span>{{ row.formName }}</span>
</template>
<template #processDefinition>
<el-table-column label="流程版本" prop="processDefinition.version">
<template #default="{ row }">
<el-tag v-if="row.processDefinition">
{{ 'v' + row.processDefinition.version }}
</el-tag>
<el-tag type="warning" v-else>未部署</el-tag>
</template>
</el-table-column>
<el-table-column label="激活状态" prop="processDefinition.suspensionState">
<template #default="{ row }">
<el-switch
v-if="row.processDefinition"
v-model="row.processDefinition.suspensionState"
:active-value="1"
:inactive-value="2"
@change="handleChangeState(row)"
/>
</template>
</el-table-column>
<el-table-column label="部署时间" prop="processDefinition.deploymentTime">
<template #default="{ row }">
<span>
{{ dayjs(row.processDefinition.deploymentTime).format('YYYY-MM-DD HH:mm:ss') }}
</span>
</template>
</el-table-column>
</template>
<template #createTime="{ row }">
<span>{{ dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss') }}</span>
</template>
<template #action="{ row }">
<el-button link type="primary" v-hasPermi="['bpm:model:update']" @click="handleUpdate(row)">
<Icon icon="ep:edit" class="mr-1px" /> {{ t('action.edit') }}
</el-button>
<el-button link type="primary" v-hasPermi="['bpm:model:update']" @click="handleDetail(row)">
<Icon icon="ep:view" class="mr-1px" /> {{ t('action.detail') }}
</el-button>
<el-button
link
type="primary"
v-hasPermi="['bpm:model:delete']"
@click="delList(row.id, false)"
>
<Icon icon="ep:delete" class="mr-1px" /> {{ t('action.del') }}
</el-button>
</template>
</Table>
</ContentWrap>
<XModal v-model="dialogVisible" :title="dialogTitle">
<!-- 对话框(添加 / 修改) -->
<Form
v-if="['create', 'update'].includes(actionType)"
:schema="allSchemas.formSchema"
:rules="rules"
ref="formRef"
/>
<!-- 对话框(详情) -->
<Descriptions
v-if="actionType === 'detail'"
:schema="allSchemas.detailSchema"
:data="detailData"
/>
<!-- 操作按钮 -->
<template #footer>
<!-- 按钮保存 -->
<XButton
v-if="['create', 'update'].includes(actionType)"
type="primary"
:title="t('action.save')"
:loading="actionLoading"
@click="submitForm()"
/>
<!-- 按钮关闭 -->
<XButton :loading="actionLoading" :title="t('dialog.close')" @click="dialogVisible = false" />
</template>
</XModal>
</template>

View File

@ -1,78 +1,105 @@
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { reactive } from 'vue'
import { useI18n } from '@/hooks/web/useI18n'
import { required } from '@/utils/formRules'
import { VxeCrudSchema, useVxeCrudSchemas } from '@/hooks/web/useVxeCrudSchemas'
import { DICT_TYPE } from '@/utils/dict'
const { t } = useI18n() // 国际化
// 表单校验
export const rules = reactive({
name: [required]
key: [required],
name: [required],
category: [required],
formType: [required],
formId: [required],
formCustomCreatePath: [required],
formCustomViewPath: [required]
})
// CrudSchema
const crudSchemas = reactive<CrudSchema[]>([
{
label: t('common.index'),
field: 'id',
type: 'index',
form: {
show: false
const crudSchemas = reactive<VxeCrudSchema>({
primaryKey: 'key',
primaryType: null,
action: true,
actionWidth: '540px',
columns: [
{
title: '流程标识',
field: 'key',
isSearch: true,
table: {
width: 120
}
},
detail: {
show: false
}
},
{
label: '流程标识',
field: 'key',
search: {
show: true
}
},
{
label: '流程名称',
field: 'name',
search: {
show: true
}
},
{
label: '流程分类',
field: 'category',
dictType: DICT_TYPE.BPM_MODEL_CATEGORY,
dictClass: 'number',
search: {
show: true
}
},
{
label: '表单信息',
field: 'formId'
},
{
label: '最新部署的流程定义',
field: 'processDefinition',
form: {
show: false
{
title: '流程名称',
field: 'name',
isSearch: true,
table: {
width: 120,
slots: {
default: 'name_default'
}
}
},
detail: {
show: false
}
},
{
label: t('common.createTime'),
field: 'createTime',
form: {
show: false
}
},
{
label: t('table.action'),
field: 'action',
width: '240px',
form: {
show: false
{
title: '流程分类',
field: 'category',
dictType: DICT_TYPE.BPM_MODEL_CATEGORY,
dictClass: 'number',
isSearch: true
},
detail: {
show: false
{
title: '表单信息',
field: 'formId',
table: {
width: 180,
slots: {
default: 'formId_default'
}
}
},
{
title: '最新部署的流程定义',
field: 'processDefinition',
isForm: false,
table: {
children: [
{
title: '流程版本',
field: 'version',
slots: {
default: 'version_default'
},
width: 80
},
{
title: '激活状态',
field: 'status',
slots: {
default: 'status_default'
},
width: 80
},
{
title: '部署时间',
field: 'processDefinition.deploymentTime',
formatter: 'formatDate',
width: 180
}
]
}
},
{
title: t('common.createTime'),
field: 'createTime',
isForm: false,
formatter: 'formatDate',
table: {
width: 180
}
}
}
])
export const { allSchemas } = useCrudSchemas(crudSchemas)
]
})
export const { allSchemas } = useVxeCrudSchemas(crudSchemas)

View File

@ -0,0 +1,210 @@
<template>
<div class="app-container">
<!-- 流程设计器负责绘制流程等 -->
<!-- <myProcessDesigner -->
<my-process-designer
:key="`designer-${reloadIndex}`"
v-if="xmlString !== undefined"
v-model="xmlString"
:value="xmlString"
v-bind="controlForm"
keyboard
ref="processDesigner"
@init-finished="initModeler"
:additionalModel="controlForm.additionalModel"
@save="save"
/>
<!-- 流程属性器负责编辑每个流程节点的属性 -->
<!-- <MyProcessPalette -->
<my-properties-panel
:key="`penal-${reloadIndex}`"
:bpmnModeler="modeler"
:prefix="controlForm.prefix"
class="process-panel"
:model="model"
/>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
// import { translations } from '@/components/bpmnProcessDesigner/src/translations'
//
import CustomContentPadProvider from '@/components/bpmnProcessDesigner/package/designer/plugins/content-pad'
//
import CustomPaletteProvider from '@/components/bpmnProcessDesigner/package/designer/plugins/palette'
// import xmlObj2json from "./utils/xml2json";
// import myProcessDesigner from '@/components/bpmnProcessDesigner/package/designer/ProcessDesigner.vue'
// import MyProcessPalette from '@/components/bpmnProcessDesigner/package/palette/ProcessPalette.vue'
import { createModelApi, getModelApi, updateModelApi } from '@/api/bpm/model'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
const router = useRouter()
//
// import MyProcessPanel from "../package/process-panel/ProcessPanel";
const xmlString = ref(undefined) // BPMN XML
const modeler = ref(null)
const reloadIndex = ref(0)
// const controlDrawerVisible = ref(false)
// const translationsSelf = translations
const controlForm = ref({
simulation: true,
labelEditing: false,
labelVisible: false,
prefix: 'flowable',
headerButtonSize: 'mini',
additionalModel: [CustomContentPadProvider, CustomPaletteProvider]
})
// const addis = ref({
// CustomContentPadProvider,
// CustomPaletteProvider
// })
//
const model = ref({})
onMounted(() => {
// modelId
const modelId = router.currentRoute.value.query && router.currentRoute.value.query.modelId
console.log(modelId, 'modelId')
if (modelId) {
// let data = '4b4909d8-97e7-11ec-8e20-862bc1a4a054'
getModelApi(modelId).then((data) => {
console.log(data, 'response')
xmlString.value = data.bpmnXml
model.value = {
...data,
bpmnXml: undefined // bpmnXml
}
// this.controlForm.processId = data.key
// xmlString.value =
// '<?xml version="1.0" encoding="UTF-8"?>\n<bpmn2:definitions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:bpmn2="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" id="diagram_Process_1645980650311" targetNamespace="http://activiti.org/bpmn"><bpmn2:process id="flowable_01" name="flowable" isExecutable="true"><bpmn2:startEvent id="Event_1iruxim"><bpmn2:outgoing>Flow_0804gmo</bpmn2:outgoing></bpmn2:startEvent><bpmn2:userTask id="task01" name="task01"><bpmn2:incoming>Flow_0804gmo</bpmn2:incoming><bpmn2:outgoing>Flow_0cx479x</bpmn2:outgoing></bpmn2:userTask><bpmn2:sequenceFlow id="Flow_0804gmo" sourceRef="Event_1iruxim" targetRef="task01" /><bpmn2:endEvent id="Event_1mdsccz"><bpmn2:incoming>Flow_0cx479x</bpmn2:incoming></bpmn2:endEvent><bpmn2:sequenceFlow id="Flow_0cx479x" sourceRef="task01" targetRef="Event_1mdsccz" /></bpmn2:process><bpmndi:BPMNDiagram id="BPMNDiagram_1"><bpmndi:BPMNPlane id="flowable_01_di" bpmnElement="flowable_01"><bpmndi:BPMNEdge id="Flow_0cx479x_di" bpmnElement="Flow_0cx479x"><di:waypoint x="440" y="350" /><di:waypoint x="492" y="350" /></bpmndi:BPMNEdge><bpmndi:BPMNEdge id="Flow_0804gmo_di" bpmnElement="Flow_0804gmo"><di:waypoint x="288" y="350" /><di:waypoint x="340" y="350" /></bpmndi:BPMNEdge><bpmndi:BPMNShape id="Event_1iruxim_di" bpmnElement="Event_1iruxim"><dc:Bounds x="252" y="332" width="36" height="36" /></bpmndi:BPMNShape><bpmndi:BPMNShape id="task01_di" bpmnElement="task01"><dc:Bounds x="340" y="310" width="100" height="80" /></bpmndi:BPMNShape><bpmndi:BPMNShape id="Event_1mdsccz_di" bpmnElement="Event_1mdsccz"><dc:Bounds x="492" y="332" width="36" height="36" /></bpmndi:BPMNShape></bpmndi:BPMNPlane></bpmndi:BPMNDiagram></bpmn2:definitions>'
// model.value = {
// key: 'flowable_01',
// name: 'flowable',
// description: 'ooxx',
// category: '1',
// formType: 10,
// formId: 11,
// formCustomCreatePath: null,
// formCustomViewPath: null,
// id: '4b4909d8-97e7-11ec-8e20-862bc1a4a054',
// createTime: 1645978019795,
// bpmnXml: undefined // bpmnXml
// }
// console.log(modeler.value, 'modeler11111111')
})
}
})
const initModeler = (item) => {
setTimeout(() => {
modeler.value = item
console.log(item, 'initModeler方法modeler')
console.log(modeler.value, 'initModeler方法modeler')
// controlForm.value.prefix = '2222'
}, 10)
}
const save = (bpmnXml) => {
const data = {
...model.value,
bpmnXml: bpmnXml // this.bpmnXml
}
console.log(data, 'data')
//
if (data.id) {
updateModelApi(data).then((response) => {
console.log(response, 'response')
// this.$modal.msgSuccess("")
ElMessage.success('修改成功')
//
close()
})
return
}
//
createModelApi(data).then((response) => {
console.log(response, 'response1')
// this.$modal.msgSuccess("")
ElMessage.success('保存成功')
//
close()
})
}
/** 关闭按钮 */
const close = () => {
// this.$tab.closeOpenPage({ path: "/bpm/manager/model" })
router.push({ path: '/bpm/manager/model' })
}
</script>
<style lang="scss">
//body {
// overflow: hidden;
// margin: 0;
// box-sizing: border-box;
//}
//.app {
// width: 100%;
// height: 100%;
// box-sizing: border-box;
// display: inline-grid;
// grid-template-columns: 100px auto max-content;
//}
.demo-control-bar {
position: fixed;
right: 8px;
bottom: 8px;
z-index: 1;
.open-control-dialog {
width: 48px;
height: 48px;
display: flex;
align-items: center;
justify-content: center;
border-radius: 4px;
font-size: 32px;
background: rgba(64, 158, 255, 1);
color: #ffffff;
cursor: pointer;
}
}
// TODO faq
//.info-tip {
// position: fixed;
// top: 40px;
// right: 500px;
// z-index: 10;
// color: #999999;
//}
.control-form {
.el-radio {
width: 100%;
line-height: 32px;
}
}
.element-overlays {
box-sizing: border-box;
padding: 8px;
background: rgba(0, 0, 0, 0.6);
border-radius: 4px;
color: #fafafa;
}
.my-process-designer {
height: calc(100vh - 84px);
}
.process-panel__container {
position: absolute;
right: 0;
top: 55px;
height: calc(100vh - 84px);
}
</style>

View File

@ -1,4 +0,0 @@
<template>
<div>index</div>
</template>
<script setup lang="ts" name="Oa"></script>

View File

@ -0,0 +1,58 @@
<template>
<ContentWrap>
<!-- 对话框(添加 / 修改) -->
<Form :schema="allSchemas.formSchema" :rules="rules" ref="formRef" />
<!-- 按钮保存 -->
<XButton
type="primary"
:title="t('action.save')"
:loading="actionLoading"
@click="submitForm"
/>
</ContentWrap>
</template>
<script setup lang="ts">
import { FormExpose } from '@/components/Form'
// import XEUtils from 'xe-utils'
// import
import * as LeaveApi from '@/api/bpm/leave'
import { rules, allSchemas } from './leave.data'
const { t } = useI18n() //
const message = useMessage() //
const router = useRouter() //
//
const actionLoading = ref(false) // Loading
const formRef = ref<FormExpose>() // Ref
//
const submitForm = async () => {
const elForm = unref(formRef)?.getElFormRef()
if (!elForm) return
elForm.validate(async (valid) => {
if (!valid) {
return
}
try {
//
actionLoading.value = true
const data = unref(formRef)?.formModel as LeaveApi.LeaveVO
// data.startTime = XEUtils.toDateString(data.startTime, 'yyyy-MM-dd HH:mm:ss')
// data.endTime = XEUtils.toDateString(data.endTime, 'yyyy-MM-dd HH:mm:ss')
data.startTime = Date.parse(new Date(data.startTime).toString())
data.endTime = Date.parse(new Date(data.endTime).toString())
//
await LeaveApi.createLeaveApi(data)
message.success(t('common.createSuccess'))
//
router.push({
path: '/bpm/oa/leave'
})
} finally {
actionLoading.value = false
}
})
}
</script>

View File

@ -0,0 +1,36 @@
<template>
<ContentWrap>
<!-- 详情 -->
<Descriptions :schema="allSchemas.detailSchema" :data="formData" />
</ContentWrap>
</template>
<script lang="ts" setup>
// import
import * as LeaveApi from '@/api/bpm/leave'
import { allSchemas } from '@/views/bpm/oa/leave/leave.data'
const { query } = useRoute() //
const message = useMessage() //
const id = ref() //
//
const formData = ref({
startTime: undefined,
endTime: undefined,
type: undefined,
reason: undefined
})
onMounted(() => {
id.value = query.id
if (!id.value) {
message.error('未传递 id 参数,无法查看 OA 请假信息')
return
}
//
LeaveApi.getLeaveApi(id.value).then((data) => {
formData.value = data
})
})
</script>

View File

@ -0,0 +1,83 @@
<template>
<ContentWrap>
<XTable @register="registerTable">
<template #toolbar_buttons>
<!-- 操作发起请假 -->
<XButton type="primary" preIcon="ep:plus" title="发起请假" @click="handleCreate()" />
</template>
<template #actionbtns_default="{ row }">
<!-- 操作: 取消请假 -->
<XTextButton
preIcon="ep:delete"
title="取消请假"
v-hasPermi="['bpm:oa-leave:create']"
v-if="row.result === 1"
@click="cancelLeave(row)"
/>
<!-- 操作: 详情 -->
<XTextButton preIcon="ep:view" :title="t('action.detail')" @click="handleDetail(row)" />
<!-- 操作: 审批进度 -->
<XTextButton preIcon="ep:edit-pen" title="审批进度" @click="handleProcessDetail(row)" />
</template>
</XTable>
</ContentWrap>
</template>
<script setup lang="ts">
// import
import { ElMessageBox } from 'element-plus'
// import
import { allSchemas } from './leave.data'
import * as LeaveApi from '@/api/bpm/leave'
import * as ProcessInstanceApi from '@/api/bpm/processInstance'
const { t } = useI18n() //
const message = useMessage() //
const router = useRouter() //
const [registerTable, { reload }] = useXTable({
allSchemas: allSchemas,
getListApi: LeaveApi.getLeavePageApi
})
//
const handleCreate = () => {
router.push({
name: 'OALeaveCreate'
})
}
//
const cancelLeave = (row) => {
ElMessageBox.prompt('请输入取消原因', '取消流程', {
confirmButtonText: t('common.ok'),
cancelButtonText: t('common.cancel'),
inputPattern: /^[\s\S]*.*\S[\s\S]*$/, //
inputErrorMessage: '取消原因不能为空'
}).then(async ({ value }) => {
await ProcessInstanceApi.cancelProcessInstanceApi(row.id, value)
message.success('取消成功')
reload()
})
}
//
const handleDetail = (row) => {
router.push({
name: 'OALeaveDetail',
query: {
id: row.id
}
})
}
//
const handleProcessDetail = (row) => {
router.push({
name: 'BpmProcessInstanceDetail',
query: {
id: row.processInstanceId
}
})
}
</script>

View File

@ -0,0 +1,90 @@
import { VxeCrudSchema, useVxeCrudSchemas } from '@/hooks/web/useVxeCrudSchemas'
const { t } = useI18n() // 国际化
// 表单校验
export const rules = reactive({
startTime: [{ required: true, message: '开始时间不能为空', trigger: 'blur' }],
endTime: [{ required: true, message: '结束时间不能为空', trigger: 'blur' }],
type: [{ required: true, message: '请假类型不能为空', trigger: 'change' }]
})
// crudSchemas
const crudSchemas = reactive<VxeCrudSchema>({
primaryKey: 'id',
primaryType: 'id',
primaryTitle: '申请编号',
action: true,
actionWidth: '260',
columns: [
{
title: t('common.status'),
field: 'result',
dictType: DICT_TYPE.BPM_PROCESS_INSTANCE_RESULT,
dictClass: 'number',
isSearch: true,
isForm: false
},
{
title: t('common.startTimeText'),
field: 'startTime',
formatter: 'formatDay',
table: {
width: 180
},
detail: {
dateFormat: 'YYYY-MM-DD'
},
form: {
component: 'DatePicker'
}
},
{
title: t('common.endTimeText'),
field: 'endTime',
formatter: 'formatDay',
table: {
width: 180
},
detail: {
dateFormat: 'YYYY-MM-DD'
},
form: {
component: 'DatePicker'
}
},
{
title: '请假类型',
field: 'type',
dictType: DICT_TYPE.BPM_OA_LEAVE_TYPE,
dictClass: 'number',
isSearch: true
},
{
title: '原因',
field: 'reason',
isSearch: true,
componentProps: {
type: 'textarea',
rows: 4
}
},
{
title: '申请时间',
field: 'createTime',
formatter: 'formatDate',
table: {
width: 180
},
isSearch: true,
search: {
show: true,
itemRender: {
name: 'XDataTimePicker'
}
},
isForm: false
}
]
})
export const { allSchemas } = useVxeCrudSchemas(crudSchemas)

Some files were not shown because too many files have changed in this diff Show More