From 4a682c69638659fea84ca808444861025c92bd90 Mon Sep 17 00:00:00 2001 From: chenchuchuan <13554600537@163.com> Date: Wed, 14 Oct 2026 16:41:07 +0800 Subject: [PATCH 1/4] =?UTF-8?q?feat(openapi):=20=E9=85=8D=E7=BD=AE=20OpenA?= =?UTF-8?q?PI=20=E8=B7=AF=E7=94=B1=E9=89=B4=E6=9D=83=E6=8B=A6=E6=88=AA?= =?UTF-8?q?=E5=99=A8=E4=BD=93=E7=B3=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 在 InterceptorConfig 中注册 OpenApiAuthInterceptor 处理 OpenAPI 路由鉴权 - 将 OpenAPI 路径从 AuthenticationInterceptor 中排除,避免误拦截 - 通过 ObjectProvider 条件注册拦截器,支持 operationEnabled 开关 - 为 pageFormTree、files、download 接口添加 @NoAuthInterface 注解 --- .../tenantadmin/config/InterceptorConfig.java | 25 +++++++++++++++++++++- .../openapi/controller/OpenApiKbController.java | 3 +++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/application-tenant/tenant-admin/src/main/java/apelet/tenantadmin/config/InterceptorConfig.java b/application-tenant/tenant-admin/src/main/java/apelet/tenantadmin/config/InterceptorConfig.java index bf73b41..248604b 100644 --- a/application-tenant/tenant-admin/src/main/java/apelet/tenantadmin/config/InterceptorConfig.java +++ b/application-tenant/tenant-admin/src/main/java/apelet/tenantadmin/config/InterceptorConfig.java @@ -1,6 +1,10 @@ package apelet.tenantadmin.config; +import apelet.common.openapi.config.OpenApiProperties; +import apelet.common.openapi.interceptor.OpenApiAuthInterceptor; import apelet.tenantadmin.interceptor.AuthenticationInterceptor; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @@ -14,8 +18,27 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class InterceptorConfig implements WebMvcConfigurer { + @Autowired + private ObjectProvider openApiAuthInterceptorProvider; + @Autowired + private OpenApiProperties openApiProperties; + @Override public void addInterceptors(InterceptorRegistry registry) { - registry.addInterceptor(new AuthenticationInterceptor()).addPathPatterns("/tenantadmin/**").addPathPatterns("/botp/**"); + String openApiPrefix = openApiProperties.getUrlPrefix(); + registry.addInterceptor(new AuthenticationInterceptor()) + .addPathPatterns("/tenantadmin/**").addPathPatterns("/botp/**") + // OpenAPI 对外开放部分不依赖应用登录态:{prefix}/v1/** 由 OpenApiAuthInterceptor 校验 accessToken, + // {prefix}/auth/token 是公开的签发接口。这里一并排除,避免调用方误带 Authorization 头时 + // 被登录态拦截器抢先拦下(它注册在前,会先执行)。 + .excludePathPatterns(openApiPrefix + "/v1/**") + .excludePathPatterns(openApiPrefix + "/auth/**"); + // OpenAPI 对外开放路由鉴权({prefix}/v1/**):校验 accessToken 并把 TokenData 注入请求上下文。 + // 注意 HandlerInterceptor 即使标了 @Component 也不会被 Spring Boot 自动注册,必须在这里显式挂上; + // common-openapi.operationEnabled=false 时该 bean 不存在,getIfAvailable() 返回 null,跳过注册即可。 + OpenApiAuthInterceptor openApiAuthInterceptor = openApiAuthInterceptorProvider.getIfAvailable(); + if (openApiAuthInterceptor != null) { + registry.addInterceptor(openApiAuthInterceptor).addPathPatterns(openApiPrefix + "/v1/**"); + } } } diff --git a/common/common-openapi/src/main/java/apelet/common/openapi/controller/OpenApiKbController.java b/common/common-openapi/src/main/java/apelet/common/openapi/controller/OpenApiKbController.java index 1f6d6b4..fad705e 100644 --- a/common/common-openapi/src/main/java/apelet/common/openapi/controller/OpenApiKbController.java +++ b/common/common-openapi/src/main/java/apelet/common/openapi/controller/OpenApiKbController.java @@ -45,6 +45,7 @@ public class OpenApiKbController { * @return 页面节点列表。 */ @PostMapping("/pageFormTree") + @NoAuthInterface public ResponseResult> pageFormTree(@RequestBody(required = false) OpenApiKbTreeQueryDto queryDto) { if (queryDto == null) { queryDto = new OpenApiKbTreeQueryDto(); @@ -61,6 +62,7 @@ public class OpenApiKbController { * @return data 为分页对象(list/pageNo/pageSize/total/hasMore)。 */ @PostMapping("/files") + @NoAuthInterface public ResponseResult files(@RequestBody(required = false) OpenApiKbFileQueryDto queryDto) { if (queryDto == null) { return ResponseResult.error(ErrorCodeEnum.ARGUMENT_NULL_EXIST, "请求体不能为空!"); @@ -79,6 +81,7 @@ public class OpenApiKbController { * @throws IOException 写出应答时发生错误。 */ @GetMapping("/download") + @NoAuthInterface public void download(@RequestParam(required = false) Long formId, @RequestParam(required = false) String dataId, @RequestParam(required = false) String fieldName, -- 2.9.0.windows.1 From 9d968d549f7dc39edfd89412577f2624513ad5fe Mon Sep 17 00:00:00 2001 From: chenchuchuan <13554600537@163.com> Date: Thu, 15 Oct 2026 11:18:27 +0800 Subject: [PATCH 2/4] =?UTF-8?q?feat(flow):=20=E6=96=B0=E5=A2=9E=E4=BB=BB?= =?UTF-8?q?=E5=8A=A1=E6=A0=87=E9=A2=98=E5=85=B3=E9=94=AE=E5=AD=97=E8=BF=87?= =?UTF-8?q?=E6=BB=A4=E5=B9=B6=E9=87=8D=E6=9E=84=E6=A0=87=E9=A2=98=E5=AD=98?= =?UTF-8?q?=E5=82=A8=E8=87=B3=E8=8A=82=E7=82=B9=E6=89=A9=E5=B1=95=E8=A1=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 将标题存储从 zz_flow_work_order_ext.title_json 迁移至独立表 zz_flow_task_instance_ext - getTaskListByUserName 新增 title 参数,待办列表支持按标题模糊过滤(Java 侧过滤) - getHistoricProcessInstanceList 新增 title 参数,走 Flowable 原生 join 查询实现首节点标题过滤 - getHistoricTaskInstanceFinishedList 新增 title 参数,走原生 join 查询实现已办任务标题过滤 - resolveTitleCached 简化签名,仅读取落库值,移除按模板实时解析的兜底逻辑 - buildAndSaveTaskTitle 首节点补写改为取定义的起始节点而非当前活动任务,修复 autoskip 场景 - 删除流程实例时级联清理 zz_flow_task_instance_ext 中的标题行 - 新增 escapeLikeKeyword 转义 LIKE 通配符,防止用户输入注入 - 新增 TitleFilterContext 内部类封装标题过滤的懒加载与缓存逻辑 --- .../flow/controller/FlowOperationController.java | 94 ++++-- .../common/flow/dao/FlowTaskInstanceExtMapper.java | 22 ++ .../flow/dao/mapper/FlowTaskInstanceExtMapper.xml | 31 ++ .../common/flow/listener/FlowUserTaskListener.java | 8 +- .../common/flow/model/FlowTaskInstanceExt.java | 86 +++++ .../apelet/common/flow/model/FlowWorkOrderExt.java | 8 - .../apelet/common/flow/service/FlowApiService.java | 43 +-- .../flow/service/FlowTaskInstanceExtService.java | 43 +++ .../flow/service/FlowTaskTitleBackfillService.java | 25 ++ .../common/flow/service/FlowWorkOrderService.java | 14 +- .../flow/service/impl/FlowApiServiceImpl.java | 371 ++++++++++++++++++--- .../impl/FlowTaskInstanceExtServiceImpl.java | 139 ++++++++ .../impl/FlowTaskTitleBackfillServiceImpl.java | 212 ++++++++++++ .../service/impl/FlowWorkOrderServiceImpl.java | 40 +-- .../common/flow/vo/FlowTaskTitleBackfillVo.java | 75 +++++ 15 files changed, 1078 insertions(+), 133 deletions(-) create mode 100644 common/common-flow/src/main/java/apelet/common/flow/dao/FlowTaskInstanceExtMapper.java create mode 100644 common/common-flow/src/main/java/apelet/common/flow/dao/mapper/FlowTaskInstanceExtMapper.xml create mode 100644 common/common-flow/src/main/java/apelet/common/flow/model/FlowTaskInstanceExt.java create mode 100644 common/common-flow/src/main/java/apelet/common/flow/service/FlowTaskInstanceExtService.java create mode 100644 common/common-flow/src/main/java/apelet/common/flow/service/FlowTaskTitleBackfillService.java create mode 100644 common/common-flow/src/main/java/apelet/common/flow/service/impl/FlowTaskInstanceExtServiceImpl.java create mode 100644 common/common-flow/src/main/java/apelet/common/flow/service/impl/FlowTaskTitleBackfillServiceImpl.java create mode 100644 common/common-flow/src/main/java/apelet/common/flow/vo/FlowTaskTitleBackfillVo.java diff --git a/common/common-flow/src/main/java/apelet/common/flow/controller/FlowOperationController.java b/common/common-flow/src/main/java/apelet/common/flow/controller/FlowOperationController.java index 43d5582..4b39b89 100644 --- a/common/common-flow/src/main/java/apelet/common/flow/controller/FlowOperationController.java +++ b/common/common-flow/src/main/java/apelet/common/flow/controller/FlowOperationController.java @@ -2,6 +2,7 @@ package apelet.common.flow.controller; import apelet.common.core.annotation.DisableDataFilter; import apelet.common.core.annotation.MyRequestBody; +import apelet.common.core.annotation.NoAuthInterface; import apelet.common.core.constant.ErrorCodeEnum; import apelet.common.core.object.*; import apelet.common.core.util.MyPageUtil; @@ -16,10 +17,7 @@ import apelet.common.flow.object.FlowEntryExtensionData; import apelet.common.flow.service.*; import apelet.common.flow.util.FlowCustomExtFactory; import apelet.common.flow.util.FlowOperationHelper; -import apelet.common.flow.vo.FlowTaskCommentVo; -import apelet.common.flow.vo.FlowTaskVo; -import apelet.common.flow.vo.FlowUserInfoVo; -import apelet.common.flow.vo.TaskInfoVo; +import apelet.common.flow.vo.*; import apelet.common.log.annotation.OperationLog; import apelet.common.log.model.constant.SysOperationLogType; import cn.hutool.core.bean.BeanUtil; @@ -79,6 +77,10 @@ public class FlowOperationController { @Autowired private FlowWorkOrderService flowWorkOrderService; @Autowired + private FlowTaskInstanceExtService flowTaskInstanceExtService; + @Autowired + private FlowTaskTitleBackfillService flowTaskTitleBackfillService; + @Autowired private FlowMessageService flowMessageService; @Autowired private FlowOperationHelper flowOperationHelper; @@ -218,10 +220,12 @@ public class FlowOperationController { taskInfoVo.setVariableList(JSON.parseArray(flowTaskExt.getVariableListJson(), JSONObject.class)); } FlowWorkOrder workOrder = flowWorkOrderService.getFlowWorkOrderByProcessInstanceId(processInstanceId); - FlowEntry flowEntry = workOrder == null ? new FlowEntry() : flowEntryService.getFlowEntryFromCache(workOrder.getProcessDefinitionKey()); - // 单条详情:直接单查一次扩展对象即可,无 N+1 风险。 - FlowWorkOrderExt workOrderExt = workOrder == null ? null : flowWorkOrderService.getFlowWorkOrderExtByWorkOrderId(workOrder.getWorkOrderId()); - taskInfoVo.setTitle(flowApiService.resolveTitleCached(flowTaskExt.getTitleTemplate(), processInstanceId, workOrder, flowEntry, taskInfoVo.getTaskKey(), workOrderExt)); + // 单条详情:只查一次节点扩展(复用批量接口传单元素集合),无 N+1 风险。 + String taskKey = taskInfoVo.getTaskKey(); + FlowTaskInstanceExt taskInstanceExt = workOrder == null || StrUtil.isBlank(taskKey) ? null + : flowTaskInstanceExtService.getMapByProcessInstanceIds(CollUtil.newHashSet(processInstanceId)) + .get(processInstanceId + ":" + taskKey); + taskInfoVo.setTitle(flowApiService.resolveTitleCached(workOrder, taskKey, taskInstanceExt)); } return ResponseResult.success(taskInfoVo); } @@ -540,6 +544,7 @@ public class FlowOperationController { * @param processDefinitionKey 流程标识。 * @param processDefinitionName 流程定义名 (模糊查询)。 * @param taskName 任务名称 (模糊查询)。 + * @param title 节点标题关键字,模糊匹配。 * @param pageParam 分页对象。 * @return 返回当前用户待办的任务列表。如果指定流程标识,则仅返回该流程的待办任务列表。 */ @@ -549,10 +554,11 @@ public class FlowOperationController { @MyRequestBody String processDefinitionKey, @MyRequestBody String processDefinitionName, @MyRequestBody String taskName, + @MyRequestBody String title, @MyRequestBody(required = true) MyPageParam pageParam) { String username = TokenData.takeFromRequest().getLoginName(); MyPageData pageData = flowApiService.getTaskListByUserName( - username, processDefinitionKey, processDefinitionName, taskName, pageParam); + username, processDefinitionKey, processDefinitionName, taskName, title, pageParam); List flowTaskVoList = flowApiService.convertToFlowTaskList(pageData.getDataList()); return ResponseResult.success(MyPageUtil.makeResponseData(flowTaskVoList, pageData.getTotalCount())); } @@ -811,6 +817,7 @@ public class FlowOperationController { * @param processDefinitionName 流程名。 * @param beginDate 流程发起开始时间。 * @param endDate 流程发起结束时间。 + * @param title 节点标题关键字,模糊匹配。 * @param pageParam 分页对象。 * @return 查询结果应答。 */ @@ -820,9 +827,10 @@ public class FlowOperationController { @MyRequestBody String processDefinitionName, @MyRequestBody String beginDate, @MyRequestBody String endDate, + @MyRequestBody String title, @MyRequestBody(required = true) MyPageParam pageParam) throws ParseException { MyPageData pageData = - flowApiService.getHistoricTaskInstanceFinishedList(processDefinitionName, beginDate, endDate, pageParam); + flowApiService.getHistoricTaskInstanceFinishedList(processDefinitionName, beginDate, endDate, title, pageParam); List> resultList = new LinkedList<>(); pageData.getDataList().forEach(instance -> resultList.add(BeanUtil.beanToMap(instance))); List taskInstanceList = pageData.getDataList(); @@ -842,11 +850,9 @@ public class FlowOperationController { flowWorkOrderService.getInList(INSTANCE_ID, instanceIdSet); Map workOrderMap = workOrderList.stream().collect(Collectors.toMap(FlowWorkOrder::getProcessInstanceId, c -> c)); - // 标题快照按工单批量预载(一次 IN 查询覆盖整页),避免逐行查扩展对象造成 N+1。 - Map workOrderExtMap = flowWorkOrderService - .getFlowWorkOrderExtByWorkOrderIds(workOrderList.stream() - .map(FlowWorkOrder::getWorkOrderId).filter(Objects::nonNull).collect(Collectors.toSet())) - .stream().collect(Collectors.toMap(FlowWorkOrderExt::getWorkOrderId, c -> c, (k1, k2) -> k1)); + // 节点标题按实例批量预载(一次 IN 查询覆盖整页),避免逐行查询造成 N+1。 + Map taskInstanceExtMap = + flowTaskInstanceExtService.getMapByProcessInstanceIds(instanceIdSet); Set processDefinitionIdSet = taskInstanceList.stream() .map(HistoricTaskInstance::getProcessDefinitionId).collect(Collectors.toSet()); List flowEntryPublishList = @@ -880,10 +886,9 @@ public class FlowOperationController { FlowEntry flowEntry = flowEntryMap.get(flowEntryPublish.getEntryId()); if (flowEntry != null) { Object taskDefinitionKey = result.get("taskDefinitionKey"); - result.put("title", flowApiService.resolveTitleCached( - flowTaskExt.getTitleTemplate(), instanceId, flowWorkOrder, flowEntry, - taskDefinitionKey == null ? null : taskDefinitionKey.toString(), - workOrderExtMap.get(flowWorkOrder.getWorkOrderId()))); + String taskKey = taskDefinitionKey == null ? null : taskDefinitionKey.toString(); + result.put("title", flowApiService.resolveTitleCached(flowWorkOrder, taskKey, + taskKey == null ? null : taskInstanceExtMap.get(instanceId + ":" + taskKey))); } } } @@ -910,6 +915,7 @@ public class FlowOperationController { * @param processDefinitionName 流程名。 * @param beginDate 流程发起开始时间。 * @param endDate 流程发起结束时间。 + * @param title 首节点标题关键字,模糊匹配。 * @param pageParam 分页对象。 * @return 查询结果应答。 */ @@ -919,10 +925,11 @@ public class FlowOperationController { @MyRequestBody String processDefinitionName, @MyRequestBody String beginDate, @MyRequestBody String endDate, + @MyRequestBody String title, @MyRequestBody(required = true) MyPageParam pageParam) throws ParseException { String loginName = TokenData.takeFromRequest().getLoginName(); MyPageData pageData = flowApiService.getHistoricProcessInstanceList( - null, processDefinitionName, loginName, beginDate, endDate, pageParam, true); + null, processDefinitionName, loginName, beginDate, endDate, title, pageParam, true); Set loginNameSet = pageData.getDataList().stream() .map(HistoricProcessInstance::getStartUserId).collect(Collectors.toSet()); List userInfoList = flowCustomExtFactory @@ -938,11 +945,8 @@ public class FlowOperationController { flowWorkOrderService.getInList(INSTANCE_ID, instanceIdSet); Map workOrderMap = workOrderList.stream().collect(Collectors.toMap(FlowWorkOrder::getProcessInstanceId, c -> c)); - // 标题快照按工单批量预载(一次 IN 查询覆盖整页),避免逐行查扩展对象造成 N+1。 - Map workOrderExtMap = flowWorkOrderService - .getFlowWorkOrderExtByWorkOrderIds(workOrderList.stream() - .map(FlowWorkOrder::getWorkOrderId).filter(Objects::nonNull).collect(Collectors.toSet())) - .stream().collect(Collectors.toMap(FlowWorkOrderExt::getWorkOrderId, c -> c, (k1, k2) -> k1)); + // 节点标题按实例批量预载(一次 IN 查询覆盖整页),避免逐行查询造成 N+1。 + Map taskInstanceExtMap = flowTaskInstanceExtService.getMapByProcessInstanceIds(instanceIdSet); Set processDefinitionIdSet = pageData.getDataList().stream() .map(HistoricProcessInstance::getProcessDefinitionId).collect(Collectors.toSet()); Map flowEntryPublishMap = new HashMap<>(); @@ -989,10 +993,10 @@ public class FlowOperationController { if (flowEntryPublish != null && flowTaskExt != null) { FlowEntry flowEntry = flowEntryMap.get(flowEntryPublish.getEntryId()); if (flowEntry != null) { - data.put("title", flowApiService.resolveTitleCached( - flowTaskExt.getTitleTemplate(), instance.getId(), workOrder, flowEntry, - initTaskKeyMap.get(instance.getProcessDefinitionId()), - workOrderExtMap.get(workOrder.getWorkOrderId()))); + // 流程实例列表使用起始节点的标题。 + String initTaskKey = initTaskKeyMap.get(instance.getProcessDefinitionId()); + data.put("title", flowApiService.resolveTitleCached(workOrder, initTaskKey, + initTaskKey == null ? null : taskInstanceExtMap.get(instance.getId() + ":" + initTaskKey))); } } } @@ -1019,7 +1023,8 @@ public class FlowOperationController { @MyRequestBody String endDate, @MyRequestBody(required = true) MyPageParam pageParam) throws ParseException { MyPageData pageData = flowApiService.getHistoricProcessInstanceList( - null, processDefinitionName, startUser, beginDate, endDate, pageParam, false); + // listAllHistoricProcessInstance 是管理端「所有历史流程」,本次不开放标题搜索,沿用原行为 + null, processDefinitionName, startUser, beginDate, endDate, null, pageParam, false); List> resultList = new LinkedList<>(); pageData.getDataList().forEach(instance -> resultList.add(BeanUtil.beanToMap(instance))); List unfinishedProcessInstanceIds = pageData.getDataList().stream() @@ -1309,4 +1314,33 @@ public class FlowOperationController { } return null; } + + /** + * 回填节点标题(运维接口)。 + *

改造前节点标题是查询时实时解析的、从不落库,所以存量流程实例没有标题数据。本接口按 + * 「流程实例 × 节点」重新解析一遍并落到 zz_flow_task_instance_ext。

+ *

免鉴权({@link NoAuthInterface}),方便直接在服务器上 curl。因此做了这些防护:

+ *
    + *
  • 幂等 —— 已有标题行的 (实例, 节点) 直接跳过,重复调用不会产生重复数据,也不会覆盖已生成的值;
  • + *
  • 只处理在线表单流程(路由表单本来没有标题),且只处理工单仍存在的实例;
  • + *
  • 单条失败只记数不中断,可反复重跑补齐;
  • + *
  • 按游标分批,避免一次请求跑太久。
  • + *
+ *

用法:先 dryRun=true 看体量,再去掉 dryRun 正式跑;返回的 finished 为 true 表示已跑完, + * 否则把 nextCursor 带上再调一次。

+ * + * @param cursorWorkOrderId 游标,取工单Id大于该值的记录;不传表示从头开始。 + * @param batchSize 单批工单数,默认 200,上限 2000。 + * @param dryRun 为 true 时只统计不写库。 + * @return 本批执行结果。 + */ + @NoAuthInterface + @PostMapping("/backfillTaskTitle") + public ResponseResult backfillTaskTitle( + @RequestParam(required = false) Long cursorWorkOrderId, + @RequestParam(required = false) Integer batchSize, + @RequestParam(required = false) Boolean dryRun) { + return ResponseResult.success( + flowTaskTitleBackfillService.backfill(cursorWorkOrderId, batchSize, dryRun)); + } } diff --git a/common/common-flow/src/main/java/apelet/common/flow/dao/FlowTaskInstanceExtMapper.java b/common/common-flow/src/main/java/apelet/common/flow/dao/FlowTaskInstanceExtMapper.java new file mode 100644 index 0000000..943db4e --- /dev/null +++ b/common/common-flow/src/main/java/apelet/common/flow/dao/FlowTaskInstanceExtMapper.java @@ -0,0 +1,22 @@ +package apelet.common.flow.dao; + +import apelet.common.core.base.dao.BaseDaoMapper; +import apelet.common.flow.model.FlowTaskInstanceExt; + +/** + * 流程节点扩展(实例级)数据操作访问接口。 + * + * @author chenchuchuan + * @date 2026-10-13 + */ +public interface FlowTaskInstanceExtMapper extends BaseDaoMapper { + + /** + * 按 (process_instance_id, task_key) 唯一键写入节点扩展,已存在则更新。 + *

用 ON DUPLICATE KEY UPDATE 而非「先查后写」,是为了让并发的多个任务创建落到同一条 SQL 上, + * 避免读-改-写之间互相覆盖,也天然保证同一节点只有一行。

+ * + * @param flowTaskInstanceExt 节点扩展对象。 + */ + void upsert(FlowTaskInstanceExt flowTaskInstanceExt); +} diff --git a/common/common-flow/src/main/java/apelet/common/flow/dao/mapper/FlowTaskInstanceExtMapper.xml b/common/common-flow/src/main/java/apelet/common/flow/dao/mapper/FlowTaskInstanceExtMapper.xml new file mode 100644 index 0000000..9cfe484 --- /dev/null +++ b/common/common-flow/src/main/java/apelet/common/flow/dao/mapper/FlowTaskInstanceExtMapper.xml @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + + + INSERT INTO zz_flow_task_instance_ext + (id, tenant_id, app_code, process_instance_id, process_definition_id, task_key, title, + create_time, create_user_id, update_time, update_user_id) + VALUES + (#{id}, #{tenantId}, #{appCode}, #{processInstanceId}, #{processDefinitionId}, #{taskKey}, #{title}, + #{createTime}, #{createUserId}, #{updateTime}, #{updateUserId}) + ON DUPLICATE KEY UPDATE + title = VALUES(title), + process_definition_id = VALUES(process_definition_id), + update_time = VALUES(update_time), + update_user_id = VALUES(update_user_id) + + diff --git a/common/common-flow/src/main/java/apelet/common/flow/listener/FlowUserTaskListener.java b/common/common-flow/src/main/java/apelet/common/flow/listener/FlowUserTaskListener.java index e35e5bd..a8f7a08 100644 --- a/common/common-flow/src/main/java/apelet/common/flow/listener/FlowUserTaskListener.java +++ b/common/common-flow/src/main/java/apelet/common/flow/listener/FlowUserTaskListener.java @@ -41,9 +41,11 @@ public class FlowUserTaskListener implements TaskListener { } /** - * 任务创建时按该节点配置的标题模板生成标题,写入工单扩展的 title_json,查询时直接读取。 + * 任务创建时按该节点配置的标题模板生成标题,写入 zz_flow_task_instance_ext,查询时直接读取。 *

首节点的 create 事件发生在工单创建之前(工单在 flowApiService.start 返回之后才建),此处取不到工单, - * 交由 FlowWorkOrderService#saveNew 在建单后补写,所以这里直接返回。

+ * 交由 FlowWorkOrderService#saveNew 在建单后按起始节点补写,所以这里直接返回。

+ * + * @param delegateTask 当前任务对象。 */ private void buildTaskTitle(DelegateTask delegateTask) { try { @@ -57,7 +59,7 @@ public class FlowUserTaskListener implements TaskListener { workOrder, delegateTask.getProcessDefinitionId(), delegateTask.getTaskDefinitionKey()); } catch (Exception e) { // 标题属于展示字段,生成失败不能阻断流程流转。 - log.warn("生成节点标题快照失败。processInstanceId [{}], taskKey [{}]", + log.warn("生成节点标题失败。processInstanceId [{}], taskKey [{}]", delegateTask.getProcessInstanceId(), delegateTask.getTaskDefinitionKey(), e); } } diff --git a/common/common-flow/src/main/java/apelet/common/flow/model/FlowTaskInstanceExt.java b/common/common-flow/src/main/java/apelet/common/flow/model/FlowTaskInstanceExt.java new file mode 100644 index 0000000..864373c --- /dev/null +++ b/common/common-flow/src/main/java/apelet/common/flow/model/FlowTaskInstanceExt.java @@ -0,0 +1,86 @@ +package apelet.common.flow.model; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.util.Date; + +/** + * 流程节点扩展实体对象(实例级)。 + *

业务键是 (processInstanceId, taskKey),即「流程实例 × 节点」,一行一个节点。

+ * + * @author chenchuchuan + * @date 2026-10-13 + */ +@Data +@TableName(value = "zz_flow_task_instance_ext") +public class FlowTaskInstanceExt { + + /** + * 主键Id。 + */ + @TableId(value = "id") + private Long id; + + /** + * 租户Id。 + */ + @TableField(value = "tenant_id") + private Long tenantId; + + /** + * 应用编码。 + */ + @TableField(value = "app_code") + private String appCode; + + /** + * 流程实例Id (→act_hi_taskinst.PROC_INST_ID_)。 + */ + @TableField(value = "process_instance_id") + private String processInstanceId; + + /** + * 流程定义Id (→act_hi_taskinst.PROC_DEF_ID_),取标题模板需用实例自己的版本。 + */ + @TableField(value = "process_definition_id") + private String processDefinitionId; + + /** + * BPMN 节点Id (= taskDefinitionKey,即 act_hi_taskinst.TASK_DEF_KEY_)。 + */ + @TableField(value = "task_key") + private String taskKey; + + /** + * 解析后的节点标题。 + */ + @TableField(value = "title") + private String title; + + /** + * 创建时间。 + */ + @TableField(value = "create_time") + private Date createTime; + + /** + * 创建者Id。 + */ + @TableField(value = "create_user_id") + private Long createUserId; + + /** + * 更新时间。 + */ + @TableField(value = "update_time") + private Date updateTime; + + /** + * 更新者Id。 + */ + @TableField(value = "update_user_id") + private Long updateUserId; +} diff --git a/common/common-flow/src/main/java/apelet/common/flow/model/FlowWorkOrderExt.java b/common/common-flow/src/main/java/apelet/common/flow/model/FlowWorkOrderExt.java index 8731ccd..4d571d1 100644 --- a/common/common-flow/src/main/java/apelet/common/flow/model/FlowWorkOrderExt.java +++ b/common/common-flow/src/main/java/apelet/common/flow/model/FlowWorkOrderExt.java @@ -40,14 +40,6 @@ public class FlowWorkOrderExt { private String businessData; /** - * 节点标题快照,JSON:{"taskKey": "解析后的标题"}。 - *

工单是「一个流程实例一行」,标题则是「实例 × 节点」级,故按 BPMN 节点Id(taskKey) 存成 JSON 承载多节点。 - * 由 FlowUserTaskListener 在任务创建时写入,查询时优先读取,取不到再回退实时解析。

- */ - @TableField(value = "title_json") - private String titleJson; - - /** * 更新时间。 */ @TableField(value = "update_time") diff --git a/common/common-flow/src/main/java/apelet/common/flow/service/FlowApiService.java b/common/common-flow/src/main/java/apelet/common/flow/service/FlowApiService.java index 6f2bd94..6676520 100644 --- a/common/common-flow/src/main/java/apelet/common/flow/service/FlowApiService.java +++ b/common/common-flow/src/main/java/apelet/common/flow/service/FlowApiService.java @@ -4,8 +4,8 @@ import apelet.common.core.object.*; import apelet.common.flow.model.FlowEntry; import apelet.common.flow.model.FlowTaskComment; import apelet.common.flow.model.FlowTaskExt; +import apelet.common.flow.model.FlowTaskInstanceExt; import apelet.common.flow.model.FlowWorkOrder; -import apelet.common.flow.model.FlowWorkOrderExt; import apelet.common.flow.object.AnalyzedNode; import apelet.common.flow.object.FlowApiOption; import apelet.common.flow.vo.FlowTaskVo; @@ -281,11 +281,12 @@ public interface FlowApiService { * @param definitionKey 流程定义的标识。 * @param definitionName 流程定义名。 * @param taskName 任务名称。 + * @param title 节点标题关键字,模糊匹配;为空时不按标题过滤。 * @param pageParam 分页对象。 * @return 用户的任务列表。 */ - MyPageData getTaskListByUserName( - String username, String definitionKey, String definitionName, String taskName, MyPageParam pageParam); + MyPageData getTaskListByUserName(String username, String definitionKey, String definitionName, + String taskName, String title, MyPageParam pageParam); /** * 获取用户的任务数量。这其中包括当前用户作为指派人和候选人。 @@ -375,6 +376,7 @@ public interface FlowApiService { * @param startUser 流程发起用户。 * @param beginDate 流程发起开始时间。 * @param endDate 流程发起结束时间。 + * @param title 首节点标题关键字,模糊匹配;为空时不按标题过滤。 * @param pageParam 分页对象。 * @param finishedOnly 仅仅返回已经结束的流程。 * @return 分页后的查询列表对象。 @@ -386,6 +388,7 @@ public interface FlowApiService { String startUser, String beginDate, String endDate, + String title, MyPageParam pageParam, boolean finishedOnly) throws ParseException; @@ -411,6 +414,7 @@ public interface FlowApiService { * @param processDefinitionName 流程名。 * @param beginDate 流程发起开始时间。 * @param endDate 流程发起结束时间。 + * @param title 节点标题关键字,模糊匹配;为空时走原有的 Flowable 查询。 * @param pageParam 分页对象。 * @return 分页后的查询列表对象。 * @throws ParseException 日期参数解析失败。 @@ -419,6 +423,7 @@ public interface FlowApiService { String processDefinitionName, String beginDate, String endDate, + String title, MyPageParam pageParam) throws ParseException; /** @@ -661,31 +666,29 @@ public interface FlowApiService { String resolveTitle(String titleTemplate, String processInstanceId, FlowWorkOrder workOrder, FlowEntry flowEntry); /** - * 优先读取已生成的标题快照,取不到再回退 {@link #resolveTitle} 实时解析。 - *

快照在任务创建时由 {@link #buildAndSaveTaskTitle} 写入工单扩展的 titleJson,按 taskKey 定位。 - * 存量数据(改造前已跑的实例)没有快照,会自动走回退分支,因此无需刷数据。

+ * 读取已生成的节点标题。 + *

标题在任务创建时由 {@link #buildAndSaveTaskTitle} 写入 zz_flow_task_instance_ext,按 (实例, 节点) 定位。 + * 本方法只读落库值,不做实时解析兜底:没有标题行就返回 null,列表上该行标题为空。 + * 因此存量数据(改造前已跑的实例)标题会为空,需要回填后才有。

* - * @param titleTemplate 节点配置的标题模板,回退时使用。 - * @param processInstanceId 流程实例Id。 - * @param workOrder 流程工单对象,为空时直接回退。 - * @param flowEntry 流程对象。 - * @param taskKey BPMN 节点Id,用于在快照中定位。 - * @param workOrderExt 工单扩展对象(调用方批量预载,避免逐行查询),可为空。 - * @return 解析后的标题。 + * @param workOrder 流程工单对象,为空时返回 null。 + * @param taskKey BPMN 节点Id,用于定位标题行,为空时返回 null。 + * @param taskInstanceExt 节点扩展对象(调用方批量预载,避免逐行查询),可为空。 + * @return 落库的标题;没有标题行返回 null。 */ - String resolveTitleCached(String titleTemplate, String processInstanceId, FlowWorkOrder workOrder, - FlowEntry flowEntry, String taskKey, FlowWorkOrderExt workOrderExt); + String resolveTitleCached(FlowWorkOrder workOrder, String taskKey, FlowTaskInstanceExt taskInstanceExt); /** - * 生成指定节点的标题快照并落库。 - *

取自该节点配置的 title_template,用当时的流程变量与在线表单业务数据解析后写入 - * {@code zz_flow_work_order_ext.title_json}。非在线表单流程、工单为空、标题为空时不写入。

+ * 生成指定节点的标题并落库到 zz_flow_task_instance_ext。 + *

取自该节点配置的 title_template,用当时的流程变量与在线表单业务数据解析后写入。 + * 非在线表单流程、工单为空、标题为空时不写入。

*

注意:首节点的 create 事件触发时工单尚未创建(工单在 flowApiService.start 返回后才建), - * 该场景下 taskKey 传空由本方法自行取当前活动任务节点,供工单创建后补写首节点标题使用。

+ * 该场景下 taskKey 传空,由本方法取该定义的起始节点 taskKey 补写。不能用「当前活动任务」兜底 —— + * autoskip 节点在 start() 内部就被 complete 了,那时取到的已经不是首节点。

* * @param workOrder 流程工单对象。 * @param processDefinitionId 流程定义Id,用于定位节点模板。 - * @param taskKey BPMN 节点Id,为空时取该实例当前的活动任务节点。 + * @param taskKey BPMN 节点Id,为空时取该定义的起始节点。 * @return 写入的标题;未写入返回null。 */ String buildAndSaveTaskTitle(FlowWorkOrder workOrder, String processDefinitionId, String taskKey); diff --git a/common/common-flow/src/main/java/apelet/common/flow/service/FlowTaskInstanceExtService.java b/common/common-flow/src/main/java/apelet/common/flow/service/FlowTaskInstanceExtService.java new file mode 100644 index 0000000..69ccbfe --- /dev/null +++ b/common/common-flow/src/main/java/apelet/common/flow/service/FlowTaskInstanceExtService.java @@ -0,0 +1,43 @@ +package apelet.common.flow.service; + +import apelet.common.core.base.service.IBaseService; +import apelet.common.flow.model.FlowTaskInstanceExt; + +import java.util.Collection; +import java.util.Map; + +/** + * 流程节点扩展(实例级)数据操作服务接口。 + * + * @author chenchuchuan + * @date 2026-10-13 + */ +public interface FlowTaskInstanceExtService extends IBaseService { + + /** + * 写入指定实例下某节点的标题。 + *

业务键是 (processInstanceId, taskKey),同一节点重复写入是覆盖语义,不会产生重复行。

+ * + * @param processInstanceId 流程实例Id。 + * @param processDefinitionId 流程定义Id,取标题模板需用实例自己的版本。 + * @param taskKey BPMN 节点Id(等价于运行时 taskDefinitionKey)。 + * @param title 解析后的标题。 + */ + void saveTaskTitle(String processInstanceId, String processDefinitionId, String taskKey, String title); + + /** + * 按实例集合批量获取节点扩展,供列表场景一次预载,避免逐行查询造成 N+1。 + * + * @param processInstanceIds 流程实例Id集合。 + * @return map,key 为 processInstanceId + ":" + taskKey。 + */ + Map getMapByProcessInstanceIds(Collection processInstanceIds); + + /** + * 按实例删除全部节点扩展。 + *

流程实例被物理删除、或草稿工单被删除时调用,避免留下孤儿行、或搜出已删除的单据。

+ * + * @param processInstanceId 流程实例Id。 + */ + void deleteByProcessInstanceId(String processInstanceId); +} diff --git a/common/common-flow/src/main/java/apelet/common/flow/service/FlowTaskTitleBackfillService.java b/common/common-flow/src/main/java/apelet/common/flow/service/FlowTaskTitleBackfillService.java new file mode 100644 index 0000000..b3f736e --- /dev/null +++ b/common/common-flow/src/main/java/apelet/common/flow/service/FlowTaskTitleBackfillService.java @@ -0,0 +1,25 @@ +package apelet.common.flow.service; + +import apelet.common.flow.vo.FlowTaskTitleBackfillVo; + +/** + * 节点标题回填服务。 + *

用于把改造前就已存在的流程实例的节点标题补齐到 zz_flow_task_instance_ext。 + * 改造前标题是查询时实时算的、从不落库,所以存量实例没有标题数据。

+ * + * @author chenchuchuan + * @date 2026-10-14 + */ +public interface FlowTaskTitleBackfillService { + + /** + * 回填一批工单的节点标题。 + *

按工单Id游标分批,幂等(已有标题行的 (实例, 节点) 直接跳过),可重复执行、可中断续跑。

+ * + * @param cursorWorkOrderId 游标,取工单Id大于该值的记录;传 null 表示从头开始。 + * @param batchSize 单批工单数,为空或非法时取默认值。 + * @param dryRun 为 true 时只统计不写库。 + * @return 本批执行结果,其中 nextCursor 为下一批游标,finished 表示是否已跑完。 + */ + FlowTaskTitleBackfillVo backfill(Long cursorWorkOrderId, Integer batchSize, Boolean dryRun); +} diff --git a/common/common-flow/src/main/java/apelet/common/flow/service/FlowWorkOrderService.java b/common/common-flow/src/main/java/apelet/common/flow/service/FlowWorkOrderService.java index 7775f6d..b8d2f3e 100644 --- a/common/common-flow/src/main/java/apelet/common/flow/service/FlowWorkOrderService.java +++ b/common/common-flow/src/main/java/apelet/common/flow/service/FlowWorkOrderService.java @@ -160,15 +160,15 @@ public interface FlowWorkOrderService extends IBaseService List getFlowWorkOrderExtByWorkOrderIds(Set workOrderIds); /** - * 写入指定工单下某节点的标题快照。 - *

titleJson 是「实例 × 节点」的映射,写入时按 taskKey 合并(读-改-写), - * 保留其他节点已写入的条目,不能整串覆盖。扩展行不存在时自动创建。

+ * 按工单Id游标分批取工单,供离线/批量任务遍历使用。 + *

与 {@link #getFlowWorkOrderList} 不同,本方法不做租户过滤、不依赖请求上下文, + * 否则在无登录态的维护接口里会因 TokenData 为空而 NPE。

* - * @param workOrderId 工单Id。 - * @param taskKey BPMN 节点Id(等价于运行时 taskDefinitionKey)。 - * @param title 解析后的标题。 + * @param cursorWorkOrderId 游标,取工单Id大于该值的记录;传 null 表示从头开始。 + * @param limit 单批数量。 + * @return 工单列表,按工单Id升序。 */ - void saveTaskTitle(Long workOrderId, String taskKey, String title); + List getListByWorkOrderIdAfter(Long cursorWorkOrderId, int limit); /** * 移除草稿工单,同时停止已经启动的流程实例。 diff --git a/common/common-flow/src/main/java/apelet/common/flow/service/impl/FlowApiServiceImpl.java b/common/common-flow/src/main/java/apelet/common/flow/service/impl/FlowApiServiceImpl.java index e55235a..8809994 100644 --- a/common/common-flow/src/main/java/apelet/common/flow/service/impl/FlowApiServiceImpl.java +++ b/common/common-flow/src/main/java/apelet/common/flow/service/impl/FlowApiServiceImpl.java @@ -23,6 +23,7 @@ import apelet.common.flow.util.BaseFlowIdentityExtHelper; import apelet.common.flow.util.FlowCustomExtFactory; import apelet.common.flow.vo.FlowTaskVo; import apelet.common.flow.vo.FlowUserInfoVo; +import apelet.common.flow.vo.TaskInfoVo; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.convert.Convert; import cn.hutool.core.lang.Assert; @@ -45,6 +46,7 @@ import org.flowable.common.engine.api.delegate.Expression; import org.flowable.common.engine.impl.de.odysseus.el.ExpressionFactoryImpl; import org.flowable.common.engine.impl.de.odysseus.el.util.SimpleContext; import org.flowable.common.engine.impl.identity.Authentication; +import org.flowable.common.engine.api.query.NativeQuery; import org.flowable.common.engine.impl.javax.el.ExpressionFactory; import org.flowable.common.engine.impl.javax.el.ValueExpression; import org.flowable.engine.*; @@ -123,6 +125,8 @@ public class FlowApiServiceImpl implements FlowApiService { private FlowVariableLogService flowVariableLogService; @Autowired private FlowTaskTimeoutJobService flowTaskTimeoutJobService; + @Autowired + private FlowTaskInstanceExtService flowTaskInstanceExtService; @Transactional(rollbackFor = Exception.class) @Override @@ -690,8 +694,8 @@ public class FlowApiServiceImpl implements FlowApiService { } @Override - public MyPageData getTaskListByUserName( - String username, String definitionKey, String definitionName, String taskName, MyPageParam pageParam) { + public MyPageData getTaskListByUserName(String username, String definitionKey, String definitionName, + String taskName, String title, MyPageParam pageParam) { TaskQuery query = this.createQuery(); if (StrUtil.isNotBlank(definitionKey)) { query.processDefinitionKey(definitionKey); @@ -705,10 +709,13 @@ public class FlowApiServiceImpl implements FlowApiService { this.buildCandidateCondition(query, username); query.orderByTaskCreateTime().desc(); Map multiInstanceTaskMap = new HashMap<>(); - long totalCount = this.countOwnedTaskList(query, username, multiInstanceTaskMap); + // 标题过滤只能在 Java 侧做:标题存在我们自己的表里,Flowable 的查询构造器表达不了; + // 而本列表的分页本来就是「批扫 + 逐条过滤」的(会签实例对候选者全体可见),跟着同一个后置过滤加最自然。 + TitleFilterContext titleFilter = new TitleFilterContext(title); + long totalCount = this.countOwnedTaskList(query, username, multiInstanceTaskMap, titleFilter); int firstResult = (pageParam.getPageNum() - 1) * pageParam.getPageSize(); List taskList = this.listOwnedTaskPage( - query, username, firstResult, pageParam.getPageSize(), multiInstanceTaskMap); + query, username, firstResult, pageParam.getPageSize(), multiInstanceTaskMap, titleFilter); return new MyPageData<>(taskList, totalCount); } @@ -716,7 +723,8 @@ public class FlowApiServiceImpl implements FlowApiService { public long getTaskCountByUserName(String username) { TaskQuery query = this.createQuery(); this.buildCandidateCondition(query, username); - return this.countOwnedTaskList(query, username, new HashMap<>()); + // 待办数量是角标,不按标题过滤 + return this.countOwnedTaskList(query, username, new HashMap<>(), new TitleFilterContext(null)); } /** @@ -724,7 +732,8 @@ public class FlowApiServiceImpl implements FlowApiService { * 多实例会签节点在流程图中将全部会签人同时配置为候选者,导致每个实例对所有人可见。 * 这里只保留会签实例归属人自己的那一条,其他会签人的实例不参与统计。 */ - private long countOwnedTaskList(TaskQuery query, String username, Map multiInstanceTaskMap) { + private long countOwnedTaskList(TaskQuery query, String username, Map multiInstanceTaskMap, + TitleFilterContext titleFilter) { long totalCount = 0; int cursor = 0; while (true) { @@ -733,8 +742,10 @@ public class FlowApiServiceImpl implements FlowApiService { break; } cursor += batch.size(); + this.loadTitles(batch, titleFilter); for (Task task : batch) { - if (this.isTaskOwnedByUser(task, username, multiInstanceTaskMap)) { + if (this.isTaskOwnedByUser(task, username, multiInstanceTaskMap) + && this.isTitleMatched(task, titleFilter)) { totalCount++; } } @@ -747,7 +758,8 @@ public class FlowApiServiceImpl implements FlowApiService { * 多实例会签节点的实例对候选者全体可见,分页时跳过不属于当前用户的其他会签实例。 */ private List listOwnedTaskPage( - TaskQuery query, String username, int firstResult, int pageSize, Map multiInstanceTaskMap) { + TaskQuery query, String username, int firstResult, int pageSize, Map multiInstanceTaskMap, + TitleFilterContext titleFilter) { List resultList = new LinkedList<>(); int skipCount = firstResult; int cursor = 0; @@ -757,8 +769,10 @@ public class FlowApiServiceImpl implements FlowApiService { break; } cursor += batch.size(); + this.loadTitles(batch, titleFilter); for (Task task : batch) { - if (!this.isTaskOwnedByUser(task, username, multiInstanceTaskMap)) { + if (!this.isTaskOwnedByUser(task, username, multiInstanceTaskMap) + || !this.isTitleMatched(task, titleFilter)) { continue; } if (skipCount > 0) { @@ -775,6 +789,83 @@ public class FlowApiServiceImpl implements FlowApiService { } /** + * 按批懒加载标题:只查本批里还没加载过的实例,避免逐条查库。 + * + * @param batch 本批任务。 + * @param titleFilter 标题过滤上下文,关键字为空时直接跳过、不做任何查询。 + */ + private void loadTitles(Collection batch, TitleFilterContext titleFilter) { + if (!titleFilter.enabled()) { + return; + } + Set toLoadIdSet = new HashSet<>(); + for (Task task : batch) { + String processInstanceId = task.getProcessInstanceId(); + if (StrUtil.isNotBlank(processInstanceId) && titleFilter.loadedInstanceIdSet.add(processInstanceId)) { + toLoadIdSet.add(processInstanceId); + } + } + if (CollUtil.isNotEmpty(toLoadIdSet)) { + titleFilter.titleMap.putAll(flowTaskInstanceExtService.getMapByProcessInstanceIds(toLoadIdSet)); + } + } + + /** + * 判断任务标题是否命中关键字。 + *

标题只认 zz_flow_task_instance_ext 的落库值:没有标题行的一律不匹配,与列表展示口径一致。

+ * + * @param task 任务对象。 + * @param titleFilter 标题过滤上下文,关键字为空时视为命中。 + * @return 是否命中。 + */ + private boolean isTitleMatched(Task task, TitleFilterContext titleFilter) { + if (!titleFilter.enabled()) { + return true; + } + FlowTaskInstanceExt taskInstanceExt = + titleFilter.titleMap.get(task.getProcessInstanceId() + ":" + task.getTaskDefinitionKey()); + return taskInstanceExt != null && StrUtil.isNotBlank(taskInstanceExt.getTitle()) + && StrUtil.contains(taskInstanceExt.getTitle(), titleFilter.keyword); + } + + /** + * 待办列表标题过滤的上下文。 + *

标题存在 zz_flow_task_instance_ext 上,Flowable 的查询构造器表达不了这个条件,只能在 Java 侧过滤; + * 而过滤时又要按实例懒加载标题、避免逐条查库。关键字、已加载实例集合、标题缓存这三样永远成组出现, + * 抽成一个对象,免得在几个方法之间来回传六个参数。

+ */ + private static class TitleFilterContext { + + /** + * 标题关键字;为空表示不按标题过滤。 + */ + private final String keyword; + + /** + * 已经加载过标题的实例Id,避免同一实例重复查库。 + */ + private final Set loadedInstanceIdSet = new HashSet<>(); + + /** + * 标题缓存,key 为 processInstanceId + ":" + taskKey。 + */ + private final Map titleMap = new HashMap<>(); + + private TitleFilterContext(String keyword) { + this.keyword = keyword; + } + + /** + * 是否按标题过滤。关键字为空时整个上下文不产生任何查询。 + * + * @return 需要按标题过滤返回 true。 + */ + private boolean enabled() { + return StrUtil.isNotBlank(keyword); + } + } + + /** * 判断任务是否属于当前用户。 * 多实例会签实例的元素变量 assignee 即该实例真正的归属人。 */ @@ -906,11 +997,9 @@ public class FlowApiServiceImpl implements FlowApiService { flowWorkOrderService.getInList("processInstanceId", procInstanceIdSet); Map workOrderMap = workOrderList.stream().collect(Collectors.toMap(FlowWorkOrder::getProcessInstanceId, c -> c)); - // 标题快照按工单批量预载(一次 IN 查询覆盖整页),避免逐行查扩展对象造成 N+1。 - Map workOrderExtMap = flowWorkOrderService - .getFlowWorkOrderExtByWorkOrderIds(workOrderList.stream() - .map(FlowWorkOrder::getWorkOrderId).filter(Objects::nonNull).collect(Collectors.toSet())) - .stream().collect(Collectors.toMap(FlowWorkOrderExt::getWorkOrderId, c -> c, (k1, k2) -> k1)); + // 节点标题按实例批量预载(一次 IN 查询覆盖整页),避免逐行查询造成 N+1。 + Map taskInstanceExtMap = + flowTaskInstanceExtService.getMapByProcessInstanceIds(procInstanceIdSet); List allFlowTaskExtList = flowTaskExtService.getByProcessDefinitionId(processDefinitionIdSet); Map flowTaskExtMap = allFlowTaskExtList.stream().collect(Collectors.toMap(t -> t.getProcessDefinitionId() + ":" + t.getTaskId(), t -> t, (k1, k2) -> k1)); Map multiInstanceTaskMap = new HashMap<>(); @@ -943,9 +1032,8 @@ public class FlowApiServiceImpl implements FlowApiService { FlowTaskExt flowTaskExt = flowTaskExtMap.get(task.getProcessDefinitionId() + ":" + task.getTaskDefinitionKey()); FlowEntry flowEntry = flowEntryMap.get(flowEntryPublishMap.get(task.getProcessDefinitionId()).getEntryId()); if (flowTaskExt != null && flowEntry != null) { - flowTaskVo.setTitle(this.resolveTitleCached(flowTaskExt.getTitleTemplate(), - task.getProcessInstanceId(), flowWorkOrder, flowEntry, task.getTaskDefinitionKey(), - flowWorkOrder == null ? null : workOrderExtMap.get(flowWorkOrder.getWorkOrderId()))); + flowTaskVo.setTitle(this.resolveTitleCached(flowWorkOrder, task.getTaskDefinitionKey(), + taskInstanceExtMap.get(task.getProcessInstanceId() + ":" + task.getTaskDefinitionKey()))); } flowTaskVoList.add(flowTaskVo); } @@ -1022,8 +1110,16 @@ public class FlowApiServiceImpl implements FlowApiService { String startUser, String beginDate, String endDate, + String title, MyPageParam pageParam, boolean finishedOnly) throws ParseException { + if (StrUtil.isNotBlank(title)) { + // 标题存在 zz_flow_task_instance_ext 上,Flowable 的查询构造器表达不了这个条件; + // 而本接口的分页与总数全由 SQL 决定,Java 侧再过滤会把分页搞坏,所以改走原生 join。 + return this.getHistoricProcessInstanceListByTitle( + processDefinitionKey, processDefinitionName, startUser, beginDate, endDate, title, + pageParam, finishedOnly); + } HistoricProcessInstanceQuery query = historyService.createHistoricProcessInstanceQuery(); if (StrUtil.isNotBlank(processDefinitionKey)) { query.processDefinitionKey(processDefinitionKey); @@ -1062,13 +1158,87 @@ public class FlowApiServiceImpl implements FlowApiService { return new MyPageData<>(instanceList, totalCount); } + /** + * 按首节点标题关键字查询历史流程实例,走 Flowable 的原生 join 查询。 + *

过滤条件逐个复刻自 {@code HistoricProcessInstanceQuery}(源码 HistoricProcessInstance.xml), + * 漏一个就是 bug,且只在带关键字时复现: + * processDefinitionKey→DEF.KEY_;processDefinitionName→DEF.NAME_;startedBy→RES.START_USER_ID_; + * startedAfter/startedBefore→RES.START_TIME_ >= / <= (注意是闭区间); + * finished→RES.END_TIME_ is not null;tenantId/withoutTenantId→RES.TENANT_ID_ 等值、或空串/NULL; + * orderByProcessInstanceStartTime().desc()→order by RES.START_TIME_ desc。

+ *

标题口径与列表展示保持一致 —— 只取首节点的标题。首节点 taskKey 存在发布版本的 + * {@code zz_flow_entry_publish.init_task_info} 里,随流程定义而变,所以要在 SQL 里用 JSON 函数解析。 + * init_task_info 是 TEXT,可能不是合法 JSON,先用 CASE + JSON_VALID 挡一道,避免脏数据让整个查询报错。

+ *

表名 ACT_HI_PROCINST / ACT_RE_PROCDEF 必须写死 —— Flowable 原生查询不支持 ${prefix} 占位符。 + * 本工程未配置 flowable 的 database-table-prefix,将来若配置,此处表名需同步修改; + * Flowable 升级时也需复查列名与语义。

+ */ + private MyPageData getHistoricProcessInstanceListByTitle( + String processDefinitionKey, String processDefinitionName, String startUser, + String beginDate, String endDate, String title, MyPageParam pageParam, + boolean finishedOnly) throws ParseException { + Map params = new HashMap<>(8); + params.put("title", "%" + this.escapeLikeKeyword(title) + "%"); + StringBuilder where = new StringBuilder(256); + where.append(" WHERE TT.TITLE LIKE #{title}"); + if (StrUtil.isNotBlank(processDefinitionKey)) { + where.append(" AND DEF.KEY_ = #{processDefinitionKey}"); + params.put("processDefinitionKey", processDefinitionKey); + } + if (StrUtil.isNotBlank(processDefinitionName)) { + where.append(" AND DEF.NAME_ = #{processDefinitionName}"); + params.put("processDefinitionName", processDefinitionName); + } + if (StrUtil.isNotBlank(startUser)) { + where.append(" AND RES.START_USER_ID_ = #{startUser}"); + params.put("startUser", startUser); + } + if (StrUtil.isNotBlank(beginDate)) { + SimpleDateFormat sdf = new SimpleDateFormat(MyDateUtil.COMMON_SHORT_DATETIME_FORMAT); + where.append(" AND RES.START_TIME_ >= #{beginDate}"); + params.put("beginDate", sdf.parse(beginDate)); + } + if (StrUtil.isNotBlank(endDate)) { + SimpleDateFormat sdf = new SimpleDateFormat(MyDateUtil.COMMON_SHORT_DATETIME_FORMAT); + where.append(" AND RES.START_TIME_ <= #{endDate}"); + params.put("endDate", sdf.parse(endDate)); + } + this.appendTenantCondition(where, params); + if (finishedOnly) { + where.append(" AND RES.END_TIME_ is not null"); + } + // RES.* 之外必须带上 DEF 的四个别名列:原生查询复用的是 historicProcessInstanceResultMap, + // 列表回去要用 getProcessDefinitionKey()/getName(),漏了这几列这两项就是空的。 + String fromJoin = " FROM ACT_HI_PROCINST RES" + + " LEFT OUTER JOIN ACT_RE_PROCDEF DEF ON RES.PROC_DEF_ID_ = DEF.ID_" + + " INNER JOIN zz_flow_entry_publish FP ON FP.process_definition_id = RES.PROC_DEF_ID_" + + " INNER JOIN zz_flow_task_instance_ext TT ON TT.PROCESS_INSTANCE_ID = RES.ID_" + + " AND TT.TASK_KEY = CASE WHEN JSON_VALID(FP.init_task_info)" + + " THEN JSON_UNQUOTE(JSON_EXTRACT(FP.init_task_info, '$.taskKey')) ELSE NULL END"; + return this.executeNativeTitleQuery( + historyService.createNativeHistoricProcessInstanceQuery().sql( + "SELECT RES.*, DEF.KEY_ AS PROC_DEF_KEY_, DEF.NAME_ AS PROC_DEF_NAME_," + + " DEF.VERSION_ AS PROC_DEF_VERSION_, DEF.DEPLOYMENT_ID_ AS DEPLOYMENT_ID_" + + fromJoin + where + " ORDER BY RES.START_TIME_ DESC"), + historyService.createNativeHistoricProcessInstanceQuery().sql("SELECT COUNT(*)" + fromJoin + where), + params, pageParam); + } + @Override public MyPageData getHistoricTaskInstanceFinishedList( String processDefinitionName, String beginDate, String endDate, + String title, MyPageParam pageParam) throws ParseException { String loginName = TokenData.takeFromRequest().getLoginName(); + if (StrUtil.isNotBlank(title)) { + // 标题存在 zz_flow_task_instance_ext 上,Flowable 的查询构造器表达不了这个条件; + // 而本接口的分页/排序/总数由 count()+listPage() 决定,Java 侧再过滤会让 totalCount 与页内容错乱, + // 所以带关键字时改走原生 join 查询,把过滤/排序/分页/count 全部下推到 SQL。 + return this.getHistoricTaskInstanceFinishedListByTitle( + processDefinitionName, beginDate, endDate, title, loginName, pageParam); + } HistoricTaskInstanceQuery query = historyService.createHistoricTaskInstanceQuery() .taskAssignee(loginName) .finished(); @@ -1100,6 +1270,109 @@ public class FlowApiServiceImpl implements FlowApiService { return new MyPageData<>(instanceList, totalCount); } + /** + * 按节点标题关键字查询当前用户已办理的任务,走 Flowable 的原生 join 查询。 + *

过滤条件逐个复刻自 {@code HistoricTaskInstanceQuery}(源码 HistoricTaskInstance.xml),漏一个就是 bug, + * 且只在带关键字时复现: + * taskAssignee→ASSIGNEE_;finished→END_TIME_ is not null;taskCompletedAfter/Before→END_TIME_ > / <; + * processDefinitionName→ACT_RE_PROCDEF 的 exists 子查询;taskTenantId/taskWithoutTenantId→TENANT_ID_ 等值、 + * 或空串/NULL;orderByHistoricTaskInstanceEndTime().desc()→order by END_TIME_ desc。

+ *

表名 ACT_HI_TASKINST 必须写死 —— Flowable 的原生查询不支持 ${prefix} 占位符(实测会被渲染成字面量)。 + * 本工程未配置 flowable 的 database-table-prefix,将来若配置,此处表名需同步修改; + * Flowable 升级时也需复查上述列名与语义。

+ *

另:join 条件命中 zz_flow_task_instance_ext 的唯一键 (process_instance_id, task_key),走 eq_ref; + * 但 LIKE '%kw%' 用不上索引,且选择性差,MySQL 有可能选错驱动表导致匹配集全量 filesort。 + * 上线前用 EXPLAIN 确认驱动表是 ACT_HI_TASKINST,必要时把 INNER JOIN 改为 STRAIGHT_JOIN。

+ */ + private MyPageData getHistoricTaskInstanceFinishedListByTitle( + String processDefinitionName, String beginDate, String endDate, String title, + String loginName, MyPageParam pageParam) throws ParseException { + Map params = new HashMap<>(8); + params.put("assignee", loginName); + params.put("title", "%" + this.escapeLikeKeyword(title) + "%"); + StringBuilder where = new StringBuilder(256); + where.append(" WHERE RES.ASSIGNEE_ = #{assignee} AND RES.END_TIME_ is not null AND TT.TITLE LIKE #{title}"); + if (StrUtil.isNotBlank(beginDate)) { + SimpleDateFormat sdf = new SimpleDateFormat(MyDateUtil.COMMON_SHORT_DATETIME_FORMAT); + where.append(" AND RES.END_TIME_ > #{beginDate}"); + params.put("beginDate", sdf.parse(beginDate)); + } + if (StrUtil.isNotBlank(endDate)) { + SimpleDateFormat sdf = new SimpleDateFormat(MyDateUtil.COMMON_SHORT_DATETIME_FORMAT); + where.append(" AND RES.END_TIME_ < #{endDate}"); + params.put("endDate", sdf.parse(endDate)); + } + if (StrUtil.isNotBlank(processDefinitionName)) { + where.append(" AND exists (select 1 from ACT_RE_PROCDEF D") + .append(" where RES.PROC_DEF_ID_ = D.ID_ and D.NAME_ = #{processDefinitionName})"); + params.put("processDefinitionName", processDefinitionName); + } + this.appendTenantCondition(where, params); + String fromJoin = " FROM ACT_HI_TASKINST RES INNER JOIN zz_flow_task_instance_ext TT" + + " ON TT.PROCESS_INSTANCE_ID = RES.PROC_INST_ID_ AND TT.TASK_KEY = RES.TASK_DEF_KEY_"; + return this.executeNativeTitleQuery( + historyService.createNativeHistoricTaskInstanceQuery() + .sql("SELECT RES.*" + fromJoin + where + " ORDER BY RES.END_TIME_ DESC"), + historyService.createNativeHistoricTaskInstanceQuery().sql("SELECT COUNT(*)" + fromJoin + where), + params, pageParam); + } + + /** + * 转义 LIKE 的通配符,避免用户输入里的 % 和 _ 被当成通配符。 + *

反斜杠是 MySQL 的默认转义符,自身要先转义。

+ * + * @param keyword 用户输入的关键字。 + * @return 转义后的关键字。 + */ + private String escapeLikeKeyword(String keyword) { + return keyword.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_"); + } + + /** + * 执行「list + count 两条同 FROM/WHERE 的原生查询」,两处原生标题查询共用。 + *

count 与 list 必须共用同一套 FROM/WHERE、且 count 不能带 ORDER BY,否则 totalCount 与页内容会对不上。

+ * + * @param listQuery 已设置好 sql 的 list 查询。 + * @param countQuery 已设置好 sql 的 count 查询。 + * @param params 绑参,会同时应用到两条查询。 + * @param pageParam 分页对象。 + * @param 查询返回的行类型。 + * @return 分页结果。 + */ + private MyPageData executeNativeTitleQuery( + NativeQuery listQuery, NativeQuery countQuery, + Map params, MyPageParam pageParam) { + for (Map.Entry entry : params.entrySet()) { + listQuery.parameter(entry.getKey(), entry.getValue()); + countQuery.parameter(entry.getKey(), entry.getValue()); + } + long totalCount = countQuery.count(); + int firstResult = (pageParam.getPageNum() - 1) * pageParam.getPageSize(); + return new MyPageData<>(listQuery.listPage(firstResult, pageParam.getPageSize()), totalCount); + } + + /** + * 追加租户过滤条件,两处原生标题查询共用。 + *

语义与 Flowable 的 taskTenantId / taskWithoutTenantId(历史流程侧是 processInstanceTenantId / + * processInstanceWithoutTenantId)保持一致:有租户Id走等值;既没有租户Id也没有 appCode 时按"无租户"处理 + * (空串或 NULL);否则把 appCode 当租户。

+ * + * @param where 正在拼装的 WHERE 片段。 + * @param params 绑参容器,tenantId 参数由本方法写入。 + */ + private void appendTenantCondition(StringBuilder where, Map params) { + TokenData tokenData = TokenData.takeFromRequest(); + if (tokenData.getTenantId() != null) { + where.append(" AND RES.TENANT_ID_ = #{tenantId}"); + params.put("tenantId", tokenData.getTenantId().toString()); + } else if (StrUtil.isBlank(tokenData.getAppCode())) { + where.append(" AND (RES.TENANT_ID_ = '' or RES.TENANT_ID_ is null)"); + } else { + where.append(" AND RES.TENANT_ID_ = #{tenantId}"); + params.put("tenantId", tokenData.getAppCode()); + } + } + @Override public List getHistoricActivityInstanceList(String processInstanceId) { return historyService.createHistoricActivityInstanceQuery().processInstanceId(processInstanceId).list(); @@ -1183,6 +1456,9 @@ public class FlowApiServiceImpl implements FlowApiService { @Override public void deleteProcessInstance(String processInstanceId) { historyService.deleteHistoricProcessInstance(processInstanceId); + // deleteHistoricProcessInstance 会级联物理删除该实例的全部 act_hi_taskinst, + // 节点扩展里的标题行不跟着删就成了永远无用的孤儿行。 + flowTaskInstanceExtService.deleteByProcessInstanceId(processInstanceId); flowMessageService.removeByProcessInstanceId(processInstanceId); FlowWorkOrder workOrder = flowWorkOrderService.getFlowWorkOrderByProcessInstanceId(processInstanceId); if (workOrder == null) { @@ -2695,22 +2971,14 @@ public class FlowApiServiceImpl implements FlowApiService { } @Override - public String resolveTitleCached(String titleTemplate, String processInstanceId, FlowWorkOrder workOrder, - FlowEntry flowEntry, String taskKey, FlowWorkOrderExt workOrderExt) { - if (workOrder != null && workOrderExt != null && StrUtil.isNotBlank(taskKey) - && StrUtil.isNotBlank(workOrderExt.getTitleJson())) { - try { - String cached = JSON.parseObject(workOrderExt.getTitleJson()).getString(taskKey); - if (StrUtil.isNotBlank(cached)) { - return cached; - } - } catch (Exception e) { - // 快照解析失败不能影响列表整体,降级为实时解析。 - log.warn("标题快照解析失败,降级为实时解析。workOrderId [{}], taskKey [{}]", - workOrder.getWorkOrderId(), taskKey, e); - } + public String resolveTitleCached(FlowWorkOrder workOrder, String taskKey, FlowTaskInstanceExt taskInstanceExt) { + // 标题只以 zz_flow_task_instance_ext 的落库值为准,不再回退到按模板实时解析。 + // 这样"这个节点到底有没有落库"在列表上一眼可见,排查/联调时不会被实时兜底掩盖。 + if (workOrder == null || taskInstanceExt == null || StrUtil.isBlank(taskKey) + || StrUtil.isBlank(taskInstanceExt.getTitle())) { + return null; } - return this.resolveTitle(titleTemplate, processInstanceId, workOrder, flowEntry); + return taskInstanceExt.getTitle(); } @Override @@ -2720,13 +2988,13 @@ public class FlowApiServiceImpl implements FlowApiService { } String nodeKey = taskKey; if (StrUtil.isBlank(nodeKey)) { - // 首节点补写场景:create 事件触发时工单还没创建,走到这里工单已建,取当前活动任务节点即可。 - Task activeTask = taskService.createTaskQuery() - .processInstanceId(workOrder.getProcessInstanceId()).active().singleResult(); - if (activeTask == null) { + // 首节点补写场景:create 事件触发时工单还没创建(工单在 flowApiService.start 返回之后才建), + // 走到这里流程可能已经推进过了(autoskip 节点在 start() 内部就被 complete), + // 所以不能取「当前活动任务」,要取该定义的起始节点,与历史流程列表的口径保持一致。 + nodeKey = this.getInitTaskKey(processDefinitionId); + if (StrUtil.isBlank(nodeKey)) { return null; } - nodeKey = activeTask.getTaskDefinitionKey(); } FlowEntry flowEntry = StrUtil.isBlank(workOrder.getProcessDefinitionKey()) ? null : flowEntryService.getFlowEntryFromCache(workOrder.getProcessDefinitionKey()); @@ -2740,11 +3008,38 @@ public class FlowApiServiceImpl implements FlowApiService { if (StrUtil.isBlank(title)) { return null; } - flowWorkOrderService.saveTaskTitle(workOrder.getWorkOrderId(), nodeKey, title); + flowTaskInstanceExtService.saveTaskTitle(workOrder.getProcessInstanceId(), processDefinitionId, nodeKey, title); return title; } /** + * 取指定流程定义的起始节点 taskKey。 + *

来源是该发布版本的 initTaskInfo,与历史流程列表(FlowOperationController#listHistoricProcessInstance) + * 取首节点标题模板的口径保持一致。

+ * + * @param processDefinitionId 流程定义Id。 + * @return 起始节点 taskKey,取不到返回null。 + */ + private String getInitTaskKey(String processDefinitionId) { + if (StrUtil.isBlank(processDefinitionId)) { + return null; + } + List publishList = + flowEntryService.getFlowEntryPublishList(CollUtil.newHashSet(processDefinitionId)); + for (FlowEntryPublish publish : publishList) { + if (!StrUtil.equals(publish.getProcessDefinitionId(), processDefinitionId) + || StrUtil.isBlank(publish.getInitTaskInfo())) { + continue; + } + TaskInfoVo initTaskInfo = JSON.parseObject(publish.getInitTaskInfo(), TaskInfoVo.class); + if (initTaskInfo != null && StrUtil.isNotBlank(initTaskInfo.getTaskKey())) { + return initTaskInfo.getTaskKey(); + } + } + return null; + } + + /** * 首节点生成标题时还没发生过任何任务完成,${submitUser} 尚未写入(它由 completeTask 设置), * 直接解析会留下字面量。首节点的"提交人"语义上就是发起人,故此时把模板里的 ${submitUser} 换成 ${initiator}。 * 第 2 个节点起上一个节点的 complete 已写好 submitUser,原样返回。 diff --git a/common/common-flow/src/main/java/apelet/common/flow/service/impl/FlowTaskInstanceExtServiceImpl.java b/common/common-flow/src/main/java/apelet/common/flow/service/impl/FlowTaskInstanceExtServiceImpl.java new file mode 100644 index 0000000..224269a --- /dev/null +++ b/common/common-flow/src/main/java/apelet/common/flow/service/impl/FlowTaskInstanceExtServiceImpl.java @@ -0,0 +1,139 @@ +package apelet.common.flow.service.impl; + +import apelet.common.core.annotation.MyDataSourceResolver; +import apelet.common.core.base.dao.BaseDaoMapper; +import apelet.common.core.base.service.BaseService; +import apelet.common.core.constant.ApplicationConstant; +import apelet.common.core.object.TokenData; +import apelet.common.core.util.DefaultDataSourceResolver; +import apelet.common.flow.dao.FlowTaskInstanceExtMapper; +import apelet.common.flow.model.FlowTaskInstanceExt; +import apelet.common.flow.service.FlowTaskInstanceExtService; +import apelet.common.sequence.wrapper.IdGeneratorWrapper; +import cn.hutool.core.collection.CollUtil; +import cn.hutool.core.util.StrUtil; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.Collection; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * 流程节点扩展(实例级)数据操作服务类。 + * + * @author chenchuchuan + * @date 2026-10-13 + */ +@MyDataSourceResolver( + resolver = DefaultDataSourceResolver.class, + intArg = ApplicationConstant.COMMON_FLOW_AND_ONLINE_DATASOURCE_TYPE) +@Service("flowTaskInstanceExtService") +public class FlowTaskInstanceExtServiceImpl extends BaseService + implements FlowTaskInstanceExtService { + + /** + * title 列的长度上限(varchar(1024)),超出会被数据库拒绝,写入前先截断。 + */ + private static final int TITLE_MAX_LENGTH = 1024; + + /** + * 截断时补的省略号。 + */ + private static final String TITLE_ELLIPSIS = "..."; + + @Autowired + private FlowTaskInstanceExtMapper flowTaskInstanceExtMapper; + @Autowired + private IdGeneratorWrapper idGenerator; + + /** + * 返回当前Service的主表Mapper对象。 + * + * @return 主表Mapper对象。 + */ + @Override + protected BaseDaoMapper mapper() { + return flowTaskInstanceExtMapper; + } + + @Transactional(rollbackFor = Exception.class) + @Override + public void saveTaskTitle(String processInstanceId, String processDefinitionId, String taskKey, String title) { + if (StrUtil.isBlank(processInstanceId) || StrUtil.isBlank(taskKey) || StrUtil.isBlank(title)) { + return; + } + FlowTaskInstanceExt entity = new FlowTaskInstanceExt(); + entity.setId(idGenerator.nextLongId()); + entity.setProcessInstanceId(processInstanceId); + entity.setProcessDefinitionId(processDefinitionId); + entity.setTaskKey(taskKey); + entity.setTitle(this.truncateTitle(title)); + Date now = new Date(); + entity.setCreateTime(now); + entity.setUpdateTime(now); + entity.setCreateUserId(this.getOperatorId()); + entity.setUpdateUserId(entity.getCreateUserId()); + TokenData tokenData = TokenData.takeFromRequest(); + if (tokenData != null) { + entity.setTenantId(tokenData.getTenantId()); + entity.setAppCode(tokenData.getAppCode()); + } + // 唯一键 (process_instance_id, task_key) 保证同一节点只有一行,重复写入是覆盖语义; + // 用 upsert 而非先查后写,避免并发的任务创建互相覆盖。 + flowTaskInstanceExtMapper.upsert(entity); + } + + @Override + public Map getMapByProcessInstanceIds(Collection processInstanceIds) { + // 空集合会产生非法的 IN () 语句,这里直接短路返回。 + if (CollUtil.isEmpty(processInstanceIds)) { + return new HashMap<>(); + } + LambdaQueryWrapper qw = new LambdaQueryWrapper<>(); + qw.in(FlowTaskInstanceExt::getProcessInstanceId, processInstanceIds); + return flowTaskInstanceExtMapper.selectList(qw).stream().collect(Collectors.toMap( + e -> e.getProcessInstanceId() + ":" + e.getTaskKey(), c -> c, (existOne, newOne) -> existOne)); + } + + @Transactional(rollbackFor = Exception.class) + @Override + public void deleteByProcessInstanceId(String processInstanceId) { + if (StrUtil.isBlank(processInstanceId)) { + return; + } + flowTaskInstanceExtMapper.delete(new LambdaQueryWrapper() + .eq(FlowTaskInstanceExt::getProcessInstanceId, processInstanceId)); + } + + /** + * 把标题截断到列宽以内。 + *

注意不能用 Hutool 的 StrUtil.maxLength(title, 1024):它是「先截到 1024 再补 ...」, + * 返回 1027 个字符,写进 varchar(1024) 会直接被数据库拒绝。

+ * + * @param title 解析后的标题。 + * @return 不超过 TITLE_MAX_LENGTH 的标题。 + */ + private String truncateTitle(String title) { + if (title.length() <= TITLE_MAX_LENGTH) { + return title; + } + return title.substring(0, TITLE_MAX_LENGTH - TITLE_ELLIPSIS.length()) + TITLE_ELLIPSIS; + } + + /** + * 取当前操作用户Id。 + *

本表的写入不总在 HTTP 请求线程里(如超时作业触发自动审批时创建下一个任务), + * 此时 TokenData 为空,回落为 0,避免非空约束报错导致标题写入被静默吞掉。

+ * + * @return 操作用户Id。 + */ + private Long getOperatorId() { + TokenData tokenData = TokenData.takeFromRequest(); + return tokenData == null || tokenData.getUserId() == null ? 0L : tokenData.getUserId(); + } +} diff --git a/common/common-flow/src/main/java/apelet/common/flow/service/impl/FlowTaskTitleBackfillServiceImpl.java b/common/common-flow/src/main/java/apelet/common/flow/service/impl/FlowTaskTitleBackfillServiceImpl.java new file mode 100644 index 0000000..36b0d3d --- /dev/null +++ b/common/common-flow/src/main/java/apelet/common/flow/service/impl/FlowTaskTitleBackfillServiceImpl.java @@ -0,0 +1,212 @@ +package apelet.common.flow.service.impl; + +import apelet.common.core.annotation.MyDataSourceResolver; +import apelet.common.core.constant.ApplicationConstant; +import apelet.common.core.object.GlobalThreadLocal; +import apelet.common.core.object.TokenData; +import apelet.common.core.util.DefaultDataSourceResolver; +import apelet.common.flow.model.FlowEntry; +import apelet.common.flow.model.FlowTaskExt; +import apelet.common.flow.model.FlowTaskInstanceExt; +import apelet.common.flow.model.FlowWorkOrder; +import apelet.common.flow.model.constant.FlowBindFormType; +import apelet.common.flow.service.FlowApiService; +import apelet.common.flow.service.FlowEntryService; +import apelet.common.flow.service.FlowTaskExtService; +import apelet.common.flow.service.FlowTaskInstanceExtService; +import apelet.common.flow.service.FlowTaskTitleBackfillService; +import apelet.common.flow.service.FlowWorkOrderService; +import apelet.common.flow.vo.FlowTaskTitleBackfillVo; +import cn.hutool.core.collection.CollUtil; +import cn.hutool.core.util.BooleanUtil; +import cn.hutool.core.util.ObjectUtil; +import cn.hutool.core.util.StrUtil; +import lombok.extern.slf4j.Slf4j; +import org.flowable.engine.HistoryService; +import org.flowable.engine.TaskService; +import org.flowable.task.api.Task; +import org.flowable.task.api.history.HistoricTaskInstance; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * 节点标题回填服务实现。 + * + * @author chenchuchuan + * @date 2026-10-14 + */ +@Slf4j +@MyDataSourceResolver( + resolver = DefaultDataSourceResolver.class, + intArg = ApplicationConstant.COMMON_FLOW_AND_ONLINE_DATASOURCE_TYPE) +@Service("flowTaskTitleBackfillService") +public class FlowTaskTitleBackfillServiceImpl implements FlowTaskTitleBackfillService { + + private static final int DEFAULT_BATCH_SIZE = 200; + + private static final int MAX_BATCH_SIZE = 2000; + + @Autowired + private FlowWorkOrderService flowWorkOrderService; + @Autowired + private FlowEntryService flowEntryService; + @Autowired + private FlowTaskExtService flowTaskExtService; + @Autowired + private FlowTaskInstanceExtService flowTaskInstanceExtService; + @Autowired + private FlowApiService flowApiService; + @Autowired + private HistoryService historyService; + @Autowired + private TaskService taskService; + + @Override + public FlowTaskTitleBackfillVo backfill(Long cursorWorkOrderId, Integer batchSize, Boolean dryRun) { + long startTime = System.currentTimeMillis(); + int size = batchSize == null || batchSize <= 0 ? DEFAULT_BATCH_SIZE : Math.min(batchSize, MAX_BATCH_SIZE); + boolean onlyCount = BooleanUtil.isTrue(dryRun); + FlowTaskTitleBackfillVo result = new FlowTaskTitleBackfillVo(); + result.setInstanceCount(0); + result.setNodeCount(0); + result.setSavedCount(0); + result.setSkippedExistCount(0); + result.setSkippedNoTitleCount(0); + result.setFailedCount(0); + result.setDryRun(onlyCount); + // 回填是没有登录态的运维动作,且要跨租户跑;关掉数据权限过滤, + // 否则 getMasterData -> buildDataPermFilter -> processDataPerm 会因 TokenData 为空而 NPE。 + boolean dataFilterEnabled = GlobalThreadLocal.setDataFilter(false); + try { + List workOrderList = flowWorkOrderService.getListByWorkOrderIdAfter(cursorWorkOrderId, size); + for (FlowWorkOrder workOrder : workOrderList) { + this.backfillOneInstance(workOrder, onlyCount, result); + } + result.setInstanceCount(workOrderList.size()); + result.setFinished(workOrderList.size() < size); + result.setNextCursor(workOrderList.isEmpty() + ? null : workOrderList.get(workOrderList.size() - 1).getWorkOrderId()); + } finally { + GlobalThreadLocal.setDataFilter(dataFilterEnabled); + } + result.setElapsedMs(System.currentTimeMillis() - startTime); + return result; + } + + /** + * 回填单个实例下出现过的所有节点。 + * + * @param workOrder 工单对象。 + * @param dryRun 只统计不写库。 + * @param result 累计结果。 + */ + private void backfillOneInstance(FlowWorkOrder workOrder, boolean dryRun, FlowTaskTitleBackfillVo result) { + String processInstanceId = workOrder.getProcessInstanceId(); + if (StrUtil.isBlank(processInstanceId)) { + return; + } + FlowEntry flowEntry = StrUtil.isBlank(workOrder.getProcessDefinitionKey()) ? null + : flowEntryService.getFlowEntryFromCache(workOrder.getProcessDefinitionKey()); + // 路由表单流程本来就没有标题,跳过 + if (flowEntry == null || !ObjectUtil.equal(flowEntry.getBindFormType(), FlowBindFormType.ONLINE_FORM)) { + return; + } + // 按实例补一份 TokenData:业务数据查询的租户/应用归属、以及 ${loginName} 之类的占位符解析, + // 要尽量贴近当初实时解析时的环境,否则算出来的业务数据可能与线上显示的不一致。 + this.bindTokenData(workOrder); + Set taskKeySet = this.getTaskKeySet(processInstanceId); + if (CollUtil.isEmpty(taskKeySet)) { + return; + } + Map existMap = dryRun ? Collections.emptyMap() + : flowTaskInstanceExtService.getMapByProcessInstanceIds(Collections.singletonList(processInstanceId)); + for (String taskKey : taskKeySet) { + result.setNodeCount(result.getNodeCount() + 1); + if (existMap.containsKey(processInstanceId + ":" + taskKey)) { + // 幂等:已有标题行不重算也不覆盖,便于重复执行与中断续跑 + result.setSkippedExistCount(result.getSkippedExistCount() + 1); + continue; + } + if (dryRun) { + continue; + } + try { + String title = this.buildTitle(workOrder, flowEntry, taskKey); + if (StrUtil.isBlank(title)) { + result.setSkippedNoTitleCount(result.getSkippedNoTitleCount() + 1); + continue; + } + flowTaskInstanceExtService.saveTaskTitle( + processInstanceId, workOrder.getProcessDefinitionId(), taskKey, title); + result.setSavedCount(result.getSavedCount() + 1); + } catch (Exception e) { + // 单条失败不影响整批,记数后继续 + result.setFailedCount(result.getFailedCount() + 1); + log.warn("回填节点标题失败。processInstanceId [{}], taskKey [{}]", processInstanceId, taskKey, e); + } + } + } + + /** + * 按模板重新解析该节点的标题。 + *

模板必须用实例自己的 processDefinitionId 取 —— zz_flow_task_ext 的主键是 + * (process_definition_id, task_id),老实例指向当初发布的那一版定义,用当前主版本会取到改版后的模板。

+ * + * @param workOrder 工单对象。 + * @param flowEntry 流程对象。 + * @param taskKey 节点Id。 + * @return 解析后的标题,解析不出返回 null。 + */ + private String buildTitle(FlowWorkOrder workOrder, FlowEntry flowEntry, String taskKey) { + FlowTaskExt flowTaskExt = flowTaskExtService + .getByProcessDefinitionIdAndTaskId(workOrder.getProcessDefinitionId(), taskKey); + String titleTemplate = flowTaskExt == null ? null : flowTaskExt.getTitleTemplate(); + return flowApiService.resolveTitle(titleTemplate, workOrder.getProcessInstanceId(), workOrder, flowEntry); + } + + /** + * 取该实例出现过的所有节点:已办的历史任务 + 正在待办的任务。 + *

待办节点也要带上,否则老单据在待办列表里同样没有标题。

+ * + * @param processInstanceId 流程实例Id。 + * @return 节点Id集合。 + */ + private Set getTaskKeySet(String processInstanceId) { + Set taskKeySet = new HashSet<>(); + List historicTaskList = + historyService.createHistoricTaskInstanceQuery().processInstanceId(processInstanceId).list(); + for (HistoricTaskInstance task : historicTaskList) { + if (StrUtil.isNotBlank(task.getTaskDefinitionKey())) { + taskKeySet.add(task.getTaskDefinitionKey()); + } + } + List activeTaskList = taskService.createTaskQuery().processInstanceId(processInstanceId).list(); + for (Task task : activeTaskList) { + if (StrUtil.isNotBlank(task.getTaskDefinitionKey())) { + taskKeySet.add(task.getTaskDefinitionKey()); + } + } + return taskKeySet; + } + + /** + * 按实例绑定 TokenData,供业务数据查询使用。 + * + * @param workOrder 工单对象。 + */ + private void bindTokenData(FlowWorkOrder workOrder) { + TokenData tokenData = new TokenData(); + tokenData.setLoginName(workOrder.getSubmitUsername()); + tokenData.setTenantId(workOrder.getTenantId()); + tokenData.setAppCode(workOrder.getAppCode()); + // 运维动作,跨租户执行,不按某个具体用户的数据权限过滤 + tokenData.setIsAdmin(Boolean.TRUE); + TokenData.addToRequest(tokenData); + } +} diff --git a/common/common-flow/src/main/java/apelet/common/flow/service/impl/FlowWorkOrderServiceImpl.java b/common/common-flow/src/main/java/apelet/common/flow/service/impl/FlowWorkOrderServiceImpl.java index a99f702..ac090b3 100644 --- a/common/common-flow/src/main/java/apelet/common/flow/service/impl/FlowWorkOrderServiceImpl.java +++ b/common/common-flow/src/main/java/apelet/common/flow/service/impl/FlowWorkOrderServiceImpl.java @@ -17,6 +17,7 @@ import apelet.common.flow.model.FlowWorkOrder; import apelet.common.flow.model.FlowWorkOrderExt; import apelet.common.flow.service.FlowApiService; import apelet.common.flow.service.FlowEntryService; +import apelet.common.flow.service.FlowTaskInstanceExtService; import apelet.common.flow.service.FlowWorkOrderService; import apelet.common.flow.util.BaseFlowIdentityExtHelper; import apelet.common.flow.util.FlowCustomExtFactory; @@ -61,6 +62,8 @@ public class FlowWorkOrderServiceImpl extends BaseService i @Autowired private FlowEntryService flowEntryService; @Autowired + private FlowTaskInstanceExtService flowTaskInstanceExtService; + @Autowired private CommonRedisUtil commonRedisUtil; /** @@ -318,35 +321,15 @@ public class FlowWorkOrderServiceImpl extends BaseService i new LambdaQueryWrapper().in(FlowWorkOrderExt::getWorkOrderId, workOrderIds)); } - @Transactional(rollbackFor = Exception.class) @Override - public void saveTaskTitle(Long workOrderId, String taskKey, String title) { - if (workOrderId == null || StrUtil.isBlank(taskKey) || StrUtil.isBlank(title)) { - return; - } - FlowWorkOrderExt existExt = this.getFlowWorkOrderExtByWorkOrderId(workOrderId); - JSONObject titleJson = existExt == null || StrUtil.isBlank(existExt.getTitleJson()) - ? new JSONObject() : JSON.parseObject(existExt.getTitleJson()); - // 同一实例的每个节点各写各的条目,这里必须是合并写入,整串覆盖会抹掉其他节点已写的标题 - titleJson.put(taskKey, title); - if (existExt == null) { - // 工单扩展行并非随工单必建(只有草稿路径会建),首次写入标题时需要补一行 - FlowWorkOrder flowWorkOrder = flowWorkOrderMapper.selectById(workOrderId); - FlowWorkOrderExt newExt = flowWorkOrder == null - ? new FlowWorkOrderExt() : BeanUtil.copyProperties(flowWorkOrder, FlowWorkOrderExt.class); - newExt.setId(idGenerator.nextLongId()); - newExt.setWorkOrderId(workOrderId); - newExt.setTitleJson(titleJson.toJSONString()); - flowWorkOrderExtMapper.insert(newExt); - return; + public List getListByWorkOrderIdAfter(Long cursorWorkOrderId, int limit) { + LambdaQueryWrapper qw = new LambdaQueryWrapper<>(); + if (cursorWorkOrderId != null) { + qw.gt(FlowWorkOrder::getWorkOrderId, cursorWorkOrderId); } - // 只更新 title_json,避免把 draft_data / business_data 一并覆盖 - FlowWorkOrderExt updateExt = new FlowWorkOrderExt(); - updateExt.setId(existExt.getId()); - updateExt.setTitleJson(titleJson.toJSONString()); - updateExt.setUpdateTime(new Date()); - updateExt.setUpdateUserId(TokenData.takeFromRequest() == null ? null : TokenData.takeFromRequest().getUserId()); - flowWorkOrderExtMapper.updateById(updateExt); + qw.orderByAsc(FlowWorkOrder::getWorkOrderId); + qw.last("LIMIT " + Math.max(limit, 1)); + return flowWorkOrderMapper.selectList(qw); } @Transactional(rollbackFor = Exception.class) @@ -357,6 +340,9 @@ public class FlowWorkOrderServiceImpl extends BaseService i return r; } flowWorkOrderMapper.deleteById(flowWorkOrder.getWorkOrderId()); + // 工单是逻辑删除,act_hi_taskinst 里的任务行仍在;节点扩展若不跟着删, + // 会搜出一张已删除的单据,而列表里那行又没有标题。 + flowTaskInstanceExtService.deleteByProcessInstanceId(flowWorkOrder.getProcessInstanceId()); return CallResult.ok(); } diff --git a/common/common-flow/src/main/java/apelet/common/flow/vo/FlowTaskTitleBackfillVo.java b/common/common-flow/src/main/java/apelet/common/flow/vo/FlowTaskTitleBackfillVo.java new file mode 100644 index 0000000..542b637 --- /dev/null +++ b/common/common-flow/src/main/java/apelet/common/flow/vo/FlowTaskTitleBackfillVo.java @@ -0,0 +1,75 @@ +package apelet.common.flow.vo; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +/** + * 节点标题回填的执行结果,便于通过 curl 直接查看。 + * + * @author chenchuchuan + * @date 2026-10-14 + */ +@Data +@Schema(description = "节点标题回填结果") +public class FlowTaskTitleBackfillVo { + + /** + * 本批处理的工单(实例)数。 + */ + @Schema(description = "本批处理的工单数") + private Integer instanceCount; + + /** + * 本批遇到的 (实例, 节点) 总数。 + */ + @Schema(description = "本批遇到的(实例,节点)总数") + private Integer nodeCount; + + /** + * 实际写入的标题条数。 + */ + @Schema(description = "写入条数") + private Integer savedCount; + + /** + * 已有标题行、直接跳过的条数。 + */ + @Schema(description = "已有标题行跳过的条数") + private Integer skippedExistCount; + + /** + * 算不出标题(非在线表单 / 模板为空 / 业务数据取不到)而跳过的条数。 + */ + @Schema(description = "算不出标题跳过的条数") + private Integer skippedNoTitleCount; + + /** + * 单条处理异常的次数。异常不会中断整体回填。 + */ + @Schema(description = "异常次数") + private Integer failedCount; + + /** + * 下一批的游标。为 null 表示已处理完。 + */ + @Schema(description = "下一批游标,null 表示已跑完") + private Long nextCursor; + + /** + * 是否已经处理完所有工单。 + */ + @Schema(description = "是否已跑完") + private Boolean finished; + + /** + * 是否为试运行(只统计不写库)。 + */ + @Schema(description = "是否试运行") + private Boolean dryRun; + + /** + * 本次请求耗时(毫秒)。 + */ + @Schema(description = "耗时毫秒") + private Long elapsedMs; +} -- 2.9.0.windows.1 From 73efdd4df78ad972411afa59f4008125f2e2bc87 Mon Sep 17 00:00:00 2001 From: chenchuchuan <13554600537@163.com> Date: Thu, 15 Oct 2026 13:45:24 +0800 Subject: [PATCH 3/4] =?UTF-8?q?refactor(flow):=20=E7=AE=80=E5=8C=96?= =?UTF-8?q?=E6=A0=87=E9=A2=98=E8=A7=A3=E6=9E=90=E9=80=BB=E8=BE=91=E5=B9=B6?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E6=9C=AA=E8=A7=A3=E6=9E=90=E6=A0=87=E8=AE=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 移除标题解析中对 FlowTaskExt、FlowEntry、FlowEntryPublish 的前置条件判断,标题只认 zz_flow_task_instance_ext 落库值 - 删除 FlowApiServiceImpl 和 FlowOperationController 中冗余的批量预加载逻辑,减少不必要的数据库查询 - 新增 title_incomplete 字段,当标题中残留未解析的 ${...} 占位符时自动标记 - FlowTaskInstanceExtMapper.xml 的 upsert 语句增加 title_incomplete 字段的插入与更新 - FlowTaskTitleBackfillServiceImpl 回填时统计 incomplete 条数,FlowTaskTitleBackfillVo 新增 incompleteCount 字段 - FlowConstant 中新增 TITLE_PLACEHOLDER_PREFIX 常量用于占位符检测 --- .../apelet/common/flow/constant/FlowConstant.java | 7 +++ .../flow/controller/FlowOperationController.java | 61 ++++------------------ .../flow/dao/mapper/FlowTaskInstanceExtMapper.xml | 10 ++-- .../common/flow/model/FlowTaskInstanceExt.java | 7 +++ .../flow/service/impl/FlowApiServiceImpl.java | 17 ++---- .../impl/FlowTaskInstanceExtServiceImpl.java | 5 ++ .../impl/FlowTaskTitleBackfillServiceImpl.java | 7 +++ .../common/flow/vo/FlowTaskTitleBackfillVo.java | 7 +++ 8 files changed, 53 insertions(+), 68 deletions(-) diff --git a/common/common-flow/src/main/java/apelet/common/flow/constant/FlowConstant.java b/common/common-flow/src/main/java/apelet/common/flow/constant/FlowConstant.java index faaf71c..6c4dc8f 100644 --- a/common/common-flow/src/main/java/apelet/common/flow/constant/FlowConstant.java +++ b/common/common-flow/src/main/java/apelet/common/flow/constant/FlowConstant.java @@ -39,6 +39,13 @@ public class FlowConstant { public static final String SUBMIT_USER_VAR = "submitUser"; /** + * 标题模板里未解析占位符的起始标记。 + *

resolveTitle 对"占位符取不到值"是静默处理的 —— 不删不报错,把 ${xxx} 原样留在标题里 + * (最常见的原因是该实例的业务数据已经不存在了)。写入标题时据此打 title_incomplete 标记。

+ */ + public static final String TITLE_PLACEHOLDER_PREFIX = "${"; + + /** * 多任务拒绝数量变量。 */ public static final String MULTI_REFUSE_COUNT_VAR = "multiRefuseCount"; diff --git a/common/common-flow/src/main/java/apelet/common/flow/controller/FlowOperationController.java b/common/common-flow/src/main/java/apelet/common/flow/controller/FlowOperationController.java index 4b39b89..d6ac6aa 100644 --- a/common/common-flow/src/main/java/apelet/common/flow/controller/FlowOperationController.java +++ b/common/common-flow/src/main/java/apelet/common/flow/controller/FlowOperationController.java @@ -853,18 +853,6 @@ public class FlowOperationController { // 节点标题按实例批量预载(一次 IN 查询覆盖整页),避免逐行查询造成 N+1。 Map taskInstanceExtMap = flowTaskInstanceExtService.getMapByProcessInstanceIds(instanceIdSet); - Set processDefinitionIdSet = taskInstanceList.stream() - .map(HistoricTaskInstance::getProcessDefinitionId).collect(Collectors.toSet()); - List flowEntryPublishList = - flowEntryService.getFlowEntryPublishList(processDefinitionIdSet); - Map flowEntryPublishMap = - flowEntryPublishList.stream().collect(Collectors.toMap(FlowEntryPublish::getProcessDefinitionId, c -> c)); - Set entryIdSet = flowEntryPublishList.stream() - .map(FlowEntryPublish::getEntryId).filter(Objects::nonNull).collect(Collectors.toSet()); - Map flowEntryMap = flowEntryService.listByIds(entryIdSet).stream() - .collect(Collectors.toMap(FlowEntry::getEntryId, e -> e)); - Map flowTaskExtMap = flowTaskExtService.getByProcessDefinitionId(processDefinitionIdSet).stream() - .collect(Collectors.toMap(t -> t.getProcessDefinitionId() + ":" + t.getTaskId(), t -> t, (k1, k2) -> k1)); resultList.forEach(result -> { String instanceId = result.get(INSTANCE_ID).toString(); HistoricProcessInstance instance = instanceMap.get(instanceId); @@ -878,19 +866,11 @@ public class FlowOperationController { FlowWorkOrder flowWorkOrder = workOrderMap.get(instanceId); if (flowWorkOrder != null) { result.put("workOrderCode", flowWorkOrder.getWorkOrderCode()); - String processDefinitionId = result.get("processDefinitionId").toString(); - FlowEntryPublish flowEntryPublish = flowEntryPublishMap.get(processDefinitionId); - FlowTaskExt flowTaskExt = flowTaskExtMap.get( - processDefinitionId + ":" + result.get("taskDefinitionKey")); - if (flowEntryPublish != null && flowTaskExt != null) { - FlowEntry flowEntry = flowEntryMap.get(flowEntryPublish.getEntryId()); - if (flowEntry != null) { - Object taskDefinitionKey = result.get("taskDefinitionKey"); - String taskKey = taskDefinitionKey == null ? null : taskDefinitionKey.toString(); - result.put("title", flowApiService.resolveTitleCached(flowWorkOrder, taskKey, - taskKey == null ? null : taskInstanceExtMap.get(instanceId + ":" + taskKey))); - } - } + // 标题只认 zz_flow_task_instance_ext 的落库值:没有标题行就是空 + Object taskDefinitionKey = result.get("taskDefinitionKey"); + String taskKey = taskDefinitionKey == null ? null : taskDefinitionKey.toString(); + result.put("title", flowApiService.resolveTitleCached(flowWorkOrder, taskKey, + taskKey == null ? null : taskInstanceExtMap.get(instanceId + ":" + taskKey))); } }); Set taskIdSet = @@ -949,22 +929,11 @@ public class FlowOperationController { Map taskInstanceExtMap = flowTaskInstanceExtService.getMapByProcessInstanceIds(instanceIdSet); Set processDefinitionIdSet = pageData.getDataList().stream() .map(HistoricProcessInstance::getProcessDefinitionId).collect(Collectors.toSet()); - Map flowEntryPublishMap = new HashMap<>(); - Map flowEntryMap = new HashMap<>(); - Map flowTaskExtMap = new HashMap<>(); - // 流程实例列表使用起始节点的标题模板。 + // 流程实例列表使用起始节点的标题,首节点 taskKey 存在发布版本的 initTaskInfo 里。 Map initTaskKeyMap = new HashMap<>(); if (CollUtil.isNotEmpty(processDefinitionIdSet)) { List flowEntryPublishList = flowEntryService.getFlowEntryPublishList(processDefinitionIdSet); - flowEntryPublishMap.putAll(flowEntryPublishList.stream() - .collect(Collectors.toMap(FlowEntryPublish::getProcessDefinitionId, c -> c))); - Set entryIdSet = flowEntryPublishList.stream() - .map(FlowEntryPublish::getEntryId).filter(Objects::nonNull).collect(Collectors.toSet()); - if (CollUtil.isNotEmpty(entryIdSet)) { - flowEntryMap.putAll(flowEntryService.listByIds(entryIdSet).stream() - .collect(Collectors.toMap(FlowEntry::getEntryId, e -> e))); - } for (FlowEntryPublish flowEntryPublish : flowEntryPublishList) { TaskInfoVo initTaskInfo = StrUtil.isBlank(flowEntryPublish.getInitTaskInfo()) ? null : JSON.parseObject(flowEntryPublish.getInitTaskInfo(), TaskInfoVo.class); @@ -972,8 +941,6 @@ public class FlowOperationController { initTaskKeyMap.put(flowEntryPublish.getProcessDefinitionId(), initTaskInfo.getTaskKey()); } } - flowTaskExtMap.putAll(flowTaskExtService.getByProcessDefinitionId(processDefinitionIdSet).stream() - .collect(Collectors.toMap(t -> t.getProcessDefinitionId() + ":" + t.getTaskId(), t -> t, (k1, k2) -> k1))); } List> resultList = new LinkedList<>(); pageData.getDataList().forEach(instance -> { @@ -987,18 +954,10 @@ public class FlowOperationController { if (workOrder != null) { data.put("workOrderCode", workOrder.getWorkOrderCode()); data.put("flowStatus", workOrder.getFlowStatus()); - FlowEntryPublish flowEntryPublish = flowEntryPublishMap.get(instance.getProcessDefinitionId()); - FlowTaskExt flowTaskExt = flowTaskExtMap.get( - instance.getProcessDefinitionId() + ":" + initTaskKeyMap.get(instance.getProcessDefinitionId())); - if (flowEntryPublish != null && flowTaskExt != null) { - FlowEntry flowEntry = flowEntryMap.get(flowEntryPublish.getEntryId()); - if (flowEntry != null) { - // 流程实例列表使用起始节点的标题。 - String initTaskKey = initTaskKeyMap.get(instance.getProcessDefinitionId()); - data.put("title", flowApiService.resolveTitleCached(workOrder, initTaskKey, - initTaskKey == null ? null : taskInstanceExtMap.get(instance.getId() + ":" + initTaskKey))); - } - } + // 流程实例列表使用起始节点的标题;标题只认落库值,没有标题行就是空 + String initTaskKey = initTaskKeyMap.get(instance.getProcessDefinitionId()); + data.put("title", flowApiService.resolveTitleCached(workOrder, initTaskKey, + initTaskKey == null ? null : taskInstanceExtMap.get(instance.getId() + ":" + initTaskKey))); } resultList.add(data); }); diff --git a/common/common-flow/src/main/java/apelet/common/flow/dao/mapper/FlowTaskInstanceExtMapper.xml b/common/common-flow/src/main/java/apelet/common/flow/dao/mapper/FlowTaskInstanceExtMapper.xml index 9cfe484..751d890 100644 --- a/common/common-flow/src/main/java/apelet/common/flow/dao/mapper/FlowTaskInstanceExtMapper.xml +++ b/common/common-flow/src/main/java/apelet/common/flow/dao/mapper/FlowTaskInstanceExtMapper.xml @@ -9,6 +9,7 @@ + @@ -17,13 +18,14 @@ INSERT INTO zz_flow_task_instance_ext - (id, tenant_id, app_code, process_instance_id, process_definition_id, task_key, title, - create_time, create_user_id, update_time, update_user_id) + (id, tenant_id, app_code, process_instance_id, process_definition_id, task_key, + title, title_incomplete, create_time, create_user_id, update_time, update_user_id) VALUES - (#{id}, #{tenantId}, #{appCode}, #{processInstanceId}, #{processDefinitionId}, #{taskKey}, #{title}, - #{createTime}, #{createUserId}, #{updateTime}, #{updateUserId}) + (#{id}, #{tenantId}, #{appCode}, #{processInstanceId}, #{processDefinitionId}, #{taskKey}, + #{title}, #{titleIncomplete}, #{createTime}, #{createUserId}, #{updateTime}, #{updateUserId}) ON DUPLICATE KEY UPDATE title = VALUES(title), + title_incomplete = VALUES(title_incomplete), process_definition_id = VALUES(process_definition_id), update_time = VALUES(update_time), update_user_id = VALUES(update_user_id) diff --git a/common/common-flow/src/main/java/apelet/common/flow/model/FlowTaskInstanceExt.java b/common/common-flow/src/main/java/apelet/common/flow/model/FlowTaskInstanceExt.java index 864373c..18aa027 100644 --- a/common/common-flow/src/main/java/apelet/common/flow/model/FlowTaskInstanceExt.java +++ b/common/common-flow/src/main/java/apelet/common/flow/model/FlowTaskInstanceExt.java @@ -61,6 +61,13 @@ public class FlowTaskInstanceExt { private String title; /** + * 标题是否未完整解析:0-完整;1-模板里还有没解析出来的 ${...} 占位符。 + *

resolveTitle 取不到值时是静默保留占位符的,靠这个标记才能事后筛出没算全的标题。

+ */ + @TableField(value = "title_incomplete") + private Integer titleIncomplete; + + /** * 创建时间。 */ @TableField(value = "create_time") diff --git a/common/common-flow/src/main/java/apelet/common/flow/service/impl/FlowApiServiceImpl.java b/common/common-flow/src/main/java/apelet/common/flow/service/impl/FlowApiServiceImpl.java index 8809994..bbc5930 100644 --- a/common/common-flow/src/main/java/apelet/common/flow/service/impl/FlowApiServiceImpl.java +++ b/common/common-flow/src/main/java/apelet/common/flow/service/impl/FlowApiServiceImpl.java @@ -982,11 +982,6 @@ public class FlowApiServiceImpl implements FlowApiService { flowEntryService.getFlowEntryPublishList(processDefinitionIdSet); Map flowEntryPublishMap = flowEntryPublishList.stream().collect(Collectors.toMap(FlowEntryPublish::getProcessDefinitionId, c -> c)); - // 批量加载流程对象,用于判断在线表单(bindFormType=0) - Set entryIdSet = flowEntryPublishList.stream() - .map(FlowEntryPublish::getEntryId).filter(Objects::nonNull).collect(Collectors.toSet()); - Map flowEntryMap = flowEntryService.listByIds(entryIdSet).stream() - .collect(Collectors.toMap(FlowEntry::getEntryId, e -> e)); List instanceList = this.getProcessInstanceList(procInstanceIdSet); Map instanceMap = instanceList.stream().collect(Collectors.toMap(ProcessInstance::getId, c -> c)); @@ -1000,8 +995,6 @@ public class FlowApiServiceImpl implements FlowApiService { // 节点标题按实例批量预载(一次 IN 查询覆盖整页),避免逐行查询造成 N+1。 Map taskInstanceExtMap = flowTaskInstanceExtService.getMapByProcessInstanceIds(procInstanceIdSet); - List allFlowTaskExtList = flowTaskExtService.getByProcessDefinitionId(processDefinitionIdSet); - Map flowTaskExtMap = allFlowTaskExtList.stream().collect(Collectors.toMap(t -> t.getProcessDefinitionId() + ":" + t.getTaskId(), t -> t, (k1, k2) -> k1)); Map multiInstanceTaskMap = new HashMap<>(); for (Task task : taskList) { FlowTaskVo flowTaskVo = new FlowTaskVo(); @@ -1029,12 +1022,10 @@ public class FlowApiServiceImpl implements FlowApiService { flowTaskVo.setIsDraft(flowWorkOrder.getFlowStatus().equals(FlowTaskStatus.DRAFT)); flowTaskVo.setWorkOrderCode(flowWorkOrder.getWorkOrderCode()); } - FlowTaskExt flowTaskExt = flowTaskExtMap.get(task.getProcessDefinitionId() + ":" + task.getTaskDefinitionKey()); - FlowEntry flowEntry = flowEntryMap.get(flowEntryPublishMap.get(task.getProcessDefinitionId()).getEntryId()); - if (flowTaskExt != null && flowEntry != null) { - flowTaskVo.setTitle(this.resolveTitleCached(flowWorkOrder, task.getTaskDefinitionKey(), - taskInstanceExtMap.get(task.getProcessInstanceId() + ":" + task.getTaskDefinitionKey()))); - } + // 标题只以 zz_flow_task_instance_ext 的落库值为准:没有标题行就是空, + // 不需要再按"节点配没配模板""是不是在线表单"做前置判断(那两个条件对标题行本身没有约束力)。 + flowTaskVo.setTitle(this.resolveTitleCached(flowWorkOrder, task.getTaskDefinitionKey(), + taskInstanceExtMap.get(task.getProcessInstanceId() + ":" + task.getTaskDefinitionKey()))); flowTaskVoList.add(flowTaskVo); } Set loginNameSet = flowTaskVoList.stream() diff --git a/common/common-flow/src/main/java/apelet/common/flow/service/impl/FlowTaskInstanceExtServiceImpl.java b/common/common-flow/src/main/java/apelet/common/flow/service/impl/FlowTaskInstanceExtServiceImpl.java index 224269a..d44ae85 100644 --- a/common/common-flow/src/main/java/apelet/common/flow/service/impl/FlowTaskInstanceExtServiceImpl.java +++ b/common/common-flow/src/main/java/apelet/common/flow/service/impl/FlowTaskInstanceExtServiceImpl.java @@ -6,6 +6,7 @@ import apelet.common.core.base.service.BaseService; import apelet.common.core.constant.ApplicationConstant; import apelet.common.core.object.TokenData; import apelet.common.core.util.DefaultDataSourceResolver; +import apelet.common.flow.constant.FlowConstant; import apelet.common.flow.dao.FlowTaskInstanceExtMapper; import apelet.common.flow.model.FlowTaskInstanceExt; import apelet.common.flow.service.FlowTaskInstanceExtService; @@ -73,6 +74,10 @@ public class FlowTaskInstanceExtServiceImpl extends BaseService最常见的原因是该实例的业务数据已经不存在了。这些行的 title_incomplete 为 1。

+ */ + @Schema(description = "标题未完整解析的条数") + private Integer incompleteCount; + + /** * 算不出标题(非在线表单 / 模板为空 / 业务数据取不到)而跳过的条数。 */ @Schema(description = "算不出标题跳过的条数") -- 2.9.0.windows.1 From 23209830b503c09b198e38d330316823bc534949 Mon Sep 17 00:00:00 2001 From: chenchuchuan <13554600537@163.com> Date: Fri, 16 Oct 2026 09:48:38 +0800 Subject: [PATCH 4/4] =?UTF-8?q?feat(botp):=20=E6=96=B0=E5=A2=9E=E5=8D=95?= =?UTF-8?q?=E6=8D=AE=E8=BD=AC=E6=8D=A2=E5=B9=B3=E5=8F=B0=E6=A0=B8=E5=BF=83?= =?UTF-8?q?=E6=A8=A1=E5=9D=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增单据转换插件抽象基类 AbstractTransformPlugIn - 实现字段映射策略模式(映射、常量、计算公式) - 新增单据基础服务 BillBaseService,支持保存、提交、详情、删除 - 新增单据基础控制器 BillBaseController 及通用 CRUD 接口 - 新增单据转换核心引擎 BotpService 及转换关系数据模型 - 新增采购申请下推回写已订货数量插件 BackPurReqTransformPlugIn - 新增单据转换关系及分录实体 BillRelation、BillRelationEntry --- common/common-botp/pom.xml | 71 +++ .../common/botp/controller/BillBaseController.java | 123 +++++ .../ConvertFieldmappingEntryController.java | 51 ++ .../controller/ConvertPluginEntryController.java | 53 ++ .../botp/controller/ConvertRelationController.java | 155 ++++++ .../controller/ConvertRelationEntryController.java | 98 ++++ .../botp/controller/ConvertRuleController.java | 192 +++++++ .../botp/controller/SysMenuqqController.java | 13 + .../apelet/common/botp/dao/BillBaseDaoMapper.java | 12 + .../botp/dao/ConvertFieldmappingEntryMapper.java | 15 + .../common/botp/dao/ConvertPluginEntryMapper.java | 15 + .../botp/dao/ConvertRelationEntryMapper.java | 15 + .../common/botp/dao/ConvertRelationMapper.java | 31 ++ .../apelet/common/botp/dao/ConvertRuleMapper.java | 21 + .../apelet/common/botp/dao/SysMenuqqMapper.java | 7 + .../dao/mapper/ConvertFieldmappingEntryMapper.xml | 7 + .../botp/dao/mapper/ConvertPluginEntryMapper.xml | 7 + .../botp/dao/mapper/ConvertRelationEntryMapper.xml | 7 + .../botp/dao/mapper/ConvertRelationMapper.xml | 31 ++ .../common/botp/dao/mapper/ConvertRuleMapper.xml | 13 + .../common/botp/dao/mapper/SysMenuqqMapper.xml | 7 + .../apelet/common/botp/db/object/DataFilter.java | 139 +++++ .../common/botp/db/object/DataFilterItem.java | 28 + .../apelet/common/botp/db/object/InsertData.java | 18 + .../common/botp/db/object/ObjectSqlData.java | 18 + .../java/apelet/common/botp/db/util/DbUtil.java | 185 +++++++ .../common/botp/dto/ConvertRelationDelDto.java | 36 ++ .../apelet/common/botp/dto/ConvertRelationDto.java | 39 ++ .../common/botp/dto/ConvertRelationEntryDto.java | 45 ++ .../common/botp/dto/ConvertRelationListDto.java | 44 ++ .../apelet/common/botp/dto/ConvertRuleDto.java | 37 ++ .../apelet/common/botp/dto/TransformResultDto.java | 45 ++ .../java/apelet/common/botp/dto/TransfromDto.java | 29 + .../common/botp/mapper/BillBaseModelMapper.java | 11 + .../java/apelet/common/botp/model/AllField.java | 39 ++ .../apelet/common/botp/model/BillBaseModel.java | 13 + .../botp/model/ConvertFieldmappingEntry.java | 93 ++++ .../common/botp/model/ConvertPluginEntry.java | 72 +++ .../apelet/common/botp/model/ConvertRelation.java | 47 ++ .../common/botp/model/ConvertRelationEntry.java | 63 +++ .../java/apelet/common/botp/model/ConvertRule.java | 223 ++++++++ .../apelet/common/botp/model/GetSearchList.java | 79 +++ .../java/apelet/common/botp/model/SysMenuqq.java | 96 ++++ .../botp/plugin/AbstractTransformPlugIn.java | 55 ++ .../botp/plugin/BackPurReqTransformPlugIn.java | 56 ++ .../botp/plugin/PurorderTransformPlugIn.java | 35 ++ .../common/botp/plugin/ReverseWritingPlugIn.java | 198 +++++++ .../common/botp/plugin/entity/BillEntity.java | 19 + .../apelet/common/botp/plugin/entity/BotpRule.java | 38 ++ .../common/botp/service/IBillBaseService.java | 80 +++ .../service/IConvertFieldmappingEntryService.java | 17 + .../botp/service/IConvertPluginEntryService.java | 16 + .../botp/service/IConvertRelationEntryService.java | 22 + .../botp/service/IConvertRelationService.java | 30 + .../common/botp/service/IConvertRuleService.java | 90 +++ .../common/botp/service/ISysMenuqqService.java | 27 + .../common/botp/service/execute/BotpService.java | 604 +++++++++++++++++++++ .../botp/service/execute/entity/BillData.java | 21 + .../botp/service/execute/entity/BillRelation.java | 54 ++ .../service/execute/entity/BillRelationEntry.java | 64 +++ .../service/execute/entity/BtpTransformResult.java | 23 + .../execute/entity/ConvertColumnConfig.java | 49 ++ .../botp/service/execute/entity/ConvertConfig.java | 31 ++ .../botp/service/execute/entity/MetaColumn.java | 53 ++ .../botp/service/execute/entity/MetaTable.java | 39 ++ .../BotpMappingCalculationFormulaMapping.java | 73 +++ .../execute/mapping/BotpMappingContext.java | 42 ++ .../execute/mapping/BotpMappingStrategy.java | 19 + .../mapping/BotpMappingStrategyConstant.java | 28 + .../mapping/BotpMappingStrategyMapping.java | 51 ++ .../common/botp/service/impl/BillBaseService.java | 344 ++++++++++++ .../impl/ConvertFieldmappingEntryServiceImpl.java | 75 +++ .../impl/ConvertPluginEntryServiceImpl.java | 75 +++ .../impl/ConvertRelationEntryServiceImpl.java | 70 +++ .../service/impl/ConvertRelationServiceImpl.java | 184 +++++++ .../botp/service/impl/ConvertRuleServiceImpl.java | 529 ++++++++++++++++++ .../botp/service/impl/SysMenuqqServiceImpl.java | 57 ++ .../java/apelet/common/botp/util/Constant.java | 17 + .../main/resources/templates/controller.java.ftl | 54 ++ .../resources/templates/controllertest.java.ftl | 143 +++++ .../src/main/resources/templates/dto.java.ftl | 17 + .../src/main/resources/templates/dtotest.java.ftl | 25 + .../src/main/resources/templates/entity.java.ftl | 158 ++++++ .../src/main/resources/templates/entity.kt.ftl | 122 +++++ .../src/main/resources/templates/entity1.java.ftl | 152 ++++++ .../src/main/resources/templates/from.vue.ftl | 0 .../src/main/resources/templates/list.vue.ftl | 535 ++++++++++++++++++ .../src/main/resources/templates/mapper.java.ftl | 26 + .../src/main/resources/templates/mapper.xml.ftl | 39 ++ .../src/main/resources/templates/service.java.ftl | 20 + .../main/resources/templates/serviceImpl.java.ftl | 181 ++++++ .../resources/templates/serviceImpltest.java.ftl | 181 ++++++ .../main/resources/templates/servicetest.java.ftl | 20 + .../src/main/resources/templates/vo.java.ftl | 16 + 94 files changed, 7217 insertions(+) create mode 100644 common/common-botp/pom.xml create mode 100644 common/common-botp/src/main/java/apelet/common/botp/controller/BillBaseController.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/controller/ConvertFieldmappingEntryController.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/controller/ConvertPluginEntryController.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/controller/ConvertRelationController.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/controller/ConvertRelationEntryController.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/controller/ConvertRuleController.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/controller/SysMenuqqController.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/dao/BillBaseDaoMapper.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/dao/ConvertFieldmappingEntryMapper.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/dao/ConvertPluginEntryMapper.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/dao/ConvertRelationEntryMapper.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/dao/ConvertRelationMapper.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/dao/ConvertRuleMapper.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/dao/SysMenuqqMapper.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/dao/mapper/ConvertFieldmappingEntryMapper.xml create mode 100644 common/common-botp/src/main/java/apelet/common/botp/dao/mapper/ConvertPluginEntryMapper.xml create mode 100644 common/common-botp/src/main/java/apelet/common/botp/dao/mapper/ConvertRelationEntryMapper.xml create mode 100644 common/common-botp/src/main/java/apelet/common/botp/dao/mapper/ConvertRelationMapper.xml create mode 100644 common/common-botp/src/main/java/apelet/common/botp/dao/mapper/ConvertRuleMapper.xml create mode 100644 common/common-botp/src/main/java/apelet/common/botp/dao/mapper/SysMenuqqMapper.xml create mode 100644 common/common-botp/src/main/java/apelet/common/botp/db/object/DataFilter.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/db/object/DataFilterItem.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/db/object/InsertData.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/db/object/ObjectSqlData.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/db/util/DbUtil.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/dto/ConvertRelationDelDto.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/dto/ConvertRelationDto.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/dto/ConvertRelationEntryDto.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/dto/ConvertRelationListDto.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/dto/ConvertRuleDto.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/dto/TransformResultDto.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/dto/TransfromDto.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/mapper/BillBaseModelMapper.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/model/AllField.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/model/BillBaseModel.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/model/ConvertFieldmappingEntry.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/model/ConvertPluginEntry.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/model/ConvertRelation.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/model/ConvertRelationEntry.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/model/ConvertRule.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/model/GetSearchList.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/model/SysMenuqq.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/plugin/AbstractTransformPlugIn.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/plugin/BackPurReqTransformPlugIn.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/plugin/PurorderTransformPlugIn.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/plugin/ReverseWritingPlugIn.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/plugin/entity/BillEntity.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/plugin/entity/BotpRule.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/service/IBillBaseService.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/service/IConvertFieldmappingEntryService.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/service/IConvertPluginEntryService.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/service/IConvertRelationEntryService.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/service/IConvertRelationService.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/service/IConvertRuleService.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/service/ISysMenuqqService.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/service/execute/BotpService.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/service/execute/entity/BillData.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/service/execute/entity/BillRelation.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/service/execute/entity/BillRelationEntry.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/service/execute/entity/BtpTransformResult.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/service/execute/entity/ConvertColumnConfig.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/service/execute/entity/ConvertConfig.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/service/execute/entity/MetaColumn.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/service/execute/entity/MetaTable.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/service/execute/mapping/BotpMappingCalculationFormulaMapping.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/service/execute/mapping/BotpMappingContext.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/service/execute/mapping/BotpMappingStrategy.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/service/execute/mapping/BotpMappingStrategyConstant.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/service/execute/mapping/BotpMappingStrategyMapping.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/service/impl/BillBaseService.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/service/impl/ConvertFieldmappingEntryServiceImpl.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/service/impl/ConvertPluginEntryServiceImpl.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/service/impl/ConvertRelationEntryServiceImpl.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/service/impl/ConvertRelationServiceImpl.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/service/impl/ConvertRuleServiceImpl.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/service/impl/SysMenuqqServiceImpl.java create mode 100644 common/common-botp/src/main/java/apelet/common/botp/util/Constant.java create mode 100644 common/common-botp/src/main/resources/templates/controller.java.ftl create mode 100644 common/common-botp/src/main/resources/templates/controllertest.java.ftl create mode 100644 common/common-botp/src/main/resources/templates/dto.java.ftl create mode 100644 common/common-botp/src/main/resources/templates/dtotest.java.ftl create mode 100644 common/common-botp/src/main/resources/templates/entity.java.ftl create mode 100644 common/common-botp/src/main/resources/templates/entity.kt.ftl create mode 100644 common/common-botp/src/main/resources/templates/entity1.java.ftl create mode 100644 common/common-botp/src/main/resources/templates/from.vue.ftl create mode 100644 common/common-botp/src/main/resources/templates/list.vue.ftl create mode 100644 common/common-botp/src/main/resources/templates/mapper.java.ftl create mode 100644 common/common-botp/src/main/resources/templates/mapper.xml.ftl create mode 100644 common/common-botp/src/main/resources/templates/service.java.ftl create mode 100644 common/common-botp/src/main/resources/templates/serviceImpl.java.ftl create mode 100644 common/common-botp/src/main/resources/templates/serviceImpltest.java.ftl create mode 100644 common/common-botp/src/main/resources/templates/servicetest.java.ftl create mode 100644 common/common-botp/src/main/resources/templates/vo.java.ftl diff --git a/common/common-botp/pom.xml b/common/common-botp/pom.xml new file mode 100644 index 0000000..1fc7b12 --- /dev/null +++ b/common/common-botp/pom.xml @@ -0,0 +1,71 @@ + + + + common + apelet + 1.0.0 + + 4.0.0 + + common-botp + jar + 1.0.0 + + + + apelet + common-core + 1.0.0 + + + apelet + common-generator + 1.0.3 + + + apelet + common-online + 1.0.3 + compile + + + apelet + common-dbutil + 1.0.0 + compile + + + io.swagger.core.v3 + swagger-annotations + 2.2.19 + compile + + + apelet + common-orm + 1.0.2 + compile + + + apelet + common-sequence + 1.0.0 + compile + + + org.jodd + jodd-core + 5.1.6 + compile + + + org.jetbrains + annotations + 24.0.1 + compile + + + + diff --git a/common/common-botp/src/main/java/apelet/common/botp/controller/BillBaseController.java b/common/common-botp/src/main/java/apelet/common/botp/controller/BillBaseController.java new file mode 100644 index 0000000..6f127f9 --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/controller/BillBaseController.java @@ -0,0 +1,123 @@ +package apelet.common.botp.controller; + +import apelet.common.botp.service.IBillBaseService; +import apelet.common.core.annotation.MyRequestBody; +import apelet.common.core.base.controller.BaseController; +import apelet.common.core.object.*; +import apelet.common.core.util.MyPageUtil; +import cn.hutool.core.bean.BeanUtil; +import com.baomidou.mybatisplus.annotation.TableName; +import com.github.pagehelper.Page; +import org.apache.commons.lang3.ObjectUtils; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +/** + * @author Soon + * @version 1.0 + * Create by 2024/2/28 8:29 + */ +public abstract class BillBaseController extends BaseController { + + + + protected abstract IBillBaseService billservice(); + + /** + * 列表接口 + * @param m + * @param orderParam + * @param pageParam + * @param traceParamDto + * @return + */ + public ResponseResult listBill(M m, + MyOrderParam orderParam, + MyPageParam pageParam, + TraceParamDto traceParamDto + ) { + Page pageList = billservice().listBill(m,orderParam,pageParam,traceParamDto); + long totalCount = pageList.getTotal(); + MyPageData result = MyPageUtil.makeResponseData(pageList, totalCount); + + String tableName = m.getClass().getAnnotation(TableName.class).value(); + result.setTableName(tableName); + List dataList = result.getDataList(); + if (dataList.size()>0){ + List vos = new ArrayList<>(); + for (M m1 : dataList) { + M o = (M) BeanUtil.copyProperties(m1, m.getClass()); + vos.add(o); + } + MyPageData voData = BeanUtil.copyProperties(result, MyPageData.class); + voData.setDataList(vos); + voData.setTableName(tableName); + return ResponseResult.success(voData); + } + //正常的返回 + return ResponseResult.success(result); + } + + /** + * 单据保存接口,包括保存单据分录 + * @param m + * @param crDto + * @return + */ + public ResponseResult saveBill(M m, @MyRequestBody List crDto){ + billservice().saveBill(m,crDto); + return ResponseResult.success("新增成功"); + + } + + /** + * 单据提交接口 ,包括保存单据分录 + * @param processDefinitionKey 流程标识 + * @param m 单据实体 + * @param crDto 关联关系 + * @return + */ + public ResponseResult submitBill(String processDefinitionKey,M m, @MyRequestBody List crDto){ + billservice().submitBill(processDefinitionKey,m,crDto); + return ResponseResult.success("提交成功"); + } + + /** + * 单据提交接口 + * @param processDefinitionKey 流程标识 + * @param id 单据id + * @return + */ + public ResponseResult submitBillKey(String processDefinitionKey,Long id){ + billservice().submitBillKey(processDefinitionKey,id); + return ResponseResult.success("提交成功"); + } + + + /** + * 单据详情 + * @param id + * @return + */ + public ResponseResult detailBill(Long id){ + M m = billservice().detailBill((K) id); + if (ObjectUtils.isNotEmpty(m)){ + //获取vo实体 + V v = this.convertToVo(m, null); + return ResponseResult.success(v); + } + return (ResponseResult) ResponseResult.success("未查到相应数据,id为"+id); + } + + /** + * 删除单据,包括分录数据关联删除 + * @param ids id逗号隔开 + * @return + */ + public ResponseResult removeBillById(String ids){ + billservice().removeBillById(ids); + return ResponseResult.success("删除成功"); + } +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/controller/ConvertFieldmappingEntryController.java b/common/common-botp/src/main/java/apelet/common/botp/controller/ConvertFieldmappingEntryController.java new file mode 100644 index 0000000..4fe943e --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/controller/ConvertFieldmappingEntryController.java @@ -0,0 +1,51 @@ +package apelet.common.botp.controller; + + +import apelet.common.botp.model.ConvertFieldmappingEntry; +import apelet.common.botp.service.IConvertFieldmappingEntryService; +import apelet.common.core.annotation.MyRequestBody; +import apelet.common.core.object.*; +import apelet.common.core.util.MyPageUtil; +import com.github.pagehelper.Page; +import com.github.pagehelper.page.PageMethod; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +/** + * @author admin + * @since 2024-01-18 10:31:58 + */ +@RestController +@RequestMapping("/botp/ConvertFieldmappingEntry") +public class ConvertFieldmappingEntryController { + @Autowired + private IConvertFieldmappingEntryService IConvertFieldmappingEntryService; + + /** + * 分页查询 + * */ + @PostMapping(value = "/list") + public ResponseResult list(@MyRequestBody ConvertFieldmappingEntry convertFieldmappingEntry, + @MyRequestBody MyOrderParam orderParam, + @MyRequestBody MyPageParam pageParam) { + if (pageParam != null) { + PageMethod.startPage(pageParam.getPageNum(), pageParam.getPageSize()); + } + String orderBy = MyOrderParam.buildOrderBy(orderParam, ConvertFieldmappingEntry.class); + List list = + IConvertFieldmappingEntryService.getConvertFieldmappingEntryListWithRelation(convertFieldmappingEntry,orderBy); + long totalCount = 0L; + if (list instanceof Page) { + totalCount = ((Page) list).getTotal(); + } + MyPageData result = MyPageUtil.makeResponseData(list, totalCount); + //正常的返回 + return ResponseResult.success(result); + } + + +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/controller/ConvertPluginEntryController.java b/common/common-botp/src/main/java/apelet/common/botp/controller/ConvertPluginEntryController.java new file mode 100644 index 0000000..543f877 --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/controller/ConvertPluginEntryController.java @@ -0,0 +1,53 @@ +package apelet.common.botp.controller; + +import apelet.common.botp.model.ConvertPluginEntry; +import apelet.common.botp.service.IConvertPluginEntryService; +import apelet.common.core.annotation.MyRequestBody; +import apelet.common.core.object.*; +import apelet.common.core.util.MyPageUtil; +import com.github.pagehelper.Page; +import com.github.pagehelper.page.PageMethod; +import io.swagger.v3.oas.annotations.media.Schema; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +/** + * @author admin + * @since 2024-01-18 10:31:58 + */ +@RestController +@RequestMapping("/botp/ConvertPluginEntry") +public class ConvertPluginEntryController { + @Autowired + private IConvertPluginEntryService IConvertPluginEntryService; + + + /** + * 分页查询 + * */ + @PostMapping(value = "/list") + @Schema(description = "list") + public ResponseResult list(@MyRequestBody ConvertPluginEntry convertPluginEntry, + @MyRequestBody MyOrderParam orderParam, + @MyRequestBody MyPageParam pageParam) { + if (pageParam != null) { + PageMethod.startPage(pageParam.getPageNum(), pageParam.getPageSize()); + } + String orderBy = MyOrderParam.buildOrderBy(orderParam, ConvertPluginEntry.class); + List list = + IConvertPluginEntryService.getConvertPluginEntryListWithRelation(convertPluginEntry,orderBy); + long totalCount = 0L; + if (list instanceof Page) { + totalCount = ((Page) list).getTotal(); + } + MyPageData result = MyPageUtil.makeResponseData(list, totalCount); + //正常的返回 + return ResponseResult.success(result); + } + + +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/controller/ConvertRelationController.java b/common/common-botp/src/main/java/apelet/common/botp/controller/ConvertRelationController.java new file mode 100644 index 0000000..b558eeb --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/controller/ConvertRelationController.java @@ -0,0 +1,155 @@ +package apelet.common.botp.controller; + +import apelet.common.botp.model.ConvertRelation; +import apelet.common.botp.service.IConvertRelationService; +import apelet.common.core.annotation.MyRequestBody; +import apelet.common.core.constant.ErrorCodeEnum; +import apelet.common.core.object.*; +import apelet.common.core.util.MyPageUtil; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.github.pagehelper.Page; +import com.github.pagehelper.page.PageMethod; +import io.swagger.v3.oas.annotations.media.Schema; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +/** + * @author admin + * @since 2024-01-18 10:31:58 + */ +@RestController +@RequestMapping("/botp/ConvertRelation") +public class ConvertRelationController { + @Autowired + private IConvertRelationService IConvertRelationService; + + @RequestMapping("/transform") + public ResponseResult transform(JSONObject transformJson) { + List qq = new ArrayList<>(); + //转换规则Id + String botpId = transformJson.getString("botpId"); + + //源单据标识 + String srcBill = transformJson.getString("srcBill"); + + //目标单据标识 + String destBill = transformJson.getString("destBill"); + + //源单据ID + String srcBillId = transformJson.getString("srcBillId"); + + List transformList = IConvertRelationService.transform(botpId, srcBill, destBill, srcBillId); + return ResponseResult.success(transformList); + + } + + + @RequestMapping("/transformT") + public ResponseResult transformT(JSONObject transformJson) { + List qq = new ArrayList<>(); + //转换规则Id + String botpId = transformJson.getString("botpId"); + + //源单据标识 + String srcBill = transformJson.getString("srcBill"); + + //目标单据标识 + String destBill = transformJson.getString("destBill"); + + //源单据ID + JSONArray srcBillArray = transformJson.getJSONArray("srcBillList"); + List srcBilList = JSONObject.parseArray(srcBillArray.toJSONString(), String.class); + List transformList = IConvertRelationService.transformT(botpId, srcBill, destBill, srcBilList); + return ResponseResult.success(transformList); + + } + + @RequestMapping("/getConvertRelation") + public ResponseResult getConvertRelation(String billId, String billType, String traceType) { + List> convertRelation = IConvertRelationService.getConvertRelation(billId, billType, traceType); + return ResponseResult.success(convertRelation); + } + + + /** + * 分页查询 + */ + @PostMapping(value = "/list") + @Schema(description = "list") + public ResponseResult list(@MyRequestBody ConvertRelation convertRelation, + @MyRequestBody MyOrderParam orderParam, + @MyRequestBody MyPageParam pageParam) { + if (pageParam != null) { + PageMethod.startPage(pageParam.getPageNum(), pageParam.getPageSize()); + } + String orderBy = MyOrderParam.buildOrderBy(orderParam, ConvertRelation.class); + List list = + IConvertRelationService.getConvertRuleListWithRelation(convertRelation, orderBy); + long totalCount = 0L; + if (list instanceof Page) { + totalCount = ((Page) list).getTotal(); + } + MyPageData result = MyPageUtil.makeResponseData(list, totalCount); + //正常的返回 + return ResponseResult.success(result); + } + + + /** + * 新增 + * + * @param convertRelation 查询参数 + */ + @PostMapping(value = "/add") + @Schema(description = "新增") + public ResponseResult add(@MyRequestBody ConvertRelation convertRelation) { + if (IConvertRelationService.addAll(convertRelation)) { + return ResponseResult.success("新增成功"); + } else { + return ResponseResult.error(ErrorCodeEnum.INVALID_DATA_MODEL); + } + } + + /** + * 有分录修改 + * + * @param convertRelation 查询参数 + */ + @PostMapping(value = "/edit") + @Schema(description = "修改") + public ResponseResult edit(@MyRequestBody ConvertRelation convertRelation) { + if (IConvertRelationService.editAll(convertRelation)) { + return ResponseResult.success("修改成功"); + } else { + return ResponseResult.error(ErrorCodeEnum.INVALID_DATA_MODEL); + } + } + + /** + * 有分录删除所有数据 + * + * @param id + */ + @GetMapping(value = "/removeById") + @Schema(description = "删除所有数据") + public ResponseResult removeById(@RequestParam Long id) { + IConvertRelationService.removeAllById(id); + return ResponseResult.success("删除成功"); + } + + @GetMapping(value = "/removeMulti") + @Schema(description = "删除所有数据") + public ResponseResult removeById(@RequestParam String ids) { + for (String id : ids.split(",")) { + IConvertRelationService.removeAllById(Long.valueOf(id)); + } + return ResponseResult.success("删除成功"); + } + + +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/controller/ConvertRelationEntryController.java b/common/common-botp/src/main/java/apelet/common/botp/controller/ConvertRelationEntryController.java new file mode 100644 index 0000000..5d9e5ad --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/controller/ConvertRelationEntryController.java @@ -0,0 +1,98 @@ +package apelet.common.botp.controller; + +import apelet.common.botp.model.ConvertRelationEntry; +import apelet.common.botp.service.impl.ConvertRelationEntryServiceImpl; +import apelet.common.core.annotation.MyRequestBody; +import apelet.common.core.constant.ErrorCodeEnum; +import apelet.common.core.object.*; +import apelet.common.core.util.MyPageUtil; +import com.github.pagehelper.Page; +import com.github.pagehelper.page.PageMethod; +import io.swagger.v3.oas.annotations.media.Schema; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +/** + * @author admin + * @since 2024-01-18 10:31:58 + */ +@RestController +@RequestMapping("/botp/ConvertRelationEntry") +public class ConvertRelationEntryController { + @Autowired + private ConvertRelationEntryServiceImpl ConvertRelationEntryServiceImpl; + + + /** + * 分页查询 + * */ + @PostMapping(value = "/list") + @Schema(description = "list") + public ResponseResult list(@MyRequestBody ConvertRelationEntry convertRelationEntry, + @MyRequestBody MyOrderParam orderParam, + @MyRequestBody MyPageParam pageParam) { + if (pageParam != null) { + PageMethod.startPage(pageParam.getPageNum(), pageParam.getPageSize()); + } + String orderBy = MyOrderParam.buildOrderBy(orderParam, ConvertRelationEntry.class); + List list = + ConvertRelationEntryServiceImpl.getConvertRuleListWithRelation(convertRelationEntry,orderBy); + long totalCount = 0L; + if (list instanceof Page) { + totalCount = ((Page) list).getTotal(); + } + MyPageData result = MyPageUtil.makeResponseData(list, totalCount); + //正常的返回 + return ResponseResult.success(result); + } + + + /** + * 新增 + * @param convertRelationEntry 查询参数 + */ + @PostMapping(value = "/add") + @Schema(description = "新增") + public ResponseResult add(@MyRequestBody ConvertRelationEntry convertRelationEntry){ + if (ConvertRelationEntryServiceImpl.addAll(convertRelationEntry)){ + return ResponseResult.success("新增成功"); + }else { + return ResponseResult.error(ErrorCodeEnum.INVALID_DATA_MODEL); + } + } + /** + * 有分录修改 + * @param convertRelationEntry 查询参数 + */ + @PostMapping(value = "/edit") + @Schema(description = "修改") + public ResponseResult edit(@MyRequestBody ConvertRelationEntry convertRelationEntry){ + if (ConvertRelationEntryServiceImpl.editAll(convertRelationEntry)){ + return ResponseResult.success("修改成功"); + }else { + return ResponseResult.error(ErrorCodeEnum.INVALID_DATA_MODEL); + } + } + /** + * 有分录删除所有数据 + * @param id + */ + @GetMapping(value = "/removeById") + @Schema(description = "删除所有数据") + public ResponseResult removeById(@RequestParam Long id){ + ConvertRelationEntryServiceImpl.removeAllById(id); + return ResponseResult.success("删除成功"); + } + @GetMapping(value = "/removeMulti") + @Schema(description = "删除所有数据") + public ResponseResult removeById(@RequestParam String ids){ + for (String id : ids.split(",")) { + ConvertRelationEntryServiceImpl.removeAllById(Long.valueOf(id)); + } + return ResponseResult.success("删除成功"); + } + + +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/controller/ConvertRuleController.java b/common/common-botp/src/main/java/apelet/common/botp/controller/ConvertRuleController.java new file mode 100644 index 0000000..33db53c --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/controller/ConvertRuleController.java @@ -0,0 +1,192 @@ +package apelet.common.botp.controller; + +import apelet.common.botp.dto.ConvertRelationDelDto; +import apelet.common.botp.dto.ConvertRelationListDto; +import apelet.common.botp.dto.TransfromDto; +import apelet.common.botp.model.AllField; +import apelet.common.botp.model.ConvertRule; +import apelet.common.botp.service.IConvertRuleService; +import apelet.common.core.annotation.MyRequestBody; +import apelet.common.core.constant.ErrorCodeEnum; +import apelet.common.core.object.*; +import apelet.common.core.util.MyPageUtil; +import apelet.common.generator.model.OnlFormHead; +import apelet.common.generator.vo.OnlFormHeadVo; +import com.github.pagehelper.Page; +import com.github.pagehelper.page.PageMethod; +import io.swagger.v3.oas.annotations.media.Schema; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +/** + * @author admin + * @since 2024-01-18 10:31:58 + */ +@RestController +@RequestMapping("/botp/ConvertRule") +public class ConvertRuleController { + + @Autowired + private IConvertRuleService convertRuleService; + + + @RequestMapping("/allField") + //查询单据的所有字段 + public List allField(String tableName) { + List allFieldList = convertRuleService.allField(tableName); + return allFieldList; + } + + + /** + * 分页查询 + * */ + @PostMapping(value = "/list") + @Schema(description = "list") + public ResponseResult list(@MyRequestBody ConvertRule convertRule, + @MyRequestBody MyOrderParam orderParam, + @MyRequestBody MyPageParam pageParam) { + if (pageParam != null) { + PageMethod.startPage(pageParam.getPageNum(), pageParam.getPageSize()); + } + String orderBy = MyOrderParam.buildOrderBy(orderParam, ConvertRule.class); + List list = + convertRuleService.getConvertRuleListWithRelation(convertRule,orderBy); + long totalCount = 0L; + if (list instanceof Page) { + totalCount = ((Page) list).getTotal(); + } + MyPageData result = MyPageUtil.makeResponseData(list, totalCount); + //正常的返回 + return ResponseResult.success(result); + } + + + /** + * 新增 + * @param convertRule 查询参数 + */ + @PostMapping(value = "/add") + @Schema(description = "新增") + public ResponseResult add(@MyRequestBody ConvertRule convertRule){ + if (convertRuleService.addAll(convertRule)){ + return ResponseResult.success("新增成功"); + }else { + return ResponseResult.error(ErrorCodeEnum.INVALID_DATA_MODEL); + } + } + /** + * 有分录修改 + * @param convertRule 查询参数 + */ + @PostMapping(value = "/edit") + @Schema(description = "修改") + public ResponseResult edit(@MyRequestBody ConvertRule convertRule){ + if (convertRuleService.editAll(convertRule)){ + return ResponseResult.success("修改成功"); + }else { + return ResponseResult.error(ErrorCodeEnum.INVALID_DATA_MODEL); + } + } + /** + * 有分录删除所有数据 + * @param id + */ + @GetMapping(value = "/removeById") + @Schema(description = "删除所有数据") + public ResponseResult removeById(@RequestParam Long id){ + convertRuleService.removeAllById(id); + return ResponseResult.success("删除成功"); + } + @GetMapping(value = "/removeMulti") + @Schema(description = "删除所有数据") + public ResponseResult removeById(@RequestParam String ids){ + for (String id : ids.split(",")) { + convertRuleService.removeAllById(Long.valueOf(id)); + } + return ResponseResult.success("删除成功"); + } + + + /** + * 删除关联关系 + * + * @param dto 转换规则id + * @return + */ + @PostMapping(value = "/removeAllRelation") + @Schema(description = "删除单据所有关联关系") + public ResponseResult removeAllRelation(@RequestBody ConvertRelationDelDto dto) { + convertRuleService.removeAllRelation(dto); + return ResponseResult.success("删除成功!"); + } + + /** + * 根据目标单据查询关联关系 + * + * @param dto 单id + * @return + */ + @PostMapping(value = "/selectAllRelationByTarget") + @Schema(description = "根据目标单据查询关联关系") + public ResponseResult selectAllRelationByTarget(@RequestBody ConvertRelationListDto dto) { + return ResponseResult.success(convertRuleService.selectAllRelationByTarget(dto)); + } + + //模版循环查询分录 + @GetMapping(value = "/getConvertPluginEntry") + @Schema(description = "查询分录插件") + public ResponseResult getChild1(@RequestParam Long id){ + return ResponseResult.success(convertRuleService.getConvertPluginEntry(id)); + } + + + @GetMapping(value = "/getConvertFieldmappingEntry") + @Schema(description = "转换规则字段映射") + public ResponseResult getChild2(@RequestParam Long id){ + return ResponseResult.success(convertRuleService.getConvertFieldmappingEntry(id)); + } + + /** + * 根据源单据查询关联关系 + * + * @param dto 单id + * @return + */ + @PostMapping(value = "/selectAllRelationBySource") + @Schema(description = "根据源单据查询关联关系") + public ResponseResult selectAllRelationBySource(@RequestBody ConvertRelationListDto dto) { + return ResponseResult.success(convertRuleService.selectAllRelationBySource(dto)); + } + /** + * 下推规则查询 + * @param dto + * @return + */ + @PostMapping(value = "/getPushBillList") + @Schema(description = "下推规则查询") + public ResponseResult getPushBillList(@RequestBody ConvertRelationDelDto dto) { + return ResponseResult.success(convertRuleService.getPushBillList(dto)); + } + + + @PostMapping(value = "/transform") + @Schema(description = "单据转换") + public ResponseResult transform(@RequestBody TransfromDto dto) { + + return ResponseResult.success(convertRuleService.transform(dto.getBotpId() + ,dto.getSrcBill(),dto.getDestBill(),dto.getSrcBillId())); + } + + + + @GetMapping(value = "/getRuleTableFiled") + public ResponseResult getRuleTableFiled (@RequestBody String tableName) { + + + return ResponseResult.success( convertRuleService.getRuleTableFiled(tableName)); + } + +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/controller/SysMenuqqController.java b/common/common-botp/src/main/java/apelet/common/botp/controller/SysMenuqqController.java new file mode 100644 index 0000000..18f2745 --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/controller/SysMenuqqController.java @@ -0,0 +1,13 @@ +package apelet.common.botp.controller; + +import apelet.common.botp.service.ISysMenuqqService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/botp/SysMenuqq") +public class SysMenuqqController { + @Autowired + private ISysMenuqqService ISysMenuqqService; +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/dao/BillBaseDaoMapper.java b/common/common-botp/src/main/java/apelet/common/botp/dao/BillBaseDaoMapper.java new file mode 100644 index 0000000..949c755 --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/dao/BillBaseDaoMapper.java @@ -0,0 +1,12 @@ +package apelet.common.botp.dao; + + +import apelet.common.core.base.dao.BaseDaoMapper; + +/** + * @author Soon + * @version 1.0 + * Create by 2024/2/28 8:37 + */ +public interface BillBaseDaoMapper extends BaseDaoMapper { +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/dao/ConvertFieldmappingEntryMapper.java b/common/common-botp/src/main/java/apelet/common/botp/dao/ConvertFieldmappingEntryMapper.java new file mode 100644 index 0000000..547e268 --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/dao/ConvertFieldmappingEntryMapper.java @@ -0,0 +1,15 @@ +package apelet.common.botp.dao; + + +import apelet.common.botp.model.ConvertFieldmappingEntry; +import apelet.common.core.base.dao.BaseDaoMapper; + +/** + * + * @author admin + * @since 2024-01-18 10:31:58 + * 转换规则字段映射 + * xykj_fieldmapping + */ +public interface ConvertFieldmappingEntryMapper extends BaseDaoMapper { +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/dao/ConvertPluginEntryMapper.java b/common/common-botp/src/main/java/apelet/common/botp/dao/ConvertPluginEntryMapper.java new file mode 100644 index 0000000..f1912f9 --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/dao/ConvertPluginEntryMapper.java @@ -0,0 +1,15 @@ +package apelet.common.botp.dao; + + +import apelet.common.botp.model.ConvertPluginEntry; +import apelet.common.core.base.dao.BaseDaoMapper; + +/** + * + * @author admin + * @since 2024-01-18 10:31:58 + * 分录插件 + * xykj_entry_plugin + */ +public interface ConvertPluginEntryMapper extends BaseDaoMapper { +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/dao/ConvertRelationEntryMapper.java b/common/common-botp/src/main/java/apelet/common/botp/dao/ConvertRelationEntryMapper.java new file mode 100644 index 0000000..9fc15f7 --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/dao/ConvertRelationEntryMapper.java @@ -0,0 +1,15 @@ +package apelet.common.botp.dao; + + +import apelet.common.botp.model.ConvertRelationEntry; +import apelet.common.core.base.dao.BaseDaoMapper; + +/** + * + * @author admin + * @since 2024-01-18 10:31:58 + * 单据分录关联关系 + * xykj_document_entry + */ +public interface ConvertRelationEntryMapper extends BaseDaoMapper { +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/dao/ConvertRelationMapper.java b/common/common-botp/src/main/java/apelet/common/botp/dao/ConvertRelationMapper.java new file mode 100644 index 0000000..f117c85 --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/dao/ConvertRelationMapper.java @@ -0,0 +1,31 @@ +package apelet.common.botp.dao; + + +import apelet.common.botp.model.ConvertRelation; +import apelet.common.botp.model.GetSearchList; +import apelet.common.core.base.dao.BaseDaoMapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +/** + * + * @author admin + * @since 2024-01-18 10:31:58 + * 单据关联关系 + * xykj_related_relationships + */ +public interface ConvertRelationMapper extends BaseDaoMapper { + + public List transform(String botpId, String srcBill, String destBill, String srcBillId); + + public List transformT(String botpId, String srcBill, String destBill, List srcBillList); + + //根据联查单据id、单据标识、上查 ,根据单据关联关系表查询关联查询的单据 + public List getConvertRelationOn(@Param("billId")String billId,@Param("billType")String billType); + + //根据联查单据id、单据标识、下查 ,根据单据关联关系表查询关联查询的单据 + public List getConvertRelationDown(@Param("billId")String billId,@Param("billType")String billType); + + +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/dao/ConvertRuleMapper.java b/common/common-botp/src/main/java/apelet/common/botp/dao/ConvertRuleMapper.java new file mode 100644 index 0000000..384db7f --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/dao/ConvertRuleMapper.java @@ -0,0 +1,21 @@ +package apelet.common.botp.dao; + +import apelet.common.botp.model.AllField; +import apelet.common.botp.model.ConvertRule; +import apelet.common.core.base.dao.BaseDaoMapper; + +import java.util.List; + +/** + * + * @author admin + * @since 2024-01-18 10:31:58 + * 转换规则存值主表 + * xykj_ConvertRule + */ +public interface ConvertRuleMapper extends BaseDaoMapper { + //查询返回源单和目标单全部字段 + public List allField(String tableName); + + +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/dao/SysMenuqqMapper.java b/common/common-botp/src/main/java/apelet/common/botp/dao/SysMenuqqMapper.java new file mode 100644 index 0000000..8e45647 --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/dao/SysMenuqqMapper.java @@ -0,0 +1,7 @@ +package apelet.common.botp.dao; + +import apelet.common.botp.model.SysMenuqq; +import apelet.common.core.base.dao.BaseDaoMapper; + +public interface SysMenuqqMapper extends BaseDaoMapper { +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/dao/mapper/ConvertFieldmappingEntryMapper.xml b/common/common-botp/src/main/java/apelet/common/botp/dao/mapper/ConvertFieldmappingEntryMapper.xml new file mode 100644 index 0000000..33772d4 --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/dao/mapper/ConvertFieldmappingEntryMapper.xml @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/common/common-botp/src/main/java/apelet/common/botp/dao/mapper/ConvertPluginEntryMapper.xml b/common/common-botp/src/main/java/apelet/common/botp/dao/mapper/ConvertPluginEntryMapper.xml new file mode 100644 index 0000000..1e38f0e --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/dao/mapper/ConvertPluginEntryMapper.xml @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/common/common-botp/src/main/java/apelet/common/botp/dao/mapper/ConvertRelationEntryMapper.xml b/common/common-botp/src/main/java/apelet/common/botp/dao/mapper/ConvertRelationEntryMapper.xml new file mode 100644 index 0000000..9bfd13b --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/dao/mapper/ConvertRelationEntryMapper.xml @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/common/common-botp/src/main/java/apelet/common/botp/dao/mapper/ConvertRelationMapper.xml b/common/common-botp/src/main/java/apelet/common/botp/dao/mapper/ConvertRelationMapper.xml new file mode 100644 index 0000000..7afafe4 --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/dao/mapper/ConvertRelationMapper.xml @@ -0,0 +1,31 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/common/common-botp/src/main/java/apelet/common/botp/dao/mapper/ConvertRuleMapper.xml b/common/common-botp/src/main/java/apelet/common/botp/dao/mapper/ConvertRuleMapper.xml new file mode 100644 index 0000000..a2c382c --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/dao/mapper/ConvertRuleMapper.xml @@ -0,0 +1,13 @@ + + + + + + + + \ No newline at end of file diff --git a/common/common-botp/src/main/java/apelet/common/botp/dao/mapper/SysMenuqqMapper.xml b/common/common-botp/src/main/java/apelet/common/botp/dao/mapper/SysMenuqqMapper.xml new file mode 100644 index 0000000..ecf3696 --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/dao/mapper/SysMenuqqMapper.xml @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/common/common-botp/src/main/java/apelet/common/botp/db/object/DataFilter.java b/common/common-botp/src/main/java/apelet/common/botp/db/object/DataFilter.java new file mode 100644 index 0000000..fc73093 --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/db/object/DataFilter.java @@ -0,0 +1,139 @@ +package apelet.common.botp.db.object; + +import apelet.common.botp.db.util.DbUtil; +import apelet.common.online.model.constant.FieldFilterType; +import cn.hutool.core.collection.CollUtil; +import cn.hutool.core.util.StrUtil; +import lombok.Data; + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; + +/** + * @author Soon + * @version 1.0 + * Create by 2024/1/23 14:01 + */ +@Data +public class DataFilter { + + /** + * 表名 + */ + private String tableName; + + /** + * 数据集合 + */ + private List dataFilterItems = new ArrayList<>(); + + + /** + * 构建查询条件sql + * @param paramList + * @return + */ + public String getWhereClause(List paramList){ + StringBuilder where = new StringBuilder(); + if(dataFilterItems.size() == 0){ + return ""; + } + List normalizedFilters = new LinkedList<>(); + for (DataFilterItem dataFilterItem:dataFilterItems){ + + String filterString = this.makeSubWhereClause(dataFilterItem,this, paramList); + if (StrUtil.isNotBlank(filterString)) { + normalizedFilters.add(filterString); + } + + } + if (CollUtil.isNotEmpty(normalizedFilters)) { + where.append(DbUtil.WHERE); + where.append(CollUtil.join(normalizedFilters, DbUtil.AND)); + } + + return where.toString(); + + } + + private String makeSubWhereClause(DataFilterItem filterItem,DataFilter filter, List paramList) { + StringBuilder where = new StringBuilder(256); + if (filterItem.getFilterType().equals(FieldFilterType.EQUAL_FILTER)) { + where.append(this.makeWhereLeftOperator(filterItem,filter)); + where.append(" = ? "); + paramList.add(filterItem.getParamValue()); + } else if (filterItem.getFilterType().equals(FieldFilterType.RANGE_FILTER)) { + where.append(this.makeRangeFilterClause(filterItem, paramList)); + } else if (filterItem.getFilterType().equals(FieldFilterType.LIKE_FILTER)) { + where.append(this.makeWhereLeftOperator(filterItem,filter)); + where.append(" LIKE ? "); + paramList.add(filterItem.getParamValue()); + } else if (filterItem.getFilterType().equals(FieldFilterType.IN_LIST_FILTER)) { + // where.append(this.makeWhereLeftOperator(filterItem)); + // where.append(" IN ( "); + // where.append(StrUtil.repeat("?,", filterItem.getColumnValueList().size())); + // where.setLength(where.length() - 1); + // where.append(")"); + // paramList.addAll(filterItem.getColumnValueList()); + } else if (filterItem.getFilterType().equals(FieldFilterType.MULTI_LIKE)) { + // where.append("("); + // StringBuilder sb = new StringBuilder(128); + // sb.append(this.makeWhereLeftOperator(filterItem)).append(" LIKE ? OR "); + // String s = StrUtil.repeat(sb.toString(), filterItem.getColumnValueList().size()); + // where.append(s, 0, s.length() - 4); + // where.append(")"); + // paramList.addAll(filterItem.getColumnValueList()); + } else if (filterItem.getFilterType().equals(FieldFilterType.NOT_IN_LIST_FILTER)) { + // where.append(this.makeWhereLeftOperator(filterItem)); + // where.append(" NOT IN ("); + // where.append(StrUtil.repeat("?,", filterItem.getColumnValueList().size())); + // where.setLength(where.length() - 1); + // where.append(")"); + // paramList.addAll(filterItem.getColumnValueList()); + } else if (filterItem.getFilterType().equals(FieldFilterType.IS_NULL)) { + where.append(this.makeWhereLeftOperator(filterItem,filter)); + where.append(" IS NULL "); + } else if (filterItem.getFilterType().equals(FieldFilterType.IS_NOT_NULL)) { + where.append(this.makeWhereLeftOperator(filterItem,filter)); + where.append(" IS NOT NULL "); + } + return where.toString(); + } + + private String makeWhereLeftOperator(DataFilterItem filterItem,DataFilter filter) { + if (StrUtil.isBlank(filter.getTableName())) { + return filterItem.getParamName(); + } + StringBuilder sb = new StringBuilder(128); + sb.append(filter.getTableName()).append(".").append(filterItem.getParamName()); + return sb.toString(); + } + + private String makeRangeFilterClause(DataFilterItem filterItem, List paramList) { + StringBuilder where = new StringBuilder(256); + // if (ObjectUtil.isNotEmpty(filter.getColumnValueStart())) { + // where.append(this.makeWhereLeftOperator(filter)); + // if (BooleanUtil.isTrue(filter.getIsOracleDate())) { + // where.append(" >= ").append(filter.getColumnValueStart()); + // } else { + // where.append(" >= ? "); + // paramList.add(filter.getColumnValueStart()); + // } + // } + // if (ObjectUtil.isNotEmpty(filter.getColumnValueEnd())) { + // if (ObjectUtil.isNotEmpty(filter.getColumnValueStart())) { + // where.append(DbUtil.AND); + // } + // where.append(this.makeWhereLeftOperator(filter)); + // if (BooleanUtil.isTrue(filter.getIsOracleDate())) { + // where.append(" <= ").append(filter.getColumnValueEnd()); + // } else { + // where.append(" <= ? "); + // paramList.add(filter.getColumnValueEnd()); + // } + // } + return where.toString(); + } + +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/db/object/DataFilterItem.java b/common/common-botp/src/main/java/apelet/common/botp/db/object/DataFilterItem.java new file mode 100644 index 0000000..d51cd0c --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/db/object/DataFilterItem.java @@ -0,0 +1,28 @@ +package apelet.common.botp.db.object; + +import apelet.common.online.model.constant.FieldFilterType; +import lombok.Data; + +/** + * @author Soon + * @version 1.0 + * Create by 2024/1/23 13:53 + */ +@Data +public class DataFilterItem { + + private String paramName; + + private String paramValue; + + private Integer filterType = FieldFilterType.EQUAL_FILTER; + + public DataFilterItem(String paramName,Integer filterType,String paramValue){ + + this.paramName = paramName; + this.paramValue = paramValue; + this.filterType = filterType; + + } + +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/db/object/InsertData.java b/common/common-botp/src/main/java/apelet/common/botp/db/object/InsertData.java new file mode 100644 index 0000000..6bdb07f --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/db/object/InsertData.java @@ -0,0 +1,18 @@ +package apelet.common.botp.db.object; + +import lombok.Data; + +import java.util.LinkedList; + +/** + * @author Soon + * @version 1.0 + * Create by 2024/1/25 17:07 + */ +@Data +public class InsertData { + + private String columnNames; + private LinkedList dataList = new LinkedList(); + +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/db/object/ObjectSqlData.java b/common/common-botp/src/main/java/apelet/common/botp/db/object/ObjectSqlData.java new file mode 100644 index 0000000..e73c97e --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/db/object/ObjectSqlData.java @@ -0,0 +1,18 @@ +package apelet.common.botp.db.object; + +import lombok.Data; + +import java.util.List; + +/** + * @author Soon + * @version 1.0 + * Create by 2024/1/25 17:58 + */ +@Data +public class ObjectSqlData { + + private String sql; + private List dataList; + +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/db/util/DbUtil.java b/common/common-botp/src/main/java/apelet/common/botp/db/util/DbUtil.java new file mode 100644 index 0000000..06cce74 --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/db/util/DbUtil.java @@ -0,0 +1,185 @@ +package apelet.common.botp.db.util; + +import apelet.common.botp.db.object.ObjectSqlData; +import apelet.common.dbutil.constant.DblinkType; +import apelet.common.dbutil.provider.DataSourceProvider; +import apelet.common.online.exception.OnlineRuntimeException; +import apelet.common.online.util.OnlineDataSourceUtil; +import cn.hutool.core.map.MapUtil; +import com.alibaba.druid.pool.DruidDataSource; +import com.alibaba.druid.pool.DruidDataSourceFactory; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.cloud.context.config.annotation.RefreshScope; +import org.springframework.stereotype.Component; + +import javax.sql.DataSource; +import java.sql.Connection; +import java.util.*; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; + +/** + * @author Soon + * @version 1.0 + * Create by 2024/1/23 17:00 + */ +@Component +@Slf4j +@RefreshScope +public class DbUtil { + + public static final String SELECT = "SELECT "; + public static final String FROM = " FROM "; + public static final String WHERE = " WHERE "; + public static final String AND = " AND "; + + private final Map datasourceMap = MapUtil.newHashMap(); + + @Value("${spring.datasource.druid.driverClassName}") + private String driverClassName; //驱动 + @Value("${spring.datasource.druid.tenant-admin.url}") + private String url; //链接 + @Value("${spring.datasource.druid.tenant-admin.username}") + private String username; //用户名 + @Value("${spring.datasource.druid.tenant-admin.password}") + private String password; //密码i + @Value("${spring.datasource.druid.initialSize}") + private int initialSize; //密码 + @Value("${spring.datasource.druid.minIdle}") + private int minPoolSize;//连接池最小连接数。 + @Value("${spring.datasource.druid.maxActive}") + private int maxPoolSize;//连接池最大连接数。 + @Value("${spring.datasource.druid.name}") + private String name;//连接池最大连接数。 + + @Autowired + private OnlineDataSourceUtil dataSourceUtil; + + private final Lock lock = new ReentrantLock(); + + + public DataSourceProvider getDataSourceProvider(){ + return dataSourceUtil.getProvider(this.getDbType()); + } + + + public void addNew(ObjectSqlData objectSqlData)throws Exception { + List objectSqlDataList = new ArrayList<>(); + objectSqlDataList.add(objectSqlData); + doHandle(objectSqlDataList); + } + public void addNewBatch(List objectSqlDataList)throws Exception { + doHandle(objectSqlDataList); + } + + private void doHandle(List objectSqlDataList) throws Exception { + Connection conn = null; + try { + conn = getDataSource().getConnection(); + conn.setAutoCommit(false); + for (ObjectSqlData s : objectSqlDataList) { + List paramList = s.getDataList(); + dataSourceUtil.execute(conn, s.getSql(), paramList); + } + conn.commit(); + } catch (Exception e) { + if (conn != null) { + conn.rollback(); + } + log.error(e.getMessage(), e); + throw new OnlineRuntimeException(e.getMessage()); + } finally { + if (conn != null) { + conn.close(); + } + } + } + + + /** + * 查询数据 + * @param query sql + * @param paramList 参数列表 + * @return + * @throws Exception + */ + public List> query(String query, List paramList) throws Exception { + DataSource dataSource = this.getDataSource(); + return dataSourceUtil.query(dataSource,query,paramList); + } + + + /** + * 根据对象获取关联的数据源。如果不存在会创建该数据库连接池的数据源, + * 并保存到Map中缓存,下次调用时可直接返回。 + * + * + * @return 关联的数据库连接池的数据源。 + */ + public DataSource getDataSource() throws Exception { + DataSource dataSource = datasourceMap.get(name); + if (dataSource != null) { + return dataSource; + } + DataSourceProvider provider = dataSourceUtil.getProvider(getDbType()); + if (provider == null) { + throw new Exception("数据库类型错误"); + } + DruidDataSource druidDataSource = null; + lock.lock(); + try { + dataSource = datasourceMap.get(name); + if (dataSource != null) { + return dataSource; + } + Properties properties = new Properties(); + druidDataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties); + druidDataSource.setUrl(url); + druidDataSource.setDriverClassName(driverClassName); + druidDataSource.setValidationQuery("SELECT 'x'"); + druidDataSource.setUsername(username); + druidDataSource.setPassword(password); + druidDataSource.setInitialSize(initialSize); + druidDataSource.setMinIdle(minPoolSize); + druidDataSource.setMaxActive(maxPoolSize); + druidDataSource.setConnectionErrorRetryAttempts(2); + druidDataSource.setTimeBetweenConnectErrorMillis(500); + druidDataSource.setBreakAfterAcquireFailure(true); + druidDataSource.init(); + datasourceMap.put(name, druidDataSource); + return druidDataSource; + } catch (Exception e) { + if (druidDataSource != null) { + druidDataSource.close(); + } + log.error("Failed to create DruidDatasource", e); + throw e; + } finally { + lock.unlock(); + } + } + + + public int getDbType(){ + if(driverClassName.contains("mysql")){ + return DblinkType.MYSQL; + } + return 0; + + } + + + public int execute(String sql, List paramList) { + try { + Connection connection = getDataSource().getConnection(); + return dataSourceUtil.execute(connection, sql, paramList); + } catch (Exception e) { + throw new RuntimeException(e); + } + + } + + +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/dto/ConvertRelationDelDto.java b/common/common-botp/src/main/java/apelet/common/botp/dto/ConvertRelationDelDto.java new file mode 100644 index 0000000..38101e2 --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/dto/ConvertRelationDelDto.java @@ -0,0 +1,36 @@ +package apelet.common.botp.dto; + +import apelet.common.core.validator.UpdateGroup; +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; +import java.util.List; + +/** + * 删除单据关联关系dto + */ +@Schema(description = "单据关联关系dto") +@Data +public class ConvertRelationDelDto { + /** + * 转换规则id/单据id。 + */ + @Schema(description = "转换规则id") + @NotNull(message = "Id不能为空!", groups = {UpdateGroup.class}) + private String billId; + + /** + * 单据标识。 + */ + @Schema(description = "单据标识") + @NotBlank(message = "单据标识不能为空!") + private String billType; + + /** + * 转换规则id + */ + @Schema(description = "转换规则id") + private List billIdList; +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/dto/ConvertRelationDto.java b/common/common-botp/src/main/java/apelet/common/botp/dto/ConvertRelationDto.java new file mode 100644 index 0000000..bfb0703 --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/dto/ConvertRelationDto.java @@ -0,0 +1,39 @@ +package apelet.common.botp.dto; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +import java.util.List; + +/** + * @author Soon + * @version 1.0 + * Create by 2024/2/19 9:59 + * @description 关联关系 + */ +@Data +public class ConvertRelationDto { + + @Schema(description = "主键") + private Long id; + + @Schema(description = "转换规则id") + private String convertRuleId; + + @Schema(description = "源单标识") + private String sourceNumber; + + @Schema(description = "源单id") + private String sourceId; + + @Schema(description = "目标单标识") + private String targetNumber; + + @Schema(description = "目标单id") + private String targetId; + + + + private List convertRelationEntryDtoList; + +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/dto/ConvertRelationEntryDto.java b/common/common-botp/src/main/java/apelet/common/botp/dto/ConvertRelationEntryDto.java new file mode 100644 index 0000000..1d87245 --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/dto/ConvertRelationEntryDto.java @@ -0,0 +1,45 @@ +package apelet.common.botp.dto; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +/** + * @author Soon + * @version 1.0 + * Create by 2024/2/19 10:05 + * @description 转换分录关系 + */ +@Data +public class ConvertRelationEntryDto { + + @Schema(description = "主键") + private Long id; + + @Schema(description = "转换规则id") + private String convertRuleId; + + @Schema(description = "源单标识") + private String sourceNumber; + + @Schema(description = "源单id") + private String sourceId; + + @Schema(description = "源单分录标识") + private String sourceEntryNumber; + + @Schema(description = "源单分录id") + private String sourceEntryId; + + @Schema(description = "目标单标识") + private String targetNumber; + + @Schema(description = "目标单id") + private String targetId; + + @Schema(description = "目标分录标识") + private String targeEntryNumber; + + @Schema(description = "目标分录id") + private String targeEntryId; + +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/dto/ConvertRelationListDto.java b/common/common-botp/src/main/java/apelet/common/botp/dto/ConvertRelationListDto.java new file mode 100644 index 0000000..236b65b --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/dto/ConvertRelationListDto.java @@ -0,0 +1,44 @@ +package apelet.common.botp.dto; + +import apelet.common.core.validator.UpdateGroup; +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; + +/** + * 查询关联关系dto + */ +@Schema(description = "查询关联关系dto") +@Data +public class ConvertRelationListDto { + /** + * 目标单据ID + */ + @Schema(description = "目标单据ID") + @NotNull(message = "目标单据ID不能为空!", groups = {UpdateGroup.class}) + private String destBillId; + + /** + * 目标单据标识。 + */ + @Schema(description = "目标单据标识") + @NotBlank(message = "目标单据标识不能为空!") + private String destBillType; + + /** + * 源单单据ID + */ + @Schema(description = "源单单据ID") + @NotNull(message = "源单单据ID不能为空!", groups = {UpdateGroup.class}) + private String srcBillId; + + /** + * 源单单据标识。 + */ + @Schema(description = "源单单据标识") + @NotBlank(message = "源单单据标识不能为空!") + private String srcBillType; + +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/dto/ConvertRuleDto.java b/common/common-botp/src/main/java/apelet/common/botp/dto/ConvertRuleDto.java new file mode 100644 index 0000000..c1b0595 --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/dto/ConvertRuleDto.java @@ -0,0 +1,37 @@ +package apelet.common.botp.dto; + +import apelet.common.botp.model.ConvertRule; +import cn.afterturn.easypoi.excel.annotation.Excel; +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +/** + * @author admin + * @since 2024-01-18 10:31:58 + */ +@Data +@Schema(description = "转换规则存值主表dto") +public class ConvertRuleDto extends ConvertRule { + + private static final long serialVersionUID = 1L; + + @Excel(name = "单据标识", width = 15) + @Schema(description = "单据标识") + private String billType; + + @Excel(name = "单据名称", width = 15) + @Schema(description = "单据名称") + private String billTypeName; + + @Excel(name = "单据编辑界面", width = 15) + @Schema(description = "单据编辑界面") + private String billEditUI; + + @Excel(name = "是否显示编辑界面", width = 15) + @Schema(description = "是否显示编辑界面") + private String isShowEdit; + +// @Excel(name = "是否显示编辑界面", width = 15) + @Schema(description = "表单类型:1:路由表单,2:在线表单") + private String billEditUIType; +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/dto/TransformResultDto.java b/common/common-botp/src/main/java/apelet/common/botp/dto/TransformResultDto.java new file mode 100644 index 0000000..b2a9aaf --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/dto/TransformResultDto.java @@ -0,0 +1,45 @@ +package apelet.common.botp.dto; + +import apelet.common.botp.service.execute.entity.BillData; +import apelet.common.botp.service.execute.entity.BillRelation; +import lombok.Data; + +import java.util.List; + +/** + * @author Soon + * @version 1.0 + * Create by 2024/2/19 8:38 + */ +@Data +public class TransformResultDto { + + /** + * 数据 + */ + private BillData billData; + + + /** + * 关联关系 + */ + private List billRelationList; + + /** + * 表单状态 + */ + private String formStatus;//1 新增状态 ; 2 保存状态 + + /** + * 表单类型:路由表单,在线表单 + */ + private String formType;//1 路由表单 2 在线表单 + + /** + * 表单页面参数 + */ + private String formVal;;//页面,路由表单路径 ,在线表单formId + + + +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/dto/TransfromDto.java b/common/common-botp/src/main/java/apelet/common/botp/dto/TransfromDto.java new file mode 100644 index 0000000..01d0274 --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/dto/TransfromDto.java @@ -0,0 +1,29 @@ +package apelet.common.botp.dto; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +import javax.validation.constraints.NotNull; + +/** + * @author Soon + * @version 1.0 + * Create by 2024/1/26 14:27 + */ +@Data +@Schema(description = "单据转换dto") +public class TransfromDto { + @Schema(description = "转换规则id") + @NotNull(message = "botpId不能为空!") + private String botpId; + @Schema(description = "源单标识") + @NotNull(message = "源单标识不能为空!") + private String srcBill; + @Schema(description = "目标标识") + @NotNull(message = "目标标识不能为空!") + private String destBill; + @Schema(description = "源单id") + @NotNull(message = "源单id不能为空!") + private String srcBillId; + +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/mapper/BillBaseModelMapper.java b/common/common-botp/src/main/java/apelet/common/botp/mapper/BillBaseModelMapper.java new file mode 100644 index 0000000..0746055 --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/mapper/BillBaseModelMapper.java @@ -0,0 +1,11 @@ +package apelet.common.botp.mapper; + +import apelet.common.core.base.mapper.BaseModelMapper; + +/** + * @author Soon + * @version 1.0 + * Create by 2024/2/28 8:40 + */ +public interface BillBaseModelMapper extends BaseModelMapper { +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/model/AllField.java b/common/common-botp/src/main/java/apelet/common/botp/model/AllField.java new file mode 100644 index 0000000..f296f16 --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/model/AllField.java @@ -0,0 +1,39 @@ +package apelet.common.botp.model; + +import apelet.common.core.base.model.BaseModel; +import cn.afterturn.easypoi.excel.annotation.Excel; +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +@Data +@Schema(description = "转换规则存值主表") +@TableName("onl_form_field") +public class AllField extends BaseModel { + + private static final long serialVersionUID = 1L; + + @TableId(type = IdType.ASSIGN_ID) + @Schema(description = "主键") + private Long id; + + @Excel(name = "父表id", width = 15) + @Schema(description = "父表id") + private Long headId; + + @Excel(name = "字段名称", width = 15) + @Schema(description = "字段名称") + private String fieldName; + + @Excel(name = "字段备注", width = 15) + @Schema(description = "字段备注") + private String fieldRemark; + + @Excel(name = "字段长度", width = 15) + @Schema(description = "字段长度") + private int fieldLength; + + +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/model/BillBaseModel.java b/common/common-botp/src/main/java/apelet/common/botp/model/BillBaseModel.java new file mode 100644 index 0000000..37615b1 --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/model/BillBaseModel.java @@ -0,0 +1,13 @@ +package apelet.common.botp.model; + +import apelet.common.core.base.model.BaseModel; +import lombok.Data; + +/** + * @author Soon + * @version 1.0 + * Create by 2024/2/28 8:33 + */ +@Data +public class BillBaseModel extends BaseModel { +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/model/ConvertFieldmappingEntry.java b/common/common-botp/src/main/java/apelet/common/botp/model/ConvertFieldmappingEntry.java new file mode 100644 index 0000000..16182eb --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/model/ConvertFieldmappingEntry.java @@ -0,0 +1,93 @@ +package apelet.common.botp.model; + +import apelet.common.core.annotation.RelationGlobalDict; +import apelet.common.core.base.model.BaseModel; +import cn.afterturn.easypoi.excel.annotation.Excel; +import cn.afterturn.easypoi.excel.annotation.ExcelIgnore; +import com.baomidou.mybatisplus.annotation.*; +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +import java.util.Map; + +/** + * @author admin + * @since 2024-01-18 10:31:58 + */ +@Data +@Schema( description = "转换规则字段映射") +@TableName("convert_fieldmapping_entry") +public class ConvertFieldmappingEntry extends BaseModel { + + private static final long serialVersionUID = 1L; + + /**主键*/ + @TableId(type = IdType.ASSIGN_ID) + @Schema(description = "主键") + private Long id; + + @Schema(description = "逻辑删除标记(1: 正常 -1: 已删除)") +// @TableLogic + @ExcelIgnore + private Integer deletedFlag; + + @Excel(name = "源字段标识", width = 15) + @Schema(description = "源字段标识") + private String oldfieldNumber; + + @Excel(name = "源字段名称", width = 15) + @Schema(description = "源字段名称") + private String oldfieldName; + + @Excel(name = "目标字段标识", width = 15) + @Schema(description = "目标字段标识") + private String newfieldNumber; + + @Excel(name = "目标字段名称", width = 15) + @Schema(description = "目标字段名称") + private String newfieldName; + + @Excel(name = "计算公式", width = 15) + @Schema(description = "计算公式") + private String calculation; + private String calculationJson; + + @Excel(name = "取值方式", width = 15) + @Schema(description = "取值方式") + private String valueMethod; + + + @Excel(name = "取值", width = 15) + @Schema(description = "取值") + private String cltValue; + + @Excel(name = "父表id", width = 15) + @Schema(description = "父表id") + private String parentId; + + @RelationGlobalDict( + masterIdField = "parentId", + dictCode = "parent_id") + @TableField(exist = false) + private Map parentIdList; + + + // @RelationOneToOne( + // masterIdField = "oldfieldNumber", + // slaveModelClass = OnlFormField.class, + // slaveIdField = "id") + // @TableField(exist = false) + // private OnlFormField oldFormField; + + // @RelationOneToOne( + // masterIdField = "newfieldNumber", + // slaveModelClass = OnlFormField.class, + // slaveIdField = "id") + // @TableField(exist = false) + // private OnlFormField newFormField; + + @RelationGlobalDict(dictCode = "deleted_flag",masterIdField = "deletedFlag") + @TableField(exist = false) + private Map deletedFlagMap; + +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/model/ConvertPluginEntry.java b/common/common-botp/src/main/java/apelet/common/botp/model/ConvertPluginEntry.java new file mode 100644 index 0000000..d3465a8 --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/model/ConvertPluginEntry.java @@ -0,0 +1,72 @@ +package apelet.common.botp.model; + +import apelet.common.core.annotation.RelationGlobalDict; +import apelet.common.core.base.model.BaseModel; +import cn.afterturn.easypoi.excel.annotation.Excel; +import cn.afterturn.easypoi.excel.annotation.ExcelIgnore; +import com.baomidou.mybatisplus.annotation.*; +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +import java.util.Map; + +/** + * @author admin + * @since 2024-01-18 10:31:58 + */ +@Data +@Schema( description = "分录插件") +@TableName("convert_plugin_entry") +public class ConvertPluginEntry extends BaseModel { + + private static final long serialVersionUID = 1L; + + /**主键*/ + @TableId(type = IdType.ASSIGN_ID) + @Schema(description = "主键") + private Long id; + + @Schema(description = "逻辑删除标记(1: 正常 -1: 已删除)") +// @TableLogic + @ExcelIgnore + private Integer deletedFlag; + + @Excel(name = "启用", width = 15) + @Schema(description = "启用") + private String enable; + + @Excel(name = "类型", width = 15) + @Schema(description = "类型") + private String type; + + @Excel(name = "类名", width = 15) + @Schema(description = "类名") + private String className; + + @Excel(name = "插件名称", width = 15) + @Schema(description = "插件名称") + private String pluginName; + + @Excel(name = "描述说明", width = 15) + @Schema(description = "描述说明") + private String commen; + + @Excel(name = "序号", width = 15) + @Schema(description = "序号") + private String serialNumber; + + @Excel(name = "父表id", width = 15) + @Schema(description = "父表id") + private String parentId; + + @RelationGlobalDict( + masterIdField = "parentId", + dictCode = "parent_id") + @TableField(exist = false) + private Map parentIdList; + + @RelationGlobalDict(dictCode = "deleted_flag",masterIdField = "deletedFlag") + @TableField(exist = false) + private Map deletedFlagMap; + +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/model/ConvertRelation.java b/common/common-botp/src/main/java/apelet/common/botp/model/ConvertRelation.java new file mode 100644 index 0000000..b2aeec9 --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/model/ConvertRelation.java @@ -0,0 +1,47 @@ +package apelet.common.botp.model; + +import apelet.common.core.base.model.BaseModel; +import cn.afterturn.easypoi.excel.annotation.Excel; +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +/** + * @author admin + * @since 2024-01-18 10:31:58 + */ +@Data +@Schema( description = "单据关联关系") +@TableName("convert_relation") +public class ConvertRelation extends BaseModel { + + private static final long serialVersionUID = 1L; + + /**主键*/ + @TableId(type = IdType.ASSIGN_ID) + @Schema(description = "主键") + private Long id; + + @Excel(name = "转换规则id", width = 15) + @Schema(description = "转换规则id") + private String convertRuleId; + + @Excel(name = "源单标识", width = 15) + @Schema(description = "源单标识") + private String sourceNumber; + + @Excel(name = "源单id", width = 15) + @Schema(description = "源单id") + private String sourceId; + + @Excel(name = "目标单标识", width = 15) + @Schema(description = "目标单标识") + private String targetNumber; + + @Excel(name = "目标单id", width = 15) + @Schema(description = "目标单id") + private String targetId; + +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/model/ConvertRelationEntry.java b/common/common-botp/src/main/java/apelet/common/botp/model/ConvertRelationEntry.java new file mode 100644 index 0000000..ba0b518 --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/model/ConvertRelationEntry.java @@ -0,0 +1,63 @@ +package apelet.common.botp.model; + +import apelet.common.core.base.model.BaseModel; +import cn.afterturn.easypoi.excel.annotation.Excel; +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +/** + * @author admin + * @since 2024-01-18 10:31:58 + */ +@Data +@Schema( description = "单据分录关联关系") +@TableName("convert_relation_entry") +public class ConvertRelationEntry extends BaseModel { + + private static final long serialVersionUID = 1L; + + /**主键*/ + @TableId(type = IdType.ASSIGN_ID) + @Schema(description = "主键") + private Long id; + + @Excel(name = "转换规则id", width = 15) + @Schema(description = "转换规则id") + private String convertRuleId; + + @Excel(name = "源单标识", width = 15) + @Schema(description = "源单标识") + private String sourceNumber; + + @Excel(name = "源单id", width = 15) + @Schema(description = "源单id") + private String sourceId; + + @Excel(name = "源单分录标识", width = 15) + @Schema(description = "源单分录标识") + private String sourceEntryNumber; + + @Excel(name = "源单分录id", width = 15) + @Schema(description = "源单分录id") + private String sourceEntryId; + + @Excel(name = "目标单标识", width = 15) + @Schema(description = "目标单标识") + private String targetNumber; + + @Excel(name = "目标单id", width = 15) + @Schema(description = "目标单id") + private String targetId; + + @Excel(name = "目标分录标识", width = 15) + @Schema(description = "目标分录标识") + private String targeEntryNumber; + + @Excel(name = "目标分录id", width = 15) + @Schema(description = "目标分录id") + private String targeEntryId; + +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/model/ConvertRule.java b/common/common-botp/src/main/java/apelet/common/botp/model/ConvertRule.java new file mode 100644 index 0000000..3c623fd --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/model/ConvertRule.java @@ -0,0 +1,223 @@ +package apelet.common.botp.model; + +import apelet.common.botp.util.Constant; +import apelet.common.core.annotation.RelationDict; +import apelet.common.core.annotation.RelationGlobalDict; +import apelet.common.core.base.model.BaseModel; +import apelet.common.online.model.OnlineForm; +import cn.afterturn.easypoi.excel.annotation.Excel; +import cn.afterturn.easypoi.excel.annotation.ExcelCollection; +import cn.afterturn.easypoi.excel.annotation.ExcelIgnore; +import com.baomidou.mybatisplus.annotation.*; +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +import java.util.List; +import java.util.Map; + +/** + * @author admin + * @since 2024-01-18 10:31:58 + */ +@Data +@Schema( description = "转换规则存值主表") +@TableName("convert_rule") +public class ConvertRule extends BaseModel { + + private static final long serialVersionUID = 1L; + + /** + * 主键 + */ + @TableId(type = IdType.ASSIGN_ID) + @Schema(description = "主键") + private Long id; + + @Schema(description = "逻辑删除标记(1: 正常 -1: 已删除)") +// @TableLogic + @ExcelIgnore + private Integer deletedFlag; + + @Excel(name = "规则编码", width = 15) + @Schema(description = "规则编码") + private String number; + + @Excel(name = "规则名称", width = 15) + @Schema(description = "规则名称") + private String name; + + @Excel(name = "源单", width = 15) + @Schema(description = "源单") + private String sourceEntityId; + + @Excel(name = "源单表", width = 15) + @Schema(description = "源单表") + private String sourceTable; + + @Excel(name = "目标单", width = 15) + @Schema(description = "目标单") + private String targetEntityId; + + @Excel(name = "启动状态", width = 15) + @Schema(description = "启动状态") + private String enabled; + + @Excel(name = "是否默认", width = 15) + @Schema(description = "是否默认") + private String isDefault; + + @Excel(name = "下推自动保存", width = 15) + @Schema(description = "下推自动保存") + private String autoSave; + + @Excel(name = "运行时可见", width = 15) + @Schema(description = "运行时可见") + private String visible; + + @Excel(name = "上游界面类型", width = 15) + @Schema(description = "上游界面类型") + private String upInterfaceType; + + @Excel(name = "下游界面类型", width = 15) + @Schema(description = "下游界面类型") + private String downInterfaceType; + + + @Excel(name = "上游路由界面", width = 15) + @Schema(description = "上游路由界面(关联菜单管理)") + private Long upRouteInterface; + + @RelationDict( + masterIdField = "upRouteInterface", + equalOneToOneRelationField = "sysMenuqq", + slaveModelClass = SysMenuqq.class, + slaveIdField = "menuId", + slaveNameField = "formRouterName") + @TableField(exist = false) + private Map upRouteInterfaceMap; + + + @Excel(name = "下游路由界面", width = 15) + @Schema(description = "下游路由界面(关联菜单管理)") + private Long downRouteInterface; + + @RelationDict( + masterIdField = "downRouteInterface", + equalOneToOneRelationField = "sysMenuqq", + slaveModelClass = SysMenuqq.class, + slaveIdField = "menuId", + slaveNameField = "formRouterName") + @TableField(exist = false) + private Map downRouteInterfaceMap; + + + @Excel(name = "上游在线列表界面", width = 15) + @Schema(description = "上游在线列表界面(关联在线表单界面(OnlineForm))") + private Long upListInterface; + + + @RelationDict( + masterIdField = "upListInterface", + equalOneToOneRelationField = "onlineForm", + slaveModelClass = OnlineForm.class, + slaveIdField = "formId", + slaveNameField = "formName") + @TableField(exist = false) + private Map upListInterfaceMap; + + + @Excel(name = "上游在线编辑界面", width = 15) + @Schema(description = "上游在线编辑界面(关联在线表单界面(OnlineForm))") + private Long upEditInterface; + + @RelationDict( + masterIdField = "upEditInterface", + equalOneToOneRelationField = "onlineForm", + slaveModelClass = OnlineForm.class, + slaveIdField = "formId", + slaveNameField = "formName") + @TableField(exist = false) + private Map upEditInterfaceList; + + + @Excel(name = "下游在线列表界面", width = 15) + @Schema(description = "下游在线列表界面(关联在线表单界面(OnlineForm))") + private Long downListInterface; + + @RelationDict( + masterIdField = "downListInterface", + equalOneToOneRelationField = "onlineForm", + slaveModelClass = OnlineForm.class, + slaveIdField = "formId", + slaveNameField = "formName") + @TableField(exist = false) + private Map downListInterfaceList; + + + @Excel(name = "下游在线编辑界面", width = 15) + @Schema(description = "下游在线编辑界面(关联在线表单界面(OnlineForm))") + private Long downEditInterface; + + @RelationDict( + masterIdField = "downEditInterface", + equalOneToOneRelationField = "onlineForm", + slaveModelClass = OnlineForm.class, + slaveIdField = "formId", + slaveNameField = "formName") + @TableField(exist = false) + private Map downEditInterfaceList; + + +// @RelationOneToOne( +// masterIdField = "id", +// slaveModelClass = ConvertRelation.class, +// slaveIdField = "convertRuleId") +// @TableField(exist = false) +// private ConvertRelation convertRelation; + + + @RelationGlobalDict(dictCode = "deleted_flag", masterIdField = "deletedFlag") + @TableField(exist = false) + private Map deletedFlagMap; + + @RelationGlobalDict( + masterIdField = "sourceEntityId", + dictCode = "sourceEntity_id") + @TableField(exist = false) + private Map sourceEntityIdList; + + + @RelationGlobalDict( + masterIdField = "targetEntityId", + dictCode = "targetEntity_id") + @TableField(exist = false) + private Map targetEntityIdList; + + + @Schema(description = "分录1") + @TableField(exist = false) + @ExcelCollection(name = "子数据", orderNum = "17", type = ConvertPluginEntry.class) + private List convertPluginEntryList; + + @Schema(description = "分录2") + @TableField(exist = false) + @ExcelCollection(name = "子数据", orderNum = "18", type = ConvertFieldmappingEntry.class) + private List ConvertFieldmappingEntry; + + + + public String getDownEditFormVal(){ + + if(getDownInterfaceType() != null ){ + if( downRouteInterfaceMap != null && getDownInterfaceType().equals(Constant.InterfaceType_ROUTE) ){// 下游单据为路由表单 + return (String)downRouteInterfaceMap.get("formRouterName"); + }else{//下游单据为在线表单 + return String.valueOf(downEditInterface); + } + }else{ + return null; + } + + } + +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/model/GetSearchList.java b/common/common-botp/src/main/java/apelet/common/botp/model/GetSearchList.java new file mode 100644 index 0000000..3174772 --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/model/GetSearchList.java @@ -0,0 +1,79 @@ +package apelet.common.botp.model; + +import apelet.common.core.annotation.RelationDict; +import apelet.common.online.model.OnlineForm; +import cn.afterturn.easypoi.excel.annotation.Excel; +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +import java.util.Map; + +@Data +@Schema( description = "开发平台主表") +public class GetSearchList { + @TableId(type = IdType.ASSIGN_ID) + @Schema(description = "主键") + private Long id; + + @Excel(name = "源单标识", width = 15) + @Schema(description = "源单标识") + private String sourceNumber; + + + @Excel(name = "单据标识", width = 15) + @Schema(description = "单据标识") + private String tableName; + + @Excel(name = "单据名称", width = 15) + @Schema(description = "单据名称") + private String tableTxt; + + + @Excel(name = "下游界面类型", width = 15) + @Schema(description = "下游界面类型") + private String downInterfaceType; + + @Excel(name = "上游界面类型", width = 15) + @Schema(description = "上游界面类型") + private String upInterfaceType; + + + @Excel(name = "上游在线列表界面", width = 15) + @Schema(description = "上游在线列表界面(关联在线表单界面(OnlineForm))") + private Long upListInterface; + + @RelationDict( + masterIdField = "upListInterface", + equalOneToOneRelationField = "onlineForm", + slaveModelClass = OnlineForm.class, + slaveIdField = "formId", + slaveNameField = "formName") + @TableField(exist = false) + private Map upListInterfaceMap; + + + @Excel(name = "下游在线列表界面", width = 15) + @Schema(description = "下游在线列表界面(关联在线表单界面(OnlineForm))") + private Long downListInterface; + + @RelationDict( + masterIdField = "downListInterface", + equalOneToOneRelationField = "onlineForm", + slaveModelClass = OnlineForm.class, + slaveIdField = "formId", + slaveNameField = "formName") + @TableField(exist = false) + private Map downListInterfaceList; + + @Excel(name = "上游路由界面", width = 15) + @Schema(description = "上游路由界面(关联菜单管理)") + private Long upRouteInterface; + + @Excel(name = "下游路由界面", width = 15) + @Schema(description = "下游路由界面(关联菜单管理)") + private Long downRouteInterface; + +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/model/SysMenuqq.java b/common/common-botp/src/main/java/apelet/common/botp/model/SysMenuqq.java new file mode 100644 index 0000000..4a73cee --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/model/SysMenuqq.java @@ -0,0 +1,96 @@ +package apelet.common.botp.model; + +import apelet.common.core.base.model.BaseModel; +import com.baomidou.mybatisplus.annotation.*; +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +@Data +@Schema(description = "菜单管理") +@TableName(value = "xy_sys_menu") +public class SysMenuqq extends BaseModel { + + /** + * 主键Id。 + */ + @TableId(value = "menu_id") + private Long menuId; + + /** + * 父菜单Id,目录菜单的父菜单为null。 + */ + @TableField(value = "parent_id") + private Long parentId; + + /** + * 菜单显示名称。 + */ + @TableField(value = "menu_name") + private String menuName; + + /** + * 菜单类型(0: 目录 1: 菜单 2: 按钮 3: UI片段)。 + */ + @TableField(value = "menu_type") + private Integer menuType; + + /** + * 前端表单路由名称,仅用于menu_type为1的菜单类型。 + */ + @TableField(value = "form_router_name") + private String formRouterName; + + /** + * 在线表单主键Id,仅用于在线表单绑定的菜单。 + */ + @TableField(value = "online_form_id") + private Long onlineFormId; + + /** + * 在线表单菜单的权限控制类型,具体值可参考SysOnlineMenuPermType常量对象。 + */ + @TableField(value = "online_menu_perm_type") + private Integer onlineMenuPermType; + + /** + * 统计页面主键Id,仅用于统计页面绑定的菜单。 + */ + @TableField(value = "report_page_id") + private Long reportPageId; + + /** + * 仅用于在线表单的流程Id。 + */ + @TableField(value = "online_flow_entry_id") + private Long onlineFlowEntryId; + + /** + * 菜单显示顺序 (值越小,排序越靠前)。 + */ + @TableField(value = "show_order") + private Integer showOrder; + + /** + * 菜单图标。 + */ + private String icon; + + /** + * 附加信息。 + */ + @TableField(value = "extra_data") + private String extraData; + + /** + * 逻辑删除标记字段(1: 正常 -1: 已删除)。 + */ + @TableLogic + @TableField(value = "deleted_flag") + private Integer deletedFlag; + + /** + * 表单开发。 + */ + @TableField(value = "bill_exploit") + private String billExploit; +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/plugin/AbstractTransformPlugIn.java b/common/common-botp/src/main/java/apelet/common/botp/plugin/AbstractTransformPlugIn.java new file mode 100644 index 0000000..eb26111 --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/plugin/AbstractTransformPlugIn.java @@ -0,0 +1,55 @@ +package apelet.common.botp.plugin; + +import apelet.common.botp.plugin.entity.BotpRule; +import apelet.common.core.object.ObjectValue; +import apelet.common.core.util.ApplicationContextHolder; +import apelet.common.generator.utils.OrmGenDataSourceUtil; + +/** + * @author Soon + * @version 1.0 + * Create by 2024/1/16 18:01 + */ +public abstract class AbstractTransformPlugIn { + + /** + * 源单据描述 + */ + protected ObjectValue srcBillData; + /** + * 目标单据描述 + */ + protected ObjectValue destBillData; + /** + * 转换规则 + */ + protected BotpRule rule; + + + + /** + * 单据转换后事件,最后执行 + */ + public abstract void afterTransform(); + + + /** + * 目标字段赋值完毕后事件 + */ + public abstract void afterFieldMapping(); + + /** + * 设置转换上下文变量 + */ + public void setContext(ObjectValue srcBillData, ObjectValue destBillData, BotpRule rule){ + + this.srcBillData = srcBillData; + this.destBillData = destBillData; + this.rule = rule; + + } + public OrmGenDataSourceUtil ormGenDataSourceUtil(){ + return ApplicationContextHolder.getBean("ormGenDataSourceUtil"); + } + +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/plugin/BackPurReqTransformPlugIn.java b/common/common-botp/src/main/java/apelet/common/botp/plugin/BackPurReqTransformPlugIn.java new file mode 100644 index 0000000..64cdd6d --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/plugin/BackPurReqTransformPlugIn.java @@ -0,0 +1,56 @@ +package apelet.common.botp.plugin; + +import apelet.common.core.object.ObjectCollection; +import apelet.common.core.object.ObjectValue; +import apelet.common.orm.impl.Selector; +import apelet.common.orm.impl.SelectorItem; + +import java.math.BigDecimal; + +/** + * 采购申请下推采购订单后回写采购申请分录已订货数量 + */ +public class BackPurReqTransformPlugIn extends AbstractTransformPlugIn{ + + @Override + public void afterTransform() { + + } + + @Override + public void afterFieldMapping() { + //源单据 申请单 + ObjectCollection srcObjectCollection = + srcBillData.getObjectCollection("pur_apply_entry"); + //目标 订单 + ObjectCollection descObjectCollection = + destBillData.getObjectCollection("pm_purorderbill_entry"); + for (int i = 0 ; i < descObjectCollection.size() ; i++){ + + //目标单据 + ObjectValue objectValue = descObjectCollection.getObject(i); + BigDecimal qty = objectValue.getBigDecimal("qty"); + Long srcbillentryid = objectValue.getLong("srcbillentryid"); + //原单据 + for (int j = 0 ; j < srcObjectCollection.size() ; j++){ + ObjectValue srcobjv = srcObjectCollection.getObject(j); + Long srcEntryId = srcobjv.getLong("id"); + if(srcEntryId==srcbillentryid){ + ObjectValue purReqObjV = new ObjectValue("pur_apply_entry"); + purReqObjV.put("id",srcEntryId); + purReqObjV.put("orderqty",srcobjv.getBigDecimal("orderqty").add(qty)); + Selector selector = new Selector(); + selector.getList().add(new SelectorItem("orderqty")); + try{ + ormGenDataSourceUtil().update(purReqObjV.getTableName(),purReqObjV,selector); + }catch (Exception e1){ + e1.printStackTrace();; + throw new RuntimeException(e1); + } + } + } + + + } + } +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/plugin/PurorderTransformPlugIn.java b/common/common-botp/src/main/java/apelet/common/botp/plugin/PurorderTransformPlugIn.java new file mode 100644 index 0000000..52f3b82 --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/plugin/PurorderTransformPlugIn.java @@ -0,0 +1,35 @@ +package apelet.common.botp.plugin; + +import apelet.common.core.object.ObjectCollection; +import apelet.common.core.object.ObjectValue; + +import java.math.BigDecimal; + +/** + * @author Soon + * @version 1.0 + * Create by 2024/4/22 11:15 + */ +public class PurorderTransformPlugIn extends AbstractTransformPlugIn{ + + + @Override + public void afterTransform() { + + } + + @Override + public void afterFieldMapping() { + ObjectCollection objectCollection = + destBillData.getObjectCollection("pur_order_entry"); + for (int i = 0 ; i < objectCollection.size() ; i++){ + + ObjectValue objectValue = objectCollection.getObject(i); + BigDecimal qty = objectValue.getBigDecimal("qty"); + BigDecimal price = objectValue.getBigDecimal("price"); + BigDecimal amount = qty.multiply(price); + objectValue.setBigDecimal("amount",amount); + + } + } +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/plugin/ReverseWritingPlugIn.java b/common/common-botp/src/main/java/apelet/common/botp/plugin/ReverseWritingPlugIn.java new file mode 100644 index 0000000..18db7a1 --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/plugin/ReverseWritingPlugIn.java @@ -0,0 +1,198 @@ +package apelet.common.botp.plugin; + +import apelet.common.core.exception.MyRuntimeException; +import apelet.common.core.object.ObjectCollection; +import apelet.common.core.object.ObjectValue; +import apelet.common.core.util.ApplicationContextHolder; +import apelet.common.generator.dto.ReverseWritingRulesDto; +import apelet.common.generator.model.ReverseWritingBusiness; +import apelet.common.generator.model.ReverseWritingFormula; +import apelet.common.generator.service.impl.ReverseWritingRulesServiceImpl; +import apelet.common.generator.utils.OrmGenDataSourceUtil; +import apelet.common.online.service.impl.OnlineFormServiceImpl; +import apelet.common.online.util.Jexl3Util; +import apelet.common.orm.impl.Selector; +import apelet.common.orm.impl.SelectorItem; +import cn.hutool.core.util.ObjectUtil; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; + +import java.util.*; +import java.util.stream.Collectors; + +/** + * 采购申请下推采购订单后回写采购申请分录已订货数量 + */ +public class ReverseWritingPlugIn extends AbstractTransformPlugIn { + + + private final ReverseWritingRulesServiceImpl reverseWritingRulesService = + ApplicationContextHolder.getBean(ReverseWritingRulesServiceImpl.class); + private final OnlineFormServiceImpl onlineFormService = + ApplicationContextHolder.getBean(OnlineFormServiceImpl.class); + private final OrmGenDataSourceUtil ormGenDataSourceUtil = + ApplicationContextHolder.getBean(OrmGenDataSourceUtil.class); + private final Jexl3Util Jexl3Util = + ApplicationContextHolder.getBean(Jexl3Util.class); + + + + @Override + public void afterTransform() { + + } + + /** + * 源单据 srcBillData + * 目标单据 destBillData + */ + @Override + public void afterFieldMapping() { + try { + String destBillType = rule.getDestBillType(); + String sourceBillType = rule.getSourceBillType(); + List rulesList = reverseWritingRulesService.listAll(); + List collect = rulesList.stream() + .filter(f -> f.getSourceDocuments().toString().equals(sourceBillType) && + f.getTargetDoc().toString().equals(destBillType) && + f.getTriggerTiming().equals("1") + ) + .collect(Collectors.toList()); + collect.forEach(f -> { + // 业务规则 + f.getBusinessList().stream().filter(i -> i.getEnable() == 1).forEach(this::a); + // 反写公式 根据目标单据数据 -> 修改原单据 + f.getFormulaList().stream().filter(i -> i.getEnable() == 1).forEach(this::b); + }); + }catch (Exception e){ + throw new MyRuntimeException(e); + } + } + + void a(ReverseWritingBusiness b) { + String preconditionsEnglish = b.getPreconditionsEnglish(); + JSONObject preconditionsJson = JSON.parseObject(b.getPreconditionsJson()); + String preconditionsField = b.getPreconditionsField(); + JSONObject jsonObject = JSON.parseObject(preconditionsField); + Map hashMap = Jexl3Util.getMapValue(jsonObject, destBillData); + Object expression = Jexl3Util.expression(preconditionsEnglish, hashMap); + + Object func = onlineFormService.func(preconditionsEnglish, preconditionsJson, destBillData); + String established = ""; + String establishedField = ""; + String establishedJson = ""; + if (func instanceof Boolean && func.equals(true)) { + // 成立 + established = b.getEstablishedEnglish(); + establishedField = b.getEstablishedField(); + establishedJson = b.getEstablishedJson(); + } else { + // 不成立 + established = b.getNotEstablishedEnglish(); + establishedField = b.getNotEstablishedField(); + establishedJson = b.getNotEstablishedJson(); + } +// Map map = Jexl3Util.getMapValue(JSON.parseObject(establishedField), destBillData); +// Jexl3Util.expression(established, map); + // 执行操作 + JSONObject json = JSON.parseObject(establishedJson); + String expressionTransl = json.getString("expressionTranslation"); + List split = Arrays.asList(expressionTransl.split("=")); + String fun = ""; + for (String s : split) { + s = s.trim(); + if (s.startsWith("$") && s.endsWith("$")) { + fun = s; + } + } + fun = Jexl3Util.getMySplit("\\$(.*?)\\$", fun); + List funParam = Arrays.asList(Jexl3Util.getMySplit("\\((.*?)\\)", fun).split(",")); + Object[] objects = Jexl3Util.getFunParam(funParam, destBillData); + Object o = onlineFormService.executeFunction(json, fun, objects); + + // 修改单据 + List s = Arrays.asList(split.get(0).split("\\.")); + if (s.get(0).equals(s.get(1))) { + // 表头 + destBillData.put(s.get(s.size()-1), o); + try { +// ormGenDataSourceUtil.update(destBillData.getTableName(),destBillData,null); + } catch (Exception e) { + throw new MyRuntimeException(e); + } + }else{ + // 分录 TODO 待确定 + + } + } + + + /** + * 根据目标单据数据 -> 修改原单据 + * @param b + */ + void b(ReverseWritingFormula b) { + String conditionEnglish = b.getConditionEnglish(); // 条件 + String conditionField = b.getConditionField(); + JSONObject conditionJson = JSON.parseObject(b.getConditionJson()); + +// JSONObject jsonObject = JSON.parseObject(conditionField); +// Map hashMap = Jexl3Util.getMapValue(jsonObject, destBillData); +// Object expression = Jexl3Util.expression(conditionEnglish, hashMap); + + Object func = onlineFormService.func(conditionEnglish, conditionJson, srcBillData); + + if (Jexl3Util.judgmentFunc(conditionEnglish, func)) { + // 反写公式 + String formulaEnglish = b.getFormulaEnglish(); + JSONObject formulaJson = JSON.parseObject(b.getFormulaJson()); + Object func1 = onlineFormService.func(formulaEnglish, formulaJson, srcBillData); + + + String formula = b.getFormulaEnglish().replaceAll("\\s", ""); // 公式 + String[] formulas = formula.split("\\."); + ObjectCollection o = (ObjectCollection) destBillData.getValues().get(formulas[1]); + Iterator iterator = o.iterator(); + while (iterator.hasNext()) { + ObjectValue next = (ObjectValue) iterator.next(); + Object destValue = next.getValues().get(formulas[2]) == null ? 0 : next.getValues().get(formulas[2]); + String sourceSingleField = b.getSourceSingleField().replaceAll("\\s", ""); // 源单字段 + String[] srcStr = sourceSingleField.split("\\."); + ObjectCollection o1 = (ObjectCollection) srcBillData.getValues().get(srcStr[1]); + Iterator iterator2 = o1.iterator(); + while (iterator2.hasNext()) { + ObjectValue next2 = (ObjectValue) iterator2.next(); + if (!ObjectUtil.contains(next2.get("number"), next.get("number"))) { + continue; + } + Object srcValue = next2.getValues().get(srcStr[2]) == null ? 0 : next2.getValues().get(srcStr[2]); + String a = ""; + switch (b.getMode()) { // 累加方式 1:累加, 2:扣减, 3:覆盖 + case "1": { + a = String.valueOf((Integer.parseInt(srcValue.toString()) + Integer.parseInt(destValue.toString()))); + break; + } + case "2": { + a = String.valueOf((Integer.parseInt(srcValue.toString()) - Integer.parseInt(destValue.toString()))); + break; + } + case "3": { + a = destValue.toString(); + break; + } + } + ObjectValue purReqObjV = new ObjectValue(srcStr[1]); + purReqObjV.put("id", next2.get("id")); + purReqObjV.put(srcStr[2], a); + Selector selector = new Selector(); + selector.getList().add(new SelectorItem(srcStr[2])); + try { + ormGenDataSourceUtil().update(purReqObjV.getTableName(), purReqObjV, selector); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + } + } + } +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/plugin/entity/BillEntity.java b/common/common-botp/src/main/java/apelet/common/botp/plugin/entity/BillEntity.java new file mode 100644 index 0000000..98d5335 --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/plugin/entity/BillEntity.java @@ -0,0 +1,19 @@ +package apelet.common.botp.plugin.entity; + +import lombok.Data; + +/** + * @author Soon + * @version 1.0 + * Create by 2024/1/16 18:01 + */ +@Data +public class BillEntity { + + /** + * 单据标识 + */ + private String billType; + + +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/plugin/entity/BotpRule.java b/common/common-botp/src/main/java/apelet/common/botp/plugin/entity/BotpRule.java new file mode 100644 index 0000000..b0d3d56 --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/plugin/entity/BotpRule.java @@ -0,0 +1,38 @@ +package apelet.common.botp.plugin.entity; + +import lombok.Data; +/** + * @author Soon + * @version 1.0 + * Create by 2024/1/16 18:01 + */ +@Data +public class BotpRule { + + /** + * 规则id + */ + private long id; + + /** + * 规则编码 + */ + private String number; + + /** + * 规则名称 + */ + private String name; + + /** + * 源单标识 + */ + private String sourceBillType; + + /** + * 目标单标识 + */ + private String destBillType; + + +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/service/IBillBaseService.java b/common/common-botp/src/main/java/apelet/common/botp/service/IBillBaseService.java new file mode 100644 index 0000000..fdaf397 --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/service/IBillBaseService.java @@ -0,0 +1,80 @@ +package apelet.common.botp.service; + + +import apelet.common.core.annotation.MyRequestBody; +import apelet.common.core.base.service.IBaseService; +import apelet.common.core.object.*; +import com.github.pagehelper.Page; + +import java.io.Serializable; +import java.util.List; + +/** + * 业务单据Service + * @param + * @param + */ +public interface IBillBaseService extends IBaseService { + + + + /** + * 单据列表 + * @param m + * @param orderParam + * @param pageParam + * @param traceParamDto + * @return 返回分页列表数据 + */ + Page listBill(M m, + MyOrderParam orderParam, + MyPageParam pageParam, + TraceParamDto traceParamDto + + ); + + /** + * 保存单据 + * @param m 单据实体 + * @param crDto 关联关系 + */ + void saveBill(M m, List crDto); + + + /** + * 提交单据,如果有流程标识,提交进入工作流 + * @param processDefinitionKey + * @param m + * @param crDto + */ + void submitBill(String processDefinitionKey,M m, @MyRequestBody List crDto); + + + /** + * 提交单据信息,如果有单据标识,提交进入工作流 + * @param processDefinitionKey 流程标识 + * @param id + */ + void submitBillKey(String processDefinitionKey,Long id); + + + /** + * 查询单据信息,包含分录信息 + * @param id + * @return + */ + M detailBill(K id); + + + + + /** + * 删除单据 + * @param ids 单据id集合 + * @return + */ + Integer removeBillById(String ids); + + + +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/service/IConvertFieldmappingEntryService.java b/common/common-botp/src/main/java/apelet/common/botp/service/IConvertFieldmappingEntryService.java new file mode 100644 index 0000000..82212e8 --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/service/IConvertFieldmappingEntryService.java @@ -0,0 +1,17 @@ +package apelet.common.botp.service; + +import apelet.common.botp.model.ConvertFieldmappingEntry; +import apelet.common.core.base.service.IBaseService; + +import java.util.List; + +/** + * @author admin + * @since 2024-01-18 10:31:58 + */ +public interface IConvertFieldmappingEntryService extends IBaseService { + List getConvertFieldmappingEntryRelation(Long id); + + List getConvertFieldmappingEntryListWithRelation(ConvertFieldmappingEntry convertFieldmappingEntry, String buildOrderBy); + +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/service/IConvertPluginEntryService.java b/common/common-botp/src/main/java/apelet/common/botp/service/IConvertPluginEntryService.java new file mode 100644 index 0000000..a125eb5 --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/service/IConvertPluginEntryService.java @@ -0,0 +1,16 @@ +package apelet.common.botp.service; + +import apelet.common.botp.model.ConvertPluginEntry; +import apelet.common.core.base.service.IBaseService; + +import java.util.List; + +/** + * @author admin + * @since 2024-01-18 10:31:58 + */ +public interface IConvertPluginEntryService extends IBaseService { + List getConvertPluginEntryRelation(Long id); + + List getConvertPluginEntryListWithRelation(ConvertPluginEntry convertPluginEntryFilter, String buildOrderBy); +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/service/IConvertRelationEntryService.java b/common/common-botp/src/main/java/apelet/common/botp/service/IConvertRelationEntryService.java new file mode 100644 index 0000000..ee3260f --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/service/IConvertRelationEntryService.java @@ -0,0 +1,22 @@ +package apelet.common.botp.service; + +import apelet.common.botp.model.ConvertRelationEntry; +import apelet.common.core.base.service.IBaseService; + +import java.util.List; + +/** + * @author admin + * @since 2024-01-18 10:31:58 + */ +public interface IConvertRelationEntryService extends IBaseService { + + Boolean removeAllById(Long id); + + Boolean editAll(ConvertRelationEntry convertRelationEntry); + + Boolean addAll(ConvertRelationEntry convertRelationEntry); + + List getConvertRuleListWithRelation(ConvertRelationEntry convertRelationEntryFilter, String buildOrderBy); + +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/service/IConvertRelationService.java b/common/common-botp/src/main/java/apelet/common/botp/service/IConvertRelationService.java new file mode 100644 index 0000000..a45d87d --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/service/IConvertRelationService.java @@ -0,0 +1,30 @@ +package apelet.common.botp.service; + +import apelet.common.botp.model.ConvertRelation; +import apelet.common.core.base.service.IBaseService; + +import java.util.List; +import java.util.Map; + +/** + * @author admin + * @since 2024-01-18 10:31:58 + */ +public interface IConvertRelationService extends IBaseService { + + Boolean removeAllById(Long id); + + Boolean editAll(ConvertRelation convertRelation); + + Boolean addAll(ConvertRelation convertRelation); + + List getConvertRuleListWithRelation(ConvertRelation convertRelationFilter, String buildOrderBy); + + + public List transform(String botpId, String srcBill, String destBill, String srcBillId); + + public List transformT(String botpId, String srcBill, String destBill, List srcBillList); + + //根据联查单据id、单据标识、上查/下查 ,根据单据关联关系表查询关联查询的单据 + public List> getConvertRelation(String billId, String billType, String searchType); +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/service/IConvertRuleService.java b/common/common-botp/src/main/java/apelet/common/botp/service/IConvertRuleService.java new file mode 100644 index 0000000..ce975c6 --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/service/IConvertRuleService.java @@ -0,0 +1,90 @@ +package apelet.common.botp.service; + +import apelet.common.botp.dto.ConvertRelationDelDto; +import apelet.common.botp.dto.ConvertRelationListDto; +import apelet.common.botp.dto.TransformResultDto; +import apelet.common.botp.model.*; +import apelet.common.core.base.service.IBaseService; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * @author admin + * @since 2024-01-18 10:31:58 + */ +public interface IConvertRuleService extends IBaseService { + //查询全部信息 + public List selectAll(String id); + + //查询返回源单和目标单全部字段 + public List allField(String tableName); + + Boolean removeAllById(Long id); + + Boolean editAll(ConvertRule convertRule); + + Boolean addAll(ConvertRule convertRule); + + List getConvertRuleListWithRelation(ConvertRule convertRuleFilter, String buildOrderBy); + + List getConvertPluginEntry(Long id); + List getConvertFieldmappingEntry(Long id); + + + + + /** + * 删除单据关联关系 + * @param dto + * @return + */ + public boolean removeAllRelation(ConvertRelationDelDto dto); + + /** + * @botpId 转准规则id + * @srcBill 源单据元数据id + * @destBill 目标单据元数据id + * @srcbillId 源单据id + * @return + */ + public TransformResultDto transform(String botpId, String srcBill, String destBill, String srcBillId); + + /** + * @botpId 转准规则id + * @srcBill 源单据元数据id + * @destBill 目标单据元数据id + * @srcbillId 源单据id集合 + * @return + */ + public TransformResultDto transform(String botpId, String srcBill, String destBill, Set srcBillList); + + + + + + + /** + * 根据目标单查询关联关系 + * @param dto + * @return + */ + public List selectAllRelationByTarget(ConvertRelationListDto dto); + + /** + * 根据源单查询关联关系 + * @param dto + * @return + */ + public List selectAllRelationBySource(ConvertRelationListDto dto); + + /** + * 下推规则查询 + * @param dto + * @return + */ + public List> getPushBillList(ConvertRelationDelDto dto); + + List> getRuleTableFiled(String tableName); +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/service/ISysMenuqqService.java b/common/common-botp/src/main/java/apelet/common/botp/service/ISysMenuqqService.java new file mode 100644 index 0000000..6035006 --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/service/ISysMenuqqService.java @@ -0,0 +1,27 @@ +package apelet.common.botp.service; + +import apelet.common.botp.model.AllField; +import apelet.common.botp.model.SysMenuqq; +import apelet.common.core.base.service.IBaseService; + +import java.util.List; + +/** + * @author admin + * @since 2024-01-18 10:31:58 + */ +public interface ISysMenuqqService extends IBaseService { + //查询全部信息 + public List selectAll(String id); + + //查询返回源单和目标单全部字段 + public List allField(String tableName); + + Boolean removeAllById(Long id); + + Boolean editAll(SysMenuqq sysMenuqq); + + Boolean addAll(SysMenuqq sysMenuqq); + + +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/service/execute/BotpService.java b/common/common-botp/src/main/java/apelet/common/botp/service/execute/BotpService.java new file mode 100644 index 0000000..51362b4 --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/service/execute/BotpService.java @@ -0,0 +1,604 @@ +package apelet.common.botp.service.execute; + +import apelet.common.botp.dao.ConvertRelationEntryMapper; +import apelet.common.botp.dao.ConvertRelationMapper; +import apelet.common.botp.db.object.*; +import apelet.common.botp.db.util.DbUtil; +import apelet.common.botp.model.*; +import apelet.common.botp.plugin.entity.BotpRule; +import apelet.common.botp.service.execute.entity.*; +import apelet.common.botp.service.execute.mapping.BotpMappingContext; +import apelet.common.core.config.DataSourceInfo; +import apelet.common.core.object.ObjectCollection; +import apelet.common.core.object.ObjectValue; +import apelet.common.core.object.TokenData; +import apelet.common.dbutil.constant.DblinkType; +import apelet.common.dbutil.provider.DataSourceProvider; +import apelet.common.generator.dao.OnlFormFieldMapper; +import apelet.common.generator.dao.OnlFormHeadMapper; +import apelet.common.generator.model.OnlFormField; +import apelet.common.generator.model.OnlFormHead; +import apelet.common.generator.service.IOnlFormHeadService; +import apelet.common.generator.utils.OrmGenDataSourceUtil; +import apelet.common.online.model.constant.FieldFilterType; +import apelet.common.orm.impl.Selector; +import apelet.common.orm.impl.SelectorItem; +import apelet.common.sequence.wrapper.IdGeneratorWrapper; +import cn.hutool.core.util.StrUtil; +import com.alibaba.fastjson.JSON; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; + +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Transactional; + +import java.io.Serializable; +import java.lang.reflect.Method; +import java.time.LocalDateTime; +import java.util.*; +import java.util.stream.Collectors; + +/** + * @author sunquan + * @version 1.0 + * Create by 2024/1/22 16:00 + */ +@Component +@Slf4j +public class BotpService { + + + @Autowired + private ConvertRelationMapper convertRelationMapper; + @Autowired + private ConvertRelationEntryMapper convertRelationEntryMapper; + @Autowired + private IdGeneratorWrapper idGenerator; + @Autowired + private DbUtil dbUtil; + + @Autowired + private OnlFormHeadMapper onlFormHeadMapper; + @Autowired + private OnlFormFieldMapper onlFormFieldMapper; + + @Autowired + private OrmGenDataSourceUtil ormGenDataSourceUtil; + + @Autowired + private IOnlFormHeadService onlFormHeadService; + + /** + * @param convertRule 规则 + * @param convertFieldmappingEntryList 映射分录 + * @param convertPluginEntryList 插件分录 + * @param srcFormHead 源元数据 + * @param destFormHead 目标元数据 + * @param srcBillId 源单据id + * @return 返回实体数据 + */ + @Transactional(rollbackFor = Exception.class) + public BtpTransformResult transform( + ConvertRule convertRule, + List convertFieldmappingEntryList, + List convertPluginEntryList, + OnlFormHead srcFormHead, + OnlFormHead destFormHead, + Set srcBillId) { + + String srcTable = srcFormHead.getTableName();//源元数据表名 + List + mappingFieldList = + convertFieldmappingEntryList.stream().filter(item -> StringUtils.isNotEmpty(item.getOldfieldNumber()) + && StringUtils.isNotEmpty(item.getNewfieldNumber()) + ).collect(Collectors.toList());//过滤掉没有配置字段映射的行 + Map selectTableMap = new HashMap<>(); + Map insertTableMap = new HashMap<>(); + + Map convertColumnConfigs = new HashMap<>(); + Map tableMap = new HashMap<>(); + for (ConvertFieldmappingEntry convertFieldmappingEntry : mappingFieldList) {//构建单据转换参数 + String oldfieldNumber = convertFieldmappingEntry.getOldfieldNumber(); + String newfieldNumber = convertFieldmappingEntry.getNewfieldNumber(); + + String srcTableNumber = null;//源单表名 + String srcColumnNumber = null;//源单字段 + if (StringUtils.isNotEmpty(oldfieldNumber)) { + OnlFormField onlFormField = onlFormFieldMapper.selectById(oldfieldNumber); + OnlFormHead onlFormHead = tableMap.get(onlFormField.getHeadId()); + if (onlFormHead == null) { + onlFormHead = onlFormHeadMapper.selectById(onlFormField.getHeadId()); + tableMap.put(onlFormField.getHeadId(), onlFormHead); + } + srcTableNumber = onlFormHead.getTableName(); + srcColumnNumber = onlFormField.getFieldName(); + } else {//配置的源字段为空,则跳过 + continue; + } + + OnlFormField onlFormField = onlFormFieldMapper.selectById(newfieldNumber); + OnlFormHead onlFormHead = tableMap.get(onlFormField.getHeadId()); + if (onlFormHead == null) { + onlFormHead = onlFormHeadMapper.selectById(onlFormField.getHeadId()); + tableMap.put(onlFormField.getHeadId(), onlFormHead); + } + String destTableNumber = onlFormHead.getTableName(); + String destColumnNumber = onlFormField.getFieldName(); + + MetaColumn srcMainColumn = this.genMetaTable(selectTableMap, srcTableNumber, srcColumnNumber, srcFormHead); + MetaColumn destMainColumn = this.genMetaTable(insertTableMap, destTableNumber, destColumnNumber, destFormHead); + + ConvertColumnConfig convertColumnConfig = new ConvertColumnConfig(); + convertColumnConfig.setColumnName(srcColumnNumber);//源表字段 + convertColumnConfig.setTableName(srcTableNumber);//源表 + convertColumnConfig.setMain(srcMainColumn == null ? false : srcMainColumn.isMain());//是否主表字段 + convertColumnConfig.setValueMethod(Integer.parseInt(convertFieldmappingEntry.getValueMethod()));//方法 + convertColumnConfig.setValue(convertFieldmappingEntry.getCltValue());//默认值 + convertColumnConfig.setValue(convertFieldmappingEntry.getCltValue());//默认值 + + if (org.apache.commons.lang3.StringUtils.isNotEmpty(convertFieldmappingEntry.getCalculationJson())) { + convertColumnConfig.setCalculationFormula(JSON.parseObject(convertFieldmappingEntry.getCalculationJson())); + } + convertColumnConfigs.put(destMainColumn, convertColumnConfig); + + } + ObjectValue srcBillData = getBillData(selectTableMap, srcBillId.iterator().next());//源单数据 + ConvertConfig convertConfig = new ConvertConfig(); + convertConfig.setSrcMetaTable(selectTableMap.get(srcFormHead.getTableName())); + convertConfig.setDestMetaTable(insertTableMap.get(destFormHead.getTableName())); + convertConfig.setColumnConfigMap(convertColumnConfigs); + + BtpTransformResult btpTransformResult = this.convertToDestBill(srcBillData, insertTableMap, convertConfig, convertRule);//转换 + //转换插件 + executePlugin(srcBillData, btpTransformResult.getBillDataList().getObject(0), convertPluginEntryList, convertRule, "afterFieldMapping");//映射完成执行 + if (convertRule.getAutoSave().equals("true")) {//转后直接保存单据 + addNew(btpTransformResult, insertTableMap.get(destFormHead.getTableName())); + } + //转换插件 + executePlugin(srcBillData, btpTransformResult.getBillDataList().getObject(0), convertPluginEntryList, convertRule, "afterTransform");//转换后执行 + return btpTransformResult; + } + + /** + * 执行转换规则 + * + * @param convertPluginEntryList + */ + private void executePlugin( + ObjectValue srcObjectValue, + ObjectValue destObjectValue, + List convertPluginEntryList//转换规则 + , ConvertRule convertRule, + String method + ) { + BotpRule botpRule = new BotpRule(); + botpRule.setId(convertRule.getId()); + botpRule.setName(convertRule.getName()); + botpRule.setNumber(convertRule.getNumber()); + botpRule.setSourceBillType(convertRule.getSourceEntityId()); + botpRule.setDestBillType(convertRule.getTargetEntityId()); + + List list = + convertPluginEntryList.stream().sorted(Comparator.comparing(ConvertPluginEntry::getSerialNumber)).collect(Collectors.toList()); + for (ConvertPluginEntry sortDto : list) { + try { + Class clazz = Class.forName(sortDto.getClassName()); + Class superClass = clazz.getSuperclass(); + Class[] parameterTypes = new Class[3]; + parameterTypes[0] = ObjectValue.class; + parameterTypes[1] = ObjectValue.class; + parameterTypes[2] = BotpRule.class; + Method ctxMethod = superClass.getDeclaredMethod("setContext", parameterTypes); + + Object ob = clazz.newInstance(); + ctxMethod.invoke(ob, srcObjectValue, destObjectValue, botpRule); + Method exeMethod = superClass.getDeclaredMethod(method); + exeMethod.invoke(ob); + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException(e); + } + } + } + + /** + * 新增数据 + * + * @param btpTransformResul + * @param metaTable + */ + private void addNew(BtpTransformResult btpTransformResult, MetaTable metaTable) { + + try { + ObjectValue destBillData = btpTransformResult.getBillDataList().getObject(0); + ormGenDataSourceUtil.addNew(metaTable.getTableName(), destBillData); + this.saveRelation(btpTransformResult.getBillRelationList().get(0), destBillData); + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException(e); + } + + } + + private void saveRelation(BillRelation billRelation, ObjectValue destBillData) { + + ConvertRelation convertRelation = new ConvertRelation(); + convertRelation.setId(billRelation.getId()); + convertRelation.setConvertRuleId(billRelation.getConvertRuleId()); + convertRelation.setSourceId(billRelation.getSourceId()); + convertRelation.setSourceNumber(billRelation.getSourceNumber()); + convertRelation.setTargetId(String.valueOf(destBillData.getPkValue())); + convertRelation.setTargetNumber(billRelation.getTargetNumber()); + convertRelation.setCreateUserId(TokenData.takeFromRequest().getUserId()); + convertRelation.setCreateTime(new Date()); + convertRelation.setUpdateUserId(TokenData.takeFromRequest().getUserId()); + convertRelation.setUpdateTime(new Date()); + convertRelationMapper.insert(convertRelation); + + for (BillRelationEntry billRelationEntry : billRelation.getBillRelationEntryList()) { + ConvertRelationEntry convertRelationEntry = new ConvertRelationEntry(); + convertRelationEntry.setId(billRelationEntry.getId()); + convertRelationEntry.setConvertRuleId(billRelationEntry.getConvertRuleId()); + convertRelationEntry.setSourceEntryId(billRelationEntry.getSourceEntryId()); + convertRelationEntry.setSourceEntryNumber(billRelationEntry.getSourceEntryNumber()); + convertRelationEntry.setSourceId(billRelationEntry.getSourceId()); + convertRelationEntry.setSourceNumber(billRelationEntry.getSourceNumber()); + convertRelationEntry.setTargeEntryId(billRelationEntry.getTargeEntryId()); + convertRelationEntry.setTargetId(String.valueOf(destBillData.getPkValue())); + convertRelationEntry.setTargeEntryNumber(billRelationEntry.getTargeEntryNumber()); + convertRelationEntry.setTargetNumber(billRelationEntry.getTargetNumber()); + convertRelationEntry.setCreateUserId(TokenData.takeFromRequest().getUserId()); + convertRelationEntry.setCreateTime(new Date()); + convertRelationEntry.setUpdateUserId(TokenData.takeFromRequest().getUserId()); + convertRelationEntry.setUpdateTime(new Date()); + convertRelationEntryMapper.insert(convertRelationEntry); + } + + } + + /** + * 插入数据 + * + * @param tableName + * @param columnNames + * @param columnValueList + */ + private ObjectSqlData doInsert(String tableName, String columnNames, List columnValueList) { + StringBuilder sql = new StringBuilder(512); + sql.append("INSERT INTO ").append(tableName).append(" (").append(columnNames).append(") VALUES ("); + sql.append(StrUtil.repeat("?,", columnValueList.size())); + sql.setLength(sql.length() - 1); + sql.append(")"); + List columnValues = + columnValueList.stream().map(Serializable.class::cast).collect(Collectors.toList()); + ObjectSqlData objectSqlData = new ObjectSqlData(); + objectSqlData.setSql(sql.toString()); + objectSqlData.setDataList(columnValueList); + return objectSqlData; + } + + + private void makeupBillData(Map dataMap) { + dataMap.put("create_time", LocalDateTime.now()); + dataMap.put("create_user_id", TokenData.takeFromRequest().getUserId()); + } + + private InsertData makeColumnNames(Map data) { + InsertData insertData = new InsertData(); + StringBuilder sb = new StringBuilder(512); + for (String columnData : data.keySet()) { + sb.append(columnData).append(","); + insertData.getDataList().add(data.get(columnData)); + } + String columnNames = sb.substring(0, sb.length() - 1); + insertData.setColumnNames(columnNames); + return insertData; + } + + + /** + * @param srcBillData 源单据数据 + * @param insertTableMap 目标元数据表,字段 + * @param convertConfig 规则配置 + * @return 目标单据数据 + */ + private BtpTransformResult convertToDestBill(ObjectValue srcBillData, Map insertTableMap, ConvertConfig convertConfig, ConvertRule convertRule) { + + BtpTransformResult btpTransformResult = initDestBillData(convertConfig, srcBillData, convertRule); + for (MetaColumn destMetaColumn : convertConfig.getColumnConfigMap().keySet()) { + ConvertColumnConfig convertColumnConfig = convertConfig.getColumnConfigMap().get(destMetaColumn); + new BotpMappingContext(convertColumnConfig.getValueMethod()).mapping(btpTransformResult.getBillDataList().getObject(0), destMetaColumn, convertColumnConfig, srcBillData); + } + + return btpTransformResult; + } + + /** + * 初始化目标数据 + * + * @param convertConfig 映射配置 + * @param srcBillData 源单数据 + * @return + */ + private BtpTransformResult initDestBillData(ConvertConfig convertConfig, ObjectValue srcBillData, ConvertRule convertRule) { + try { + Set destTableSet = new HashSet<>(); + Set destEntryTableSet = new HashSet<>(); + String mainTableName = null; + String entryTableName = null;//源表只取一个分录 + for (MetaColumn destMetaColumn : convertConfig.getColumnConfigMap().keySet()) { + ConvertColumnConfig convertColumnConfig = convertConfig.getColumnConfigMap().get(destMetaColumn); + if (!destMetaColumn.isMain()) { + destTableSet.add(destMetaColumn.getMetaTable());//目标表表名集合 + if (convertColumnConfig.getColumnName() != null) {//源字段 + if (!convertColumnConfig.getTableName().equals(convertConfig.getSrcMetaTable().getTableName())) {//如果配置的不是源表表头,则记录 + destEntryTableSet.add(destMetaColumn.getMetaTable()); + } + } + entryTableName = convertColumnConfig.getTableName(); + } else { + mainTableName = convertColumnConfig.getTableName(); + } + } + ObjectValue destBillData = new ObjectValue(convertConfig.getDestMetaTable().getTableName()); + List billRelationEntryList = new ArrayList<>(); + ConvertColumnConfig convertColumnConfig = null; + Iterator iterator = convertConfig.getColumnConfigMap().values().iterator(); + while (iterator.hasNext()) { + convertColumnConfig = iterator.next(); + if (convertColumnConfig.getTableName() != null) { + break; + } + } + OnlFormHead srcOnlFormHead = onlFormHeadService.getHeadTableNameCache(convertColumnConfig.getTableName()); +// OnlFormHead srcOnlFormHead = onlFormHeadMapper.selectOne((QueryWrapper) (new QueryWrapper<>().eq("table_name", ))); + for (String tableName : destTableSet) { + if (destBillData.get(tableName) == null) { + ObjectCollection dataList = new ObjectCollection(); + if (destEntryTableSet.contains(tableName)) {//分录字段映射包含分录字段,分录初始化行数为源单分录行数 + ObjectCollection objectCollection = srcBillData.getObjectCollection(entryTableName); + for (int i = 0; i < objectCollection.size(); i++) { + OnlFormHead destOnlFormHead + = onlFormHeadMapper.selectOne((QueryWrapper) (new QueryWrapper<>().eq("table_name", tableName))); + ObjectValue entryData = new ObjectValue(tableName); + entryData.setLong(entryData.getPKField(), idGenerator.nextLongId()); + BillRelationEntry billRelationEntry = new BillRelationEntry(); + billRelationEntry.setId(idGenerator.nextLongId()); + billRelationEntry.setConvertRuleId(String.valueOf(convertRule.getId())); + billRelationEntry.setSourceEntryId(String.valueOf(objectCollection.getObject(i).get("id"))); + billRelationEntry.setSourceEntryNumber(String.valueOf(srcOnlFormHead.getId())); + billRelationEntry.setSourceId(String.valueOf(srcBillData.get("id"))); + billRelationEntry.setSourceNumber(convertRule.getSourceEntityId()); + billRelationEntry.setTargeEntryId(String.valueOf(entryData.get("id"))); + billRelationEntry.setTargetId(String.valueOf(destBillData.get("id"))); + billRelationEntry.setTargeEntryNumber(String.valueOf(destOnlFormHead.getId())); + billRelationEntry.setTargetNumber(convertRule.getTargetEntityId()); + billRelationEntry.setCreateUserId(TokenData.takeFromRequest().getUserId()); + billRelationEntry.setCreateTime(new Date()); + billRelationEntry.setUpdateUserId(TokenData.takeFromRequest().getUserId()); + billRelationEntry.setUpdateTime(new Date()); + billRelationEntryList.add(billRelationEntry); + dataList.addObject(entryData); + } + } else { + ObjectValue entryData = new ObjectValue(tableName); + entryData.setLong(entryData.getPKField(), idGenerator.nextLongId()); + dataList.addObject(entryData); + } + destBillData.putObjectCollection(tableName, dataList); + } + } + BtpTransformResult btpTransformResult = new BtpTransformResult(); + btpTransformResult.getBillDataList().addObject(destBillData); + BillRelation billRelation = new BillRelation(); + billRelation.setId(idGenerator.nextLongId()); + billRelation.setConvertRuleId(String.valueOf(convertRule.getId())); + billRelation.setSourceId(String.valueOf(srcBillData.get("id"))); + billRelation.setSourceNumber(convertRule.getSourceEntityId()); + billRelation.setTargetId(String.valueOf(destBillData.get("id"))); + billRelation.setTargetNumber(convertRule.getTargetEntityId()); + billRelation.setBillRelationEntryList(billRelationEntryList); + billRelation.setCreateUserId(TokenData.takeFromRequest().getUserId()); + billRelation.setCreateTime(new Date()); + billRelation.setUpdateUserId(TokenData.takeFromRequest().getUserId()); + billRelation.setUpdateTime(new Date()); + btpTransformResult.getBillRelationList().add(billRelation); + return btpTransformResult; + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException(e.getMessage()); + } + } + + + /** + * 查询单据数据 + * + * @param selectTableMap + * @param id 单据id + * @return + */ + private ObjectValue getBillData(Map selectTableMap, String id) { + + Selector selector = new Selector(); + String vaName = null; + for (MetaTable metaTable : selectTableMap.values()) { + metaTable.getMetaColumnList().add(getPkColumn()); + for (int i = 0; i < metaTable.getMetaColumnList().size(); i++) { + MetaColumn metaColumn = metaTable.getMetaColumnList().get(i); + if (metaTable.isMain()) {//主表数据 + vaName = metaTable.getTableName(); + selector.getList().add(new SelectorItem(metaColumn.getColumnName())); + } else {//分录数据 + selector.getList().add(new SelectorItem(new StringBuilder(metaTable.getTableName()) + .append(".").append(metaColumn.getColumnName()).toString())); + } + } + + } + + return ormGenDataSourceUtil.queryOne(vaName, Long.valueOf(id), selector);//TODO 未处理 + } + + + /** + * 查询单据集合 + * + * @param table 数据库表 + * @param selectFields 查询字段 + * @param id 单据id + * @return + */ + public List> getDataEntryCol(MetaTable table, String selectFields, String id) { + DataFilter dataFilter = new DataFilter(); + DataFilterItem dataFilterItem = new DataFilterItem("parent_id", FieldFilterType.EQUAL_FILTER, id); + dataFilter.getDataFilterItems().add(dataFilterItem); + List> dataList = getList(table, selectFields, dataFilter); + return dataList; + } + + /** + * 查询单挑数据 + * + * @param table 查询元数据库表 + * @param selectFields 查询字段 + * @param id 单据id + * @return 数据集合 + */ + private Map getData(MetaTable table, String selectFields, String id) { + + DataFilter dataFilter = new DataFilter(); + DataFilterItem dataFilterItem = new DataFilterItem("id", FieldFilterType.EQUAL_FILTER, id); + dataFilter.getDataFilterItems().add(dataFilterItem); + List> dataList = getList(table, selectFields, dataFilter); + return dataList.size() == 0 ? null : dataList.get(0); + + } + + /** + * @param table 表元数据 + * @param selectFields 查询字段 + * @param dataFilter 过滤 + * @return + */ + private List> getList(MetaTable table, String selectFields, DataFilter dataFilter) { + StringBuilder sql = new StringBuilder(512); + sql.append(DbUtil.SELECT).append(selectFields).append(DbUtil.FROM).append(table.getTableName()); + List paramList = new ArrayList<>(); + sql.append(dataFilter.getWhereClause(paramList)); + try { + List> dataList = + dbUtil.query(sql.toString(), paramList); + return dataList; + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new RuntimeException(e.getMessage()); + } + + + } + + private MetaColumn getPkColumn() { + + MetaColumn metaColumn = new MetaColumn(); + metaColumn.setColumnName("id"); + metaColumn.setColumnType("bigint"); + + return metaColumn; + } + + + /** + * 封装单据数据库表,字段 + * + * @param tableMap + * @param tableName + * @param columnName + */ + private MetaColumn genMetaTable(Map tableMap, String tableName, String columnName, OnlFormHead formHead) { + if (tableName == null) { + return null; + } + MetaTable metaTable = tableMap.get(tableName); + if (metaTable == null) { + metaTable = new MetaTable(); + // metaTable.setFormHeadId(); + metaTable.setTableName(tableName); + metaTable.setMetaColumnList(new ArrayList<>()); + if (tableName.equals(formHead.getTableName())) { + metaTable.setMain(true); + } else { + metaTable.setMain(false); + } + tableMap.put(tableName, metaTable); + } + + // TODO: 2024/1/24 + // metaColumn.setColumnType(); + MetaColumn metaColumn = new MetaColumn(); + if (tableName.equals(formHead.getTableName())) { + metaColumn.setMain(true); + } else { + metaColumn.setMain(false); + } + metaColumn.setMetaTable(metaTable.getTableName()); + metaColumn.setColumnName(columnName); + metaTable.getMetaColumnList().add(metaColumn); + return metaColumn; + } + + + private String makeSelectFields(MetaTable table) { + + DataSourceProvider provider = dbUtil.getDataSourceProvider(); + ; + StringBuilder selectFieldBuider = new StringBuilder(512); + String intString = "SIGNED"; + if (provider.getDblinkType() == DblinkType.POSTGRESQL) { + intString = "INT8"; + } + // 拼装主表的select fields字段。 + for (MetaColumn column : table.getMetaColumnList()) { + + String columnAliasName = column.getColumnName(); + if (this.castToInteger(column)) { + selectFieldBuider + .append("CAST(") + .append(table.getTableName()) + .append(".") + .append(column.getColumnName()) + .append(" AS ") + .append(intString) + .append(") \"") + .append(columnAliasName) + .append("\","); + } else if ("date".equals(column.getColumnType())) { + selectFieldBuider + .append("CAST(") + .append(table.getTableName()) + .append(".") + .append(column.getColumnName()) + .append(" AS CHAR(10)) \"") + .append(columnAliasName) + .append("\","); + } else { + selectFieldBuider + .append(table.getTableName()) + .append(".") + .append(column.getColumnName()) + .append(" \"") + .append(columnAliasName) + .append("\","); + } + } + return selectFieldBuider.substring(0, selectFieldBuider.length() - 1); + } + + private boolean castToInteger(MetaColumn column) { + return "tinyint(1)".equals(column.getColumnType()); + } + + +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/service/execute/entity/BillData.java b/common/common-botp/src/main/java/apelet/common/botp/service/execute/entity/BillData.java new file mode 100644 index 0000000..da35f6e --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/service/execute/entity/BillData.java @@ -0,0 +1,21 @@ +package apelet.common.botp.service.execute.entity; + +import lombok.Data; + +import java.util.List; +import java.util.Map; + +/** + * @author sunquan + * @version 1.0 + * Create by 2024/1/23 19:20 + */ +@Data +public class BillData { + + private Map headData; + + private Map>> entryData; + + +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/service/execute/entity/BillRelation.java b/common/common-botp/src/main/java/apelet/common/botp/service/execute/entity/BillRelation.java new file mode 100644 index 0000000..4f2cca8 --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/service/execute/entity/BillRelation.java @@ -0,0 +1,54 @@ +package apelet.common.botp.service.execute.entity; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +import java.util.Date; +import java.util.List; + +/** + * @author Soon + * @version 1.0 + * Create by 2024/2/19 10:10 + */ +@Data +public class BillRelation { + + @Schema(description = "主键") + private Long id; + + @Schema(description = "转换规则id") + private String convertRuleId; + + @Schema(description = "源单标识") + private String sourceNumber; + + @Schema(description = "源单id") + private String sourceId; + + @Schema(description = "目标单标识") + private String targetNumber; + + @Schema(description = "目标单id") + private String targetId; + + private Long createUserId; + + /** + * 创建时间。 + */ + private Date createTime; + + /** + * 更新者Id。 + */ + private Long updateUserId; + + /** + * 更新时间。 + */ + private Date updateTime; + + private List billRelationEntryList; + +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/service/execute/entity/BillRelationEntry.java b/common/common-botp/src/main/java/apelet/common/botp/service/execute/entity/BillRelationEntry.java new file mode 100644 index 0000000..0f89351 --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/service/execute/entity/BillRelationEntry.java @@ -0,0 +1,64 @@ +package apelet.common.botp.service.execute.entity; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +import java.util.Date; + +/** + * @author Soon + * @version 1.0 + * Create by 2024/2/19 10:10 + */ +@Data +public class BillRelationEntry { + + @Schema(description = "主键") + private Long id; + + @Schema(description = "转换规则id") + private String convertRuleId; + + @Schema(description = "源单标识") + private String sourceNumber; + + @Schema(description = "源单id") + private String sourceId; + + @Schema(description = "源单分录标识") + private String sourceEntryNumber; + + @Schema(description = "源单分录id") + private String sourceEntryId; + + @Schema(description = "目标单标识") + private String targetNumber; + + @Schema(description = "目标单id") + private String targetId; + + @Schema(description = "目标分录标识") + private String targeEntryNumber; + + @Schema(description = "目标分录id") + private String targeEntryId; + + private Long createUserId; + + /** + * 创建时间。 + */ + private Date createTime; + + /** + * 更新者Id。 + */ + private Long updateUserId; + + /** + * 更新时间。 + */ + private Date updateTime; + + +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/service/execute/entity/BtpTransformResult.java b/common/common-botp/src/main/java/apelet/common/botp/service/execute/entity/BtpTransformResult.java new file mode 100644 index 0000000..9249a34 --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/service/execute/entity/BtpTransformResult.java @@ -0,0 +1,23 @@ +package apelet.common.botp.service.execute.entity; + +import apelet.common.core.object.ObjectCollection; +import lombok.Data; + +import java.util.ArrayList; +import java.util.List; + +/** + * @author Soon + * @version 1.0 + * Create by 2024/2/19 10:15 + * @description 转换结果 + */ +@Data +public class BtpTransformResult { + + private ObjectCollection billDataList = new ObjectCollection(); + + private List billRelationList = new ArrayList<>(); + + +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/service/execute/entity/ConvertColumnConfig.java b/common/common-botp/src/main/java/apelet/common/botp/service/execute/entity/ConvertColumnConfig.java new file mode 100644 index 0000000..2c08b24 --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/service/execute/entity/ConvertColumnConfig.java @@ -0,0 +1,49 @@ +package apelet.common.botp.service.execute.entity; + +import com.alibaba.fastjson.JSONObject; +import lombok.Data; + +/** + * @author Soon + * @version 1.0 + * @description + * Create by 2024/1/23 22:21 + */ +@Data +public class ConvertColumnConfig { + + /** + * 表名 + */ + private String tableName;//表名 源单 + + /** + * 字段名 + */ + private String columnName;//字段名 源单 + + + /** + * 取值方式 + */ + private int valueMethod;//1 源字段 2 目标字段 + + + /** + * 字段值 + */ + private String value; + + /** + * 是否主表 + */ + private boolean isMain; + + /** + * 计算公式 + */ + private JSONObject calculationFormula; + + + +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/service/execute/entity/ConvertConfig.java b/common/common-botp/src/main/java/apelet/common/botp/service/execute/entity/ConvertConfig.java new file mode 100644 index 0000000..d0af81d --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/service/execute/entity/ConvertConfig.java @@ -0,0 +1,31 @@ +package apelet.common.botp.service.execute.entity; + +import lombok.Data; + +import java.util.Map; + +/** + * @author sunquan + * @version 1.0 + * @description 单据转换配置 + * Create by 2024/1/23 22:18 + */ +@Data +public class ConvertConfig { + + /** + * key 目标字段 val 字段转换配置 + */ + private Map columnConfigMap ; + + /** + * 源元数据table + */ + private MetaTable srcMetaTable; + + /** + * 目标元数据table + */ + private MetaTable destMetaTable; + +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/service/execute/entity/MetaColumn.java b/common/common-botp/src/main/java/apelet/common/botp/service/execute/entity/MetaColumn.java new file mode 100644 index 0000000..e0c906a --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/service/execute/entity/MetaColumn.java @@ -0,0 +1,53 @@ +package apelet.common.botp.service.execute.entity; + +import lombok.Data; + +import java.util.Objects; + +/** + * + * @author sunquan + * @version 1.0 + * Create by 2024/1/22 21:04 + */ +@Data +public class MetaColumn { + + /** + * 字段名称 + */ + private String columnName; + + /** + * 字段类型 + */ + private String columnType; + + + /** + * 主表 + */ + private String metaTable; + + public boolean isMain; + + + + + @Override + public int hashCode() { + return Objects.hash(columnName, metaTable); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + MetaColumn user = (MetaColumn) o; + return columnName.equals(user.columnName) && metaTable + .equals(user.getMetaTable()); + } + + + +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/service/execute/entity/MetaTable.java b/common/common-botp/src/main/java/apelet/common/botp/service/execute/entity/MetaTable.java new file mode 100644 index 0000000..3bc9d84 --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/service/execute/entity/MetaTable.java @@ -0,0 +1,39 @@ +package apelet.common.botp.service.execute.entity; + +import lombok.Data; + +import java.util.List; + +/** + * + * @author sunquan + * @version 1.0 + * Create by 2024/1/22 21:01 + */ +@Data +public class MetaTable { + + /** + * 表单元数据id + */ + private String formHeadId; + + /** + * 表单元数据表名 + */ + private String tableName; + + /** + * 字段名 + */ + private List metaColumnList; + + /** + * 是否为主表 + */ + private boolean isMain; + + + + +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/service/execute/mapping/BotpMappingCalculationFormulaMapping.java b/common/common-botp/src/main/java/apelet/common/botp/service/execute/mapping/BotpMappingCalculationFormulaMapping.java new file mode 100644 index 0000000..1f1c057 --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/service/execute/mapping/BotpMappingCalculationFormulaMapping.java @@ -0,0 +1,73 @@ +package apelet.common.botp.service.execute.mapping; + +import apelet.common.botp.service.execute.entity.ConvertColumnConfig; +import apelet.common.botp.service.execute.entity.MetaColumn; +import apelet.common.core.object.ObjectCollection; +import apelet.common.core.object.ObjectValue; +import apelet.common.core.util.ApplicationContextHolder; +import apelet.common.online.service.impl.OnlineFormServiceImpl; +import apelet.common.online.util.Jexl3Util; +import com.alibaba.fastjson.JSONObject; + +import java.util.Arrays; +import java.util.List; + +/** + * @author Soon + * @version 1.0 + * Create by 2024/1/25 10:46 + */ +public class BotpMappingCalculationFormulaMapping extends BotpMappingStrategy { + + private final OnlineFormServiceImpl onlineFormService = + ApplicationContextHolder.getBean(OnlineFormServiceImpl.class); + private final Jexl3Util Jexl3Util = + ApplicationContextHolder.getBean(Jexl3Util.class); + + + + @Override + public void mapping(ObjectValue destBillData, MetaColumn destMetaColumn, ConvertColumnConfig convertColumnConfig, ObjectValue srcBillData) { + ObjectCollection entryDataList = null; + if (!convertColumnConfig.isMain()) {//源表不为主表 + entryDataList = srcBillData.getObjectCollection(convertColumnConfig.getTableName()); + } + if (destMetaColumn.isMain()) {//目标字段为主表 + if (convertColumnConfig.getColumnName() != null) {//源 + if (convertColumnConfig.isMain()) {//源字段为主表 + JSONObject json = convertColumnConfig.getCalculationFormula(); + destBillData.put(destMetaColumn.getColumnName(), srcBillData.get(convertColumnConfig.getColumnName())); + + destBillData.put(destMetaColumn.getColumnName(), getValue(json, srcBillData)); + } else {//源字段为附表,取分录第一行 + if (entryDataList != null && !entryDataList.isEmpty()) { + destBillData.put(destMetaColumn.getColumnName(), entryDataList.getObject(0).get(convertColumnConfig.getColumnName())); + // List> = destBillData.getEntryData().get(destMetaColumn.getMetaTable().getTableName());//获取目标分录 + } + } + } + } else {//目标字段为附表,对应附表分录 + if (convertColumnConfig.getColumnName() != null) {//源 + ObjectCollection listMap = destBillData.getObjectCollection(destMetaColumn.getMetaTable()); + for (int i = 0; i < listMap.size(); i++) { + if (convertColumnConfig.isMain()) {//源字段为主表,每行分录赋值源单表头字段 + listMap.getObject(i).put(destMetaColumn.getColumnName(), + srcBillData.get(convertColumnConfig.getColumnName())); + } else {//源字段为附表,每行分录赋值目标单字段 + listMap.getObject(i).put(destMetaColumn.getColumnName(), + entryDataList.getObject(i).get(convertColumnConfig.getColumnName())); + } + } + } + } + + } + + Object getValue(JSONObject json, ObjectValue objectValue) { + String expression = json.getString("expressionTranslation"); + String fun = Jexl3Util.getMySplit("\\$(.*?)\\$", expression); + List funParam = Arrays.asList(Jexl3Util.getMySplit("\\((.*?)\\)", fun).split(",")); + Object[] objects = Jexl3Util.getFunParam(funParam, objectValue); + return onlineFormService.executeFunction(json, fun, objects); + } +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/service/execute/mapping/BotpMappingContext.java b/common/common-botp/src/main/java/apelet/common/botp/service/execute/mapping/BotpMappingContext.java new file mode 100644 index 0000000..68cb3e9 --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/service/execute/mapping/BotpMappingContext.java @@ -0,0 +1,42 @@ +package apelet.common.botp.service.execute.mapping; + +import apelet.common.botp.service.execute.entity.ConvertColumnConfig; +import apelet.common.botp.service.execute.entity.MetaColumn; +import apelet.common.core.object.ObjectValue; + +/** + * 单据转换映射策略 + * @author Soon + * @version 1.0 + * Create by 2024/1/25 10:37 + */ +public class BotpMappingContext { + + public static final int valueMethod_mapping = 1;//映射 + public static final int valueMethod_constant = 2;//常量 + public static final int valueMethod_expression = 3;//计算公式 + + + + + public BotpMappingStrategy botpMappingStrategy; + + + public BotpMappingContext(int valueMethod){ + + if(valueMethod == BotpMappingContext.valueMethod_mapping){ + botpMappingStrategy = new BotpMappingStrategyMapping(); + }else if(valueMethod == BotpMappingContext.valueMethod_constant){ + botpMappingStrategy = new BotpMappingStrategyConstant(); + }else if(valueMethod == BotpMappingContext.valueMethod_expression){ + botpMappingStrategy = new BotpMappingCalculationFormulaMapping(); + } + + } + + public void mapping(ObjectValue destBillData, MetaColumn destMetaColumn, ConvertColumnConfig convertColumnConfig, ObjectValue srcBillData){ + botpMappingStrategy.mapping(destBillData,destMetaColumn,convertColumnConfig,srcBillData); + + } + +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/service/execute/mapping/BotpMappingStrategy.java b/common/common-botp/src/main/java/apelet/common/botp/service/execute/mapping/BotpMappingStrategy.java new file mode 100644 index 0000000..535f8cf --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/service/execute/mapping/BotpMappingStrategy.java @@ -0,0 +1,19 @@ +package apelet.common.botp.service.execute.mapping; + +import apelet.common.botp.service.execute.entity.ConvertColumnConfig; +import apelet.common.botp.service.execute.entity.MetaColumn; +import apelet.common.core.object.ObjectValue; + +/** + * @author sunquan + * @version 1.0 + * Create by 2024/1/25 10:40 + */ +public abstract class BotpMappingStrategy { + + /** + * 映射转换 + */ + public abstract void mapping(ObjectValue destBillData, MetaColumn destMetaColumn, ConvertColumnConfig convertColumnConfig, ObjectValue srcBillData); + +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/service/execute/mapping/BotpMappingStrategyConstant.java b/common/common-botp/src/main/java/apelet/common/botp/service/execute/mapping/BotpMappingStrategyConstant.java new file mode 100644 index 0000000..25602bb --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/service/execute/mapping/BotpMappingStrategyConstant.java @@ -0,0 +1,28 @@ +package apelet.common.botp.service.execute.mapping; + +import apelet.common.botp.service.execute.entity.ConvertColumnConfig; +import apelet.common.botp.service.execute.entity.MetaColumn; +import apelet.common.core.object.ObjectCollection; +import apelet.common.core.object.ObjectValue; + +/** + * @author Soon + * @version 1.0 + * Create by 2024/1/25 10:47 + */ +public class BotpMappingStrategyConstant extends BotpMappingStrategy{ + + @Override + public void mapping(ObjectValue destBillData, MetaColumn destMetaColumn, ConvertColumnConfig convertColumnConfig, ObjectValue srcBillData) { + if(destMetaColumn.isMain()){//目标字段为主表,直接赋值常量 + destBillData.put( + destMetaColumn.getColumnName(),convertColumnConfig.getValue()); + }else{//目标字段为附表,对应附表分录,赋值常量 + ObjectCollection listMap = destBillData.getObjectCollection(destMetaColumn.getMetaTable()); + for (int i = 0 ; i < listMap.size() ; i++){ + listMap.getObject(i).put(destMetaColumn.getColumnName(),convertColumnConfig.getValue()); + } + } + } + +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/service/execute/mapping/BotpMappingStrategyMapping.java b/common/common-botp/src/main/java/apelet/common/botp/service/execute/mapping/BotpMappingStrategyMapping.java new file mode 100644 index 0000000..451a91f --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/service/execute/mapping/BotpMappingStrategyMapping.java @@ -0,0 +1,51 @@ +package apelet.common.botp.service.execute.mapping; + +import apelet.common.botp.service.execute.entity.ConvertColumnConfig; +import apelet.common.botp.service.execute.entity.MetaColumn; +import apelet.common.core.object.ObjectCollection; +import apelet.common.core.object.ObjectValue; + +/** + * @author Soon + * @version 1.0 + * Create by 2024/1/25 10:46 + */ +public class BotpMappingStrategyMapping extends BotpMappingStrategy{ + + @Override + public void mapping(ObjectValue destBillData, MetaColumn destMetaColumn, ConvertColumnConfig convertColumnConfig, ObjectValue srcBillData) { + ObjectCollection entryDataList = null; + if( !convertColumnConfig.isMain() ){//源表不为主表 + entryDataList = srcBillData.getObjectCollection(convertColumnConfig.getTableName()); + } + if(destMetaColumn.isMain()){//目标字段为主表 + if(convertColumnConfig.getColumnName() != null){//源 + if(convertColumnConfig.isMain()){//源字段为主表 + destBillData.put(destMetaColumn.getColumnName() + ,srcBillData.get(convertColumnConfig.getColumnName())); + }else{//源字段为附表,取分录第一行 + if( entryDataList.size() > 0){ + if(entryDataList != null){ + destBillData.put(destMetaColumn.getColumnName(),entryDataList.getObject(0).get(convertColumnConfig.getColumnName())); + // List> = destBillData.getEntryData().get(destMetaColumn.getMetaTable().getTableName());//获取目标分录 + } + } + + } + } + }else{//目标字段为附表,对应附表分录 + if(convertColumnConfig.getColumnName() != null) {//源 + ObjectCollection listMap = destBillData.getObjectCollection(destMetaColumn.getMetaTable()); + for (int i = 0 ; i < listMap.size() ; i++){ + if (convertColumnConfig.isMain()) {//源字段为主表,每行分录赋值源单表头字段 + listMap.getObject(i).put(destMetaColumn.getColumnName() + ,srcBillData.get(convertColumnConfig.getColumnName())); + }else{//源字段为附表,每行分录赋值目标单字段 + listMap.getObject(i).put(destMetaColumn.getColumnName(),entryDataList.getObject(i).get(convertColumnConfig.getColumnName())); + } + } + } + } + + } +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/service/impl/BillBaseService.java b/common/common-botp/src/main/java/apelet/common/botp/service/impl/BillBaseService.java new file mode 100644 index 0000000..8d924bc --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/service/impl/BillBaseService.java @@ -0,0 +1,344 @@ +package apelet.common.botp.service.impl; + +import apelet.common.botp.model.ConvertRelation; +import apelet.common.botp.model.ConvertRelationEntry; +import apelet.common.botp.service.IBillBaseService; +import apelet.common.botp.service.IConvertRelationEntryService; +import apelet.common.botp.service.IConvertRelationService; +import apelet.common.core.annotation.RelationOneToMany; +import apelet.common.core.base.dao.BaseDaoMapper; +import apelet.common.core.base.service.BaseService; +import apelet.common.core.object.*; +import apelet.common.core.util.ApplicationContextHolder; +import apelet.common.core.util.MyModelUtil; +import cn.hutool.core.util.StrUtil; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.github.pagehelper.Page; +import com.github.pagehelper.page.PageMethod; +import org.apache.commons.lang3.ObjectUtils; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.stereotype.Service; + +import java.io.Serializable; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +/** + * @author Soon + * @version 1.0 + * Create by 2024/2/28 8:35 + */ +@Service +public abstract class BillBaseService + extends BaseService implements IBillBaseService { + + @Autowired + private IConvertRelationService convertRelationService; + @Autowired + private IConvertRelationEntryService convertRelationEntryService; + + @Override + protected BaseDaoMapper mapper() { + return baseMapper; + } + + @Override + public Page listBill(M m, MyOrderParam orderParam, MyPageParam pageParam, TraceParamDto traceParamDto) { + + + String orderBy = MyOrderParam.buildOrderBy(orderParam, m.getClass()); + LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(m); + + if (StrUtil.isNotBlank(orderBy)) { + queryWrapper.last(" ORDER BY " + orderBy); + } + if (pageParam != null) { + PageMethod.startPage(pageParam.getPageNum(), pageParam.getPageSize()); + } + List resultList = baseMapper.selectList(queryWrapper); + int batchSize = resultList instanceof Page ? 0 : 1000; + this.buildRelationForDataList(resultList, MyRelationParam.normal(), batchSize); + return (Page) resultList; + } + + @Override + public void saveBill(M m, List crDtoList) { + + try { + Long id = (Long) getGetMethod(m.getClass(),"id").invoke(m); + if(ObjectUtils.isEmpty(id)){ + getSetMethod(m.getClass().getSuperclass(),"createUserId").invoke(m, TokenData.takeFromRequest().getUserId()); + getSetMethod(m.getClass().getSuperclass(),"createTime").invoke(m, new Date()); + baseMapper.insert(m); + Method getMethod = this.getGetMethod(m.getClass(),"id"); + Long Id = (Long) getMethod.invoke(m); + this.saveEntry(m,Id); + }else { + M isExistObj = baseMapper.selectById(id); + //查询id是否对应数据 有 更新数据 无 插入数据 + if (ObjectUtils.isEmpty(isExistObj)) { + getSetMethod(m.getClass().getSuperclass(),"createUserId").invoke(m, TokenData.takeFromRequest().getUserId()); + getSetMethod(m.getClass().getSuperclass(),"createTime").invoke(m, new Date()); + baseMapper.insert(m); + this.saveEntry(m, id); + } else { + getSetMethod(m.getClass().getSuperclass(),"updateUserId").invoke(m, TokenData.takeFromRequest().getUserId()); + getSetMethod(m.getClass().getSuperclass(),"updateTime").invoke(m, new Date()); + baseMapper.updateById(m); + this.saveEntry(m, id); + } + } + + saveRelation(crDtoList); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + @Override + public void submitBill(String processDefinitionKey, M m, List crDto) { + try { + //提交的 数据保存或更新 + this.saveBill(m, crDto); + //获取对应的id + Long id = (Long) getGetMethod(m.getClass(),"id").invoke(m); + //获取对应service + Object serviceImpl = getServiceImpl(m.getClass()); + Method startWithBusinessKeyMethod = serviceImpl.getClass().getMethod("startWithBusinessKey", String.class, Long.class); + if (StringUtils.isNotEmpty(processDefinitionKey)){ + //开启流程 + startWithBusinessKeyMethod.invoke(serviceImpl,processDefinitionKey,id); + } + } catch (Exception e) { + throw new RuntimeException(e); + } + + } + + @Override + public void submitBillKey(String processDefinitionKey, Long id) { + + try { + Object serviceImpl = getServiceImpl(this.modelClass); + Method startWithBusinessKeyMethod = serviceImpl.getClass().getMethod("startWithBusinessKey", String.class, Long.class); + if (StringUtils.isNotEmpty(processDefinitionKey)){ + //开启流程 + startWithBusinessKeyMethod.invoke(serviceImpl,processDefinitionKey,id); + } + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + @Override + public M detailBill(K id) { + //查询单据 + M m = baseMapper.selectById(id); + if (ObjectUtils.isEmpty(m)){ + return null; + } + try { + Field[] fields = m.getClass().getDeclaredFields(); + for (Field field : fields) { + // 是否引用RelationOneToMany注解 + if (field.isAnnotationPresent(RelationOneToMany.class)) { + //获取分录实体class + Class entryClass = field.getAnnotation(RelationOneToMany.class).slaveModelClass(); + //获取对应service + ServiceImpl serviceImpl = (ServiceImpl) getServiceImpl(entryClass); +// Method getListByFilterMethod = serviceImpl.getClass().getMethod("getListByFilter",entryClass); + //构建对象 + Constructor constructor = entryClass.getConstructor(); + Object o = constructor.newInstance(); + Method setParentIdMethod = getSetMethod(entryClass,"parentId"); + setParentIdMethod.invoke(o, id); + //通过 主表id 获取对应分录数据 + LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(o); + List list = serviceImpl.list(queryWrapper); +// List list = (List) getListByFilterMethod.invoke(serviceImpl, o); + + Method setMethod = getSetMethod(m.getClass(), field.getName()); + setMethod.invoke(m,list); + } + + } + } catch (Exception e) { + throw new RuntimeException(e); + } + return m; + } + + @Override + public Integer removeBillById(String ids) { + String[] idsplit = ids.split(","); + for (String id : idsplit) { + //删除主表数据 + this.removeById(id); + try { + Field[] fields = this.entityClass.getClass().getDeclaredFields(); + for (Field field : fields) { + // 是否引用RelationOneToMany注解 + if (field.isAnnotationPresent(RelationOneToMany.class)) { + //获取分录实体class + Class entryClass = field.getAnnotation(RelationOneToMany.class).slaveModelClass(); + //获取对应service + ServiceImpl serviceImpl = (ServiceImpl) getServiceImpl(entryClass); + Method removeByMethod = serviceImpl.getClass().getSuperclass().getMethod("removeBy", Serializable.class); + //构建对象 + Constructor constructor = entryClass.getConstructor(); + Object o = constructor.newInstance(); + Method setParentIdMethod = getSetMethod(entryClass,"parentId"); + setParentIdMethod.invoke(o, ids); + //通过 主表id 删除对应分录数据 + removeByMethod.invoke(serviceImpl, o); + } + + } + } catch (Exception e) { + throw new RuntimeException(e); + } + } + return null; + } + + /** + * 保存分录 + * + * @param m + * @param parenId + * @throws Exception + */ + public void saveEntry(M m, Long parenId) throws Exception { + Field[] fields = m.getClass().getDeclaredFields(); + for (Field field : fields) { + // 是否引用RelationOneToMany注解 + if (field.isAnnotationPresent(RelationOneToMany.class)) { + String fieldName = field.getName(); + //获取分录实体class + Class aClass = field.getAnnotation(RelationOneToMany.class).slaveModelClass(); + Method getMethod = this.getGetMethod(m.getClass(), fieldName); + Object object = getMethod.invoke(m); + if (object instanceof List) { + for (Object o : (List) object) { + Long Id = (Long) getGetMethod(aClass,"id").invoke(o); + if (ObjectUtils.isEmpty(Id)){ + getSetMethod(aClass.getSuperclass(),"createUserId").invoke(o, TokenData.takeFromRequest().getUserId()); + getSetMethod(aClass.getSuperclass(),"createTime").invoke(o, new Date()); + getSetMethod(aClass,"parentId").invoke(o, parenId); + ServiceImpl serviceImpl = (ServiceImpl) getServiceImpl(aClass); + serviceImpl.save(o); + }else { + //查询id是否对应数据 有 更新数据 无 插入数据 + ServiceImpl serviceImpl = (ServiceImpl) getServiceImpl(aClass); + Object isHaveObj = serviceImpl.getById(Id); + getSetMethod(aClass.getSuperclass(),"createUserId").invoke(o, TokenData.takeFromRequest().getUserId()); + getSetMethod(aClass.getSuperclass(),"createTime").invoke(o, new Date()); + getSetMethod(aClass,"parentId").invoke(o, parenId); + if (ObjectUtils.isNotEmpty(isHaveObj)) { + serviceImpl.updateById(o); + } else { + serviceImpl.save(o); + } + } + } + } + } + } + } + /** + * 获取get方法 + * + * @param clazz + * @param fieldName + * @return + */ + private Method getGetMethod(Class clazz, String fieldName) { + Method method=null; + StringBuffer sb = new StringBuffer(); + sb.append("get"); + sb.append(fieldName.substring(0, 1).toUpperCase()); + sb.append(fieldName.substring(1)); + try { + method= clazz.getMethod(sb.toString()); + } catch (Exception e) { + throw new RuntimeException(e); + } + return method; + } + + /** + * 获取set方法 + * + * @param clazz + * @param fieldName + * @return + */ + private Method getSetMethod(Class clazz, String fieldName) { + Method method=null; + try { + Class[] parameterTypes = new Class[1]; + Field field = clazz.getDeclaredField(fieldName); + parameterTypes[0] = field.getType(); + StringBuffer sb = new StringBuffer(); + sb.append("set"); + sb.append(fieldName.substring(0, 1).toUpperCase()); + sb.append(fieldName.substring(1)); + method = clazz.getMethod(sb.toString(), parameterTypes); + return method; + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + /** + * 返回对应serviceImpl + * @param clazz + * @return + */ + private static Object getServiceImpl(Class clazz) { + ApplicationContext applicationContext = ApplicationContextHolder.getApplicationContext(); + String entityName = clazz.getSimpleName(); + String serviceName = entityName.substring(0, 1).toLowerCase() + entityName.substring(1)+"Service"; + return applicationContext.getBean(serviceName); + } + + private void saveRelation(List crDto) { + if (crDto != null) { + List convertRelationList = MyModelUtil.copyCollectionTo(crDto, ConvertRelation.class); + if (convertRelationList != null && convertRelationList.size() > 0) { + List insertRelation = new ArrayList<>(); + for (ConvertRelation convertRelation : convertRelationList) { + if (!convertRelationService.existId(convertRelation.getId())) { + insertRelation.add(convertRelation); + } + } + if (insertRelation.size() > 0) { + convertRelationService.saveBatch(insertRelation); + } + + } + List convertRelationEntryDtoList = new ArrayList<>(); + for (ConvertRelationDto convertRelationDto : + crDto) { + for (ConvertRelationEntryDto convertRelationEntry + : convertRelationDto.getConvertRelationEntryDtoList()) { + if (!convertRelationEntryService.existId(convertRelationEntry.getId())) { + convertRelationEntryDtoList.add(convertRelationEntry); + } + } + } + List convertRelationEntries = MyModelUtil.copyCollectionTo(convertRelationEntryDtoList, ConvertRelationEntry.class); + if (convertRelationEntries.size() > 0) { + convertRelationEntryService.saveBatch(convertRelationEntries); + } + } + } + +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/service/impl/ConvertFieldmappingEntryServiceImpl.java b/common/common-botp/src/main/java/apelet/common/botp/service/impl/ConvertFieldmappingEntryServiceImpl.java new file mode 100644 index 0000000..42795ce --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/service/impl/ConvertFieldmappingEntryServiceImpl.java @@ -0,0 +1,75 @@ +package apelet.common.botp.service.impl; + + +import apelet.common.botp.dao.ConvertFieldmappingEntryMapper; +import apelet.common.botp.model.ConvertFieldmappingEntry; +import apelet.common.botp.service.IConvertFieldmappingEntryService; +import apelet.common.core.base.dao.BaseDaoMapper; +import apelet.common.core.base.service.BaseService; +import apelet.common.core.object.MyRelationParam; +import apelet.common.generator.dao.OnlFormHeadMapper; +import apelet.common.generator.model.OnlFormHead; +import cn.hutool.core.util.StrUtil; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.github.pagehelper.Page; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * @author admin + * @since 2024-01-18 10:31:58 + */ +@Service +public class ConvertFieldmappingEntryServiceImpl extends BaseService implements IConvertFieldmappingEntryService { + @Autowired + private ConvertFieldmappingEntryMapper ConvertFieldmappingEntryMapper; + + @Autowired + private OnlFormHeadMapper onlFormHeadMapper; + + + @Override + protected BaseDaoMapper mapper() { + return baseMapper; + } + + @Override + public List getConvertFieldmappingEntryRelation(Long id) { + List resultList = this.list(new LambdaQueryWrapper().eq(ConvertFieldmappingEntry::getParentId, id)); + + int batchSize = resultList instanceof Page ? 0 : 1000; + this.buildRelationForDataList(resultList, MyRelationParam.normal(), batchSize); + return resultList; + } + + @Override + public List getConvertFieldmappingEntryListWithRelation(ConvertFieldmappingEntry convertFieldmappingEntry, String buildOrderBy) { + LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(convertFieldmappingEntry); + if (StrUtil.isNotBlank(buildOrderBy)) { + queryWrapper.last(" ORDER BY " + buildOrderBy); + } + List resultList = baseMapper.selectList(queryWrapper); + //处理返回数据 + for (int i = 0; i < resultList.size(); i++) { + ConvertFieldmappingEntry convertFieldmappingEntry1 = resultList.get(i); + //源单 + String parentId = convertFieldmappingEntry1.getParentId(); + OnlFormHead onlFormHeadBys = onlFormHeadMapper.selectById(parentId); + if (onlFormHeadBys!=null) { + String tableTxt = onlFormHeadBys.getTableTxt(); + Map sourceEntityIdMap = new HashMap<>(); + sourceEntityIdMap.put("parentId", parentId); + sourceEntityIdMap.put("parentName", tableTxt); + convertFieldmappingEntry1.setParentIdList(sourceEntityIdMap); + } + } + + int batchSize = resultList instanceof Page ? 0 : 1000; + this.buildRelationForDataList(resultList, MyRelationParam.normal(), batchSize); + return resultList; + } +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/service/impl/ConvertPluginEntryServiceImpl.java b/common/common-botp/src/main/java/apelet/common/botp/service/impl/ConvertPluginEntryServiceImpl.java new file mode 100644 index 0000000..c3cfc1f --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/service/impl/ConvertPluginEntryServiceImpl.java @@ -0,0 +1,75 @@ +package apelet.common.botp.service.impl; + +import apelet.common.botp.dao.ConvertPluginEntryMapper; +import apelet.common.botp.model.ConvertPluginEntry; +import apelet.common.botp.service.IConvertPluginEntryService; +import apelet.common.core.base.dao.BaseDaoMapper; +import apelet.common.core.base.service.BaseService; +import apelet.common.core.object.MyRelationParam; +import apelet.common.generator.dao.OnlFormHeadMapper; +import apelet.common.generator.model.OnlFormHead; +import cn.hutool.core.util.StrUtil; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.github.pagehelper.Page; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * @author admin + * @since 2024-01-18 10:31:58 + */ +@Service +public class ConvertPluginEntryServiceImpl extends BaseService implements IConvertPluginEntryService { + @Autowired + private ConvertPluginEntryMapper ConvertPluginEntryMapper; + + @Autowired + private OnlFormHeadMapper onlFormHeadMapper; + + + @Override + protected BaseDaoMapper mapper() { + return baseMapper; + } + + @Override + public List getConvertPluginEntryRelation(Long id) { + List resultList = this.list(new LambdaQueryWrapper().eq(ConvertPluginEntry::getParentId, id)); + int batchSize = resultList instanceof Page ? 0 : 1000; + this.buildRelationForDataList(resultList, MyRelationParam.normal(), batchSize); + return resultList; + } + + + @Override + public List getConvertPluginEntryListWithRelation(ConvertPluginEntry convertPluginEntryFilter, String buildOrderBy) { + LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(convertPluginEntryFilter); + if (StrUtil.isNotBlank(buildOrderBy)) { + queryWrapper.last(" ORDER BY " + buildOrderBy); + } + List resultList = baseMapper.selectList(queryWrapper); + //处理返回数据 + for (int i = 0; i < resultList.size(); i++) { + ConvertPluginEntry convertPluginEntry = resultList.get(i); + //源单 + String parentId = convertPluginEntry.getParentId(); + OnlFormHead onlFormHeadBys = onlFormHeadMapper.selectById(parentId); + if (onlFormHeadBys!=null) { + String tableTxt = onlFormHeadBys.getTableTxt(); + Map sourceEntityIdMap = new HashMap<>(); + sourceEntityIdMap.put("parentId", parentId); + sourceEntityIdMap.put("parentName", tableTxt); + convertPluginEntry.setParentIdList(sourceEntityIdMap); + } + } + + + int batchSize = resultList instanceof Page ? 0 : 1000; + this.buildRelationForDataList(resultList, MyRelationParam.normal(), batchSize); + return resultList; + } +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/service/impl/ConvertRelationEntryServiceImpl.java b/common/common-botp/src/main/java/apelet/common/botp/service/impl/ConvertRelationEntryServiceImpl.java new file mode 100644 index 0000000..38011a3 --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/service/impl/ConvertRelationEntryServiceImpl.java @@ -0,0 +1,70 @@ +package apelet.common.botp.service.impl; + +import apelet.common.botp.dao.ConvertRelationEntryMapper; +import apelet.common.botp.model.ConvertRelationEntry; +import apelet.common.botp.service.IConvertRelationEntryService; +import apelet.common.core.base.dao.BaseDaoMapper; +import apelet.common.core.base.service.BaseService; +import apelet.common.core.object.MyRelationParam; +import cn.hutool.core.util.StrUtil; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.github.pagehelper.Page; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; + +/** + * @author admin + * @since 2024-01-18 10:31:58 + */ +@Service +public class ConvertRelationEntryServiceImpl extends BaseService implements IConvertRelationEntryService { + @Autowired + private ConvertRelationEntryMapper ConvertRelationEntryMapper; + + @Override + public Boolean removeAllById(Long id) { + boolean remove = this.removeById(id); + return remove; + } + + @Override + public Boolean editAll(ConvertRelationEntry convertRelationEntry) { + Long id = convertRelationEntry.getId(); + if (null==id)return false; + //设置主数据基本信息 + boolean update = this.updateById(convertRelationEntry); + //设置分录数据基本信息,重新添加 + return update; + } + + @Override + public Boolean addAll(ConvertRelationEntry convertRelationEntry) { + //设置主数据基本信息 + boolean save = this.save(convertRelationEntry); + Long id = convertRelationEntry.getId(); + if (null==id){ + return false; + } + //设置分录数据基本信息,添加 + return save; + } + + @Override + public List getConvertRuleListWithRelation(ConvertRelationEntry convertRelationEntryFilter, String buildOrderBy) { + LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(convertRelationEntryFilter); + if (StrUtil.isNotBlank(buildOrderBy)) { + queryWrapper.last(" ORDER BY " + buildOrderBy); + } + List resultList = baseMapper.selectList(queryWrapper); + int batchSize = resultList instanceof Page ? 0 : 1000; + this.buildRelationForDataList(resultList, MyRelationParam.normal(), batchSize); + return resultList; + } + + @Override + protected BaseDaoMapper mapper() { + return baseMapper; + } +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/service/impl/ConvertRelationServiceImpl.java b/common/common-botp/src/main/java/apelet/common/botp/service/impl/ConvertRelationServiceImpl.java new file mode 100644 index 0000000..2573a27 --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/service/impl/ConvertRelationServiceImpl.java @@ -0,0 +1,184 @@ +package apelet.common.botp.service.impl; + +import apelet.common.botp.dao.ConvertRelationMapper; +import apelet.common.botp.model.ConvertRelation; +import apelet.common.botp.model.GetSearchList; +import apelet.common.botp.model.SysMenuqq; +import apelet.common.botp.service.IConvertRelationService; +import apelet.common.botp.service.ISysMenuqqService; +import apelet.common.core.base.dao.BaseDaoMapper; +import apelet.common.core.base.service.BaseService; +import apelet.common.core.object.MyRelationParam; +import apelet.common.online.dao.OnlineFormMapper; +import apelet.common.online.model.OnlineForm; +import cn.hutool.core.util.StrUtil; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.github.pagehelper.Page; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.*; + +/** + * @author admin + * @since 2024-01-18 10:31:58 + */ +@Service +public class ConvertRelationServiceImpl extends BaseService implements IConvertRelationService { + @Autowired + private ConvertRelationMapper convertRelationMapper; + @Autowired + private OnlineFormMapper onlineFormMapper; + + @Override + public Boolean removeAllById(Long id) { + boolean remove = this.removeById(id); + return remove; + } + + @Override + public Boolean editAll(ConvertRelation convertRelation) { + Long id = convertRelation.getId(); + if (null == id) return false; + //设置主数据基本信息 + boolean update = this.updateById(convertRelation); + //设置分录数据基本信息,重新添加 + return update; + } + + @Override + public Boolean addAll(ConvertRelation convertRelation) { + //设置主数据基本信息 + boolean save = this.save(convertRelation); + Long id = convertRelation.getId(); + if (null == id) { + return false; + } + //设置分录数据基本信息,添加 + return save; + } + + @Override + public List getConvertRuleListWithRelation(ConvertRelation convertRelationFilter, String buildOrderBy) { + LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(convertRelationFilter); + if (StrUtil.isNotBlank(buildOrderBy)) { + queryWrapper.last(" ORDER BY " + buildOrderBy); + } + List resultList = baseMapper.selectList(queryWrapper); + int batchSize = resultList instanceof Page ? 0 : 1000; + this.buildRelationForDataList(resultList, MyRelationParam.normal(), batchSize); + return resultList; + } + + @Override + public List transform(String botpId, String srcBill, String destBill, String srcBillId) { + List transformList = convertRelationMapper.transform(botpId, srcBill, destBill, srcBillId); + return transformList; + } + + @Override + public List transformT(String botpId, String srcBill, String destBill, List srcBillList) { + List convertRelations = convertRelationMapper.transformT(botpId, srcBill, destBill, srcBillList); + return convertRelations; + } + + @Autowired + private ISysMenuqqService sysMenuqqService; + @Override + public List> getConvertRelation(String billId, String billType, String searchType) { + List GetSearchList = new ArrayList<>(); + List> GetSearchListNew = new ArrayList<>(); + + if ("1".equals(searchType)) { + GetSearchList = convertRelationMapper.getConvertRelationOn(billId, billType); + for (GetSearchList getSearchList : GetSearchList) { + //通过id查询zz_online_form表数据 + Long upListInterface = getSearchList.getUpListInterface(); + + Map upListInterfaceMap = new HashMap<>(); + + String upInterfaceType = getSearchList.getUpInterfaceType(); + + upListInterfaceMap.put("billTypeName",null); + upListInterfaceMap.put("billListUI",null); + if ("1".equals(upInterfaceType)) { + SysMenuqq sysMenu = sysMenuqqService.getOne(new LambdaQueryWrapper().eq(SysMenuqq::getMenuId, getSearchList.getUpRouteInterface())); + if (sysMenu != null){ + //单据名称-- + upListInterfaceMap.put("billTypeName", sysMenu.getMenuName()); + //菜单管理路劲 + upListInterfaceMap.put("billListUI", sysMenu.getFormRouterName()); + } + //单据标识--类型1:路由,2:在线表单 + upListInterfaceMap.put("billType", "1"); + + //界面类型 + upListInterfaceMap.put("upInterfaceType", "路由表单"); + GetSearchListNew.add(upListInterfaceMap); + } else if ("2".equals(upInterfaceType)) { + OnlineForm onlineForm = onlineFormMapper.selectById(upListInterface); + //单据标识--类型1:路由,2:在线表单 + upListInterfaceMap.put("billType", "2"); + if (onlineForm != null){ + upListInterfaceMap.put("billTypeName", onlineForm.getFormName()); + } + Long formId = onlineForm.getFormId(); + //界面类型 + upListInterfaceMap.put("upInterfaceType", "在线表单"); + //菜单管理路劲 + upListInterfaceMap.put("billListUI", formId); + GetSearchListNew.add(upListInterfaceMap); + } + } + } else if ("2".equals(searchType)) { + GetSearchList = convertRelationMapper.getConvertRelationDown(billId, billType); + for (GetSearchList getSearchList : GetSearchList) { + //通过id查询zz_online_form表数据 + Long downListInterface = getSearchList.getDownListInterface(); + + Map downListInterfaceMap = new HashMap<>(); + + //单据名称 + downListInterfaceMap.put("billTypeName", null); + //菜单管理路劲 + downListInterfaceMap.put("billListUI", null); + String downInterfaceType = getSearchList.getDownInterfaceType(); + if ("1".equals(downInterfaceType)) { + //单据类型 + downListInterfaceMap.put("billType", "1"); + SysMenuqq sysMenu = sysMenuqqService.getOne(new LambdaQueryWrapper().eq(SysMenuqq::getMenuId, getSearchList.getDownRouteInterface())); + if (sysMenu != null){ + //路由 + downListInterfaceMap.put("billListUI", sysMenu.getFormRouterName()); + //单据名称 + downListInterfaceMap.put("billTypeName", sysMenu.getMenuName()); + } + + //界面类型 + downListInterfaceMap.put("upInterfaceType", "路由表单"); + GetSearchListNew.add(downListInterfaceMap); + } else if ("2".equals(downInterfaceType)) { + //单据类型 + downListInterfaceMap.put("billType", "2"); + OnlineForm onlineForm = onlineFormMapper.selectById(downListInterface); + Long formId = onlineForm.getFormId(); + //界面类型 + downListInterfaceMap.put("upInterfaceType", "在线表单"); + if (onlineForm != null){ + //菜单管理路劲 + downListInterfaceMap.put("billListUI", formId); + //单据名称 + downListInterfaceMap.put("billTypeName", onlineForm.getFormName()); + } + GetSearchListNew.add(downListInterfaceMap); + } + } + } + return GetSearchListNew; + } + + @Override + protected BaseDaoMapper mapper() { + return baseMapper; + } +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/service/impl/ConvertRuleServiceImpl.java b/common/common-botp/src/main/java/apelet/common/botp/service/impl/ConvertRuleServiceImpl.java new file mode 100644 index 0000000..9deb952 --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/service/impl/ConvertRuleServiceImpl.java @@ -0,0 +1,529 @@ +package apelet.common.botp.service.impl; + +import apelet.common.botp.dao.ConvertFieldmappingEntryMapper; +import apelet.common.botp.dao.ConvertPluginEntryMapper; +import apelet.common.botp.dao.ConvertRuleMapper; +import apelet.common.botp.dto.*; +import apelet.common.botp.model.*; +import apelet.common.botp.service.*; +import apelet.common.botp.service.execute.BotpService; +import apelet.common.botp.service.execute.entity.BillData; +import apelet.common.botp.service.execute.entity.BtpTransformResult; +import apelet.common.botp.util.Constant; +import apelet.common.core.base.dao.BaseDaoMapper; +import apelet.common.core.base.service.BaseService; +import apelet.common.core.constant.GlobalDeletedFlag; +import apelet.common.core.object.*; +import apelet.common.generator.dao.OnlFormHeadMapper; +import apelet.common.generator.model.OnlFormField; +import apelet.common.generator.model.OnlFormHead; +import apelet.common.generator.service.IOnlFormHeadService; +import apelet.common.generator.utils.OrmGenDataSourceUtil; +import apelet.common.online.dao.OnlineFormMapper; +import cn.hutool.core.util.ObjectUtil; +import cn.hutool.core.util.StrUtil; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.github.pagehelper.Page; +import jodd.util.StringUtil; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.jetbrains.annotations.NotNull; +import org.springframework.beans.BeanUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.*; +import java.util.stream.Collectors; + +/** + * @author admin + * @since 2024-01-18 10:31:58 + */ +@Service +@Slf4j +public class ConvertRuleServiceImpl extends BaseService implements IConvertRuleService { + + @Autowired + private ConvertRuleMapper convertRuleMapper; + @Autowired + private IConvertRelationService convertRelationService; + @Autowired + private IConvertRelationEntryService convertRelationEntryService; + @Autowired + private IConvertFieldmappingEntryService convertFieldmappingEntryService; + @Autowired + private IConvertPluginEntryService convertPluginEntryService; + + @Autowired + private ConvertFieldmappingEntryMapper convertFieldmappingEntryMapper; + + @Autowired + private ConvertPluginEntryMapper convertPluginEntryMapper; + + @Autowired + private OnlFormHeadMapper onlFormHeadMapper; + + @Autowired + private OnlineFormMapper onlineFormMapper; + + @Autowired + private OrmGenDataSourceUtil ormGenDataSourceUtil; + @Autowired + private BotpService botpService; + + @Override + public List selectAll(String id) { + return null; + } + @Override + protected BaseDaoMapper mapper() { + return baseMapper; + } + + @Override + public List allField(String tableName) { + List allFieldList = convertRuleMapper.allField(tableName); + return allFieldList; + } + + + + @Override + public Boolean removeAllById(Long id) { + boolean remove = this.removeById(id); + //有分录情况删除 + if (remove){ + removeChild(id); + } + return remove; + } + + @Override + public Boolean editAll(ConvertRule convertRule) { + Long id = convertRule.getId(); + if (null==id){ + return false; + } + //设置主数据基本信息 + addOrUpdateBaseData(convertRule,null); + boolean update = this.updateById(convertRule); + //删除分录数据 + removeChild(id); + //设置分录数据基本信息,重新添加 + return addChild(convertRule,id); + } + + @Override + public Boolean addAll(ConvertRule convertRule) { + //设置主数据基本信息 + addOrUpdateBaseData(convertRule,null); + boolean save = this.save(convertRule); + Long id = convertRule.getId(); + if (null==id){ + return false; + } + //设置分录数据基本信息,添加 + return addChild(convertRule,id); + } + + @Override + public List getConvertRuleListWithRelation(ConvertRule convertRuleFilter, String buildOrderBy) { + LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(convertRuleFilter); + if (StrUtil.isNotBlank(buildOrderBy)) { + queryWrapper.last(" ORDER BY " + buildOrderBy); + } + List resultList = baseMapper.selectList(queryWrapper); + //处理返回数据 + for (int i = 0; i < resultList.size(); i++) { + ConvertRule convertRule = resultList.get(i); + //源单 + String sourceEntityId = convertRule.getSourceEntityId(); + OnlFormHead onlFormHeadBys = onlFormHeadMapper.selectById(sourceEntityId); + if (onlFormHeadBys!=null) { + String tableTxt = onlFormHeadBys.getTableTxt(); + Map sourceEntityIdMap = new HashMap<>(); + sourceEntityIdMap.put("sourceEntityId", sourceEntityId); + sourceEntityIdMap.put("sourceEntityName", tableTxt); + convertRule.setSourceEntityIdList(sourceEntityIdMap); + } + + //目标单 + String targetEntityId = convertRule.getTargetEntityId(); + OnlFormHead onlFormHeadByt = onlFormHeadMapper.selectById(targetEntityId); + if (onlFormHeadByt!=null) { + String tableTxt2 = onlFormHeadByt.getTableTxt(); + Map targetEntityIdMap = new HashMap<>(); + targetEntityIdMap.put("targetEntityId", targetEntityId); + targetEntityIdMap.put("targetEntityName", tableTxt2); + convertRule.setTargetEntityIdList(targetEntityIdMap); + } + + } + int batchSize = resultList instanceof Page ? 0 : 1000; + this.buildRelationForDataList(resultList, MyRelationParam.normal(), batchSize); + return resultList; + } + + @Override + public List getConvertPluginEntry(Long id) { + return convertPluginEntryService.getConvertPluginEntryRelation(id); + } + + @Override + public List getConvertFieldmappingEntry(Long id) { + return convertFieldmappingEntryService.getConvertFieldmappingEntryRelation(id); + } + + + /** + * 添加子数据方法 + */ + private Boolean addChild(ConvertRule convertRule,Long id){ + List child1 = convertRule.getConvertPluginEntryList(); + if (ObjectUtil.isNotEmpty(child1)){ + for (ConvertPluginEntry one : child1) { + addOrUpdateBaseData(one,id); + convertPluginEntryMapper.insert(one); + } + } + List child2 = convertRule.getConvertFieldmappingEntry(); + if (ObjectUtil.isNotEmpty(child2)){ + for (ConvertFieldmappingEntry one : child2) { + addOrUpdateBaseData(one,id); + convertFieldmappingEntryMapper.insert(one); + + } + } + return true; + } + + + private void removeChild(Long id){ + convertPluginEntryService.remove(new LambdaQueryWrapper().eq(ConvertPluginEntry::getParentId,id)); + convertFieldmappingEntryService.remove(new LambdaQueryWrapper().eq(ConvertFieldmappingEntry::getParentId,id)); + } + + + + + + + + + @Override + public TransformResultDto transform(String botpId, String srcBill, String destBill, String srcBillId) { + + Set srcBillList = new HashSet<>(); + srcBillList.add(srcBillId); + + return transform(botpId,srcBill,destBill,srcBillList); + } + + @Override + public TransformResultDto transform(String botpId, String srcBill, String destBill, Set srcBillList) { + ConvertRule convertRule = convertRuleMapper.selectById(botpId);//查询转换规则 + //查询转换规则字段映射 + List convertFieldmappingEntryList = convertFieldmappingEntryMapper.selectList( + new LambdaQueryWrapper() + .eq(ConvertFieldmappingEntry::getParentId, convertRule.getId())); + List convertPluginEntryList = convertPluginEntryMapper.selectList( + new LambdaQueryWrapper() + .eq(ConvertPluginEntry::getEnable, "true") + .eq(ConvertPluginEntry::getParentId, convertRule.getId())); + OnlFormHead srcFormHead = onlFormHeadMapper.selectById(convertRule.getSourceEntityId());//源单元数据 + OnlFormHead destFormHead = onlFormHeadMapper.selectById(convertRule.getTargetEntityId());//目标单元数据 + BtpTransformResult btpTransformResult = botpService.transform( + convertRule, convertFieldmappingEntryList, convertPluginEntryList, srcFormHead, destFormHead, srcBillList); + TransformResultDto transformResultDto = new TransformResultDto(); + ObjectValue objectValue = btpTransformResult.getBillDataList().getObject(0); + transformResultDto.setBillData(convertOvToBillData(objectValue)); + if (convertRule.getAutoSave().equals("1")) {//自动保存 + transformResultDto.setFormStatus(Constant.FormStatus_AddNew); + } else { + transformResultDto.setFormStatus(Constant.FormStatus_Save); + } + transformResultDto.setFormType(convertRule.getDownInterfaceType()); + if (transformResultDto.getFormType().equals(Constant.InterfaceType_ROUTE)) { + toCamelCase(transformResultDto.getBillData()); + } + return transformResultDto; + } + + private BillData convertOvToBillData(ObjectValue objectValue){ + + BillData billData = new BillData(); + Map headData = new HashMap<>(); + Map>> entryDataCol = new HashMap<>(); + if(objectValue.size() > 0){ + Iterator it = objectValue.getValues().keySet().iterator(); + while (it.hasNext()){ + String fieldKey = (String)it.next(); + if(objectValue.get(fieldKey) == null){ + continue; + } + if(objectValue.get(fieldKey) instanceof ObjectCollection){ + ObjectCollection objectCollection = objectValue.getObjectCollection(fieldKey); + List> entryList = new ArrayList<>(); + Map entryMap = new HashMap<>(); + for(int i = 0; i < objectCollection.size() ; i++){ + ObjectValue entryValue = objectCollection.getObject(i); + Iterator entryIt = entryValue.getValues().keySet().iterator(); + while(entryIt.hasNext()){ + String entryFiledKey = (String)entryIt.next(); + if(entryValue.get(entryFiledKey) instanceof ObjectValue ){ + ObjectValue entityValue = (ObjectValue)entryValue.get(entryFiledKey); + Long pk = entityValue.getPkValue(); + if(pk == null || pk == 0L){ + continue; + } + entityValue = ormGenDataSourceUtil.queryOne(entityValue.getTableName(),pk); + if(entityValue == null){ + continue; + } + entryMap.put(entryFiledKey,entityValue.get("id")); + entryMap.put(entryFiledKey+"_",entityValue.getValues()); + }else{ + entryMap.put(entryFiledKey,entryValue.get(entryFiledKey)); + } + } + entryList.add(entryMap); + } + entryDataCol.put(fieldKey,entryList); + }else if(objectValue.get(fieldKey) instanceof ObjectValue){ + ObjectValue entityValue = (ObjectValue)objectValue.get(fieldKey); + Long pk = entityValue.getPkValue(); + if(pk == null || pk == 0L){ + continue; + } + entityValue = ormGenDataSourceUtil.queryOne(entityValue.getTableName(),pk); + if(entityValue == null){ + continue; + } + headData.put(fieldKey,entityValue.get("id")); + headData.put(fieldKey+"_",entityValue.getValues()); + }else{ + headData.put(fieldKey,objectValue.get(fieldKey)); + } + } + } + billData.setHeadData(headData); + billData.setEntryData(entryDataCol); + + return billData; + } + + /** + * 数据集合的键值,转换成驼峰形式 + * @param billData 数据集 + */ + private void toCamelCase(BillData billData){ + + billData.setHeadData(toCamelCase(billData.getHeadData())); + Map>> entryData = billData.getEntryData(); + for (String key:entryData.keySet()){ + List> dataList = new ArrayList<>(); + for(Map datamap:entryData.get(key)){ + dataList.add(toCamelCase(datamap)); + } + entryData.put(key,dataList); + } + billData.setEntryData(toCamelCase(entryData)); + + + } + + private Map toCamelCase(Map dataMap){ + + Map aftTransformData = new HashMap<>(); + Iterator iterator = dataMap.keySet().iterator(); + while (iterator.hasNext()){ + String key = iterator.next(); + aftTransformData.put(StrUtil.toCamelCase(key),dataMap.get(key)); + } + return aftTransformData; + } + + + @Override + public boolean removeAllRelation(ConvertRelationDelDto dto) { + //删除单据关联关系-主表-> 转换规则id等于billId And (源单标识等于billtype或者目标单标识等于billtype) + boolean removeMain = convertRelationService.remove(new LambdaQueryWrapper() + .eq(ConvertRelation::getConvertRuleId, dto.getBillId()) + .nested(r -> r.eq(ConvertRelation::getSourceNumber, dto.getBillType()) + .or().eq(ConvertRelation::getTargetNumber, dto.getBillType()))); + if (!removeMain) { + return false; + } + //删除分录表 + boolean removeEntry = convertRelationEntryService.remove(new LambdaQueryWrapper() + .eq(ConvertRelationEntry::getConvertRuleId, dto.getBillId()) + .nested(r -> r.eq(ConvertRelationEntry::getSourceNumber, dto.getBillType()) + .or().eq(ConvertRelationEntry::getTargetNumber, dto.getBillType()) + ) + ); + if (!removeEntry) { + return false; + } + //删除字段映射表 + boolean removeEntryField = convertFieldmappingEntryService.remove(new LambdaQueryWrapper() + .eq(ConvertFieldmappingEntry::getParentId, dto.getBillId())); + return removeEntryField; + } + + @Override + public List selectAllRelationByTarget(ConvertRelationListDto dto) { + return convertRelationService.list(new LambdaQueryWrapper() + .eq(ConvertRelation::getTargetId, dto.getDestBillId()) + .eq(ConvertRelation::getTargetNumber, dto.getDestBillType()) + ); + } + @Override + public List selectAllRelationBySource(ConvertRelationListDto dto) { + return convertRelationService.list(new LambdaQueryWrapper() + .eq(ConvertRelation::getSourceId, dto.getSrcBillId()) + .eq(ConvertRelation::getSourceNumber, dto.getSrcBillType()) + ); + } + + + + /** + * 设置基本参数方法 + */ + private void addOrUpdateBaseData(T t,Long id){ + if (t instanceof ConvertRule){ + ConvertRule data = (ConvertRule) t; + data.setDeletedFlag(GlobalDeletedFlag.NORMAL); + data.setUpdateUserId(TokenData.takeFromRequest().getUserId()); + data.setUpdateTime(new Date()); + if (ObjectUtil.isEmpty(data.getCreateTime())){ + data.setCreateUserId(TokenData.takeFromRequest().getUserId()); + data.setCreateTime(new Date()); + } + } + else if (t instanceof ConvertPluginEntry){ + ConvertPluginEntry data = (ConvertPluginEntry) t; + data.setParentId(String.valueOf(id)); + if (ObjectUtil.isEmpty(data.getCreateTime())){ + data.setCreateUserId(TokenData.takeFromRequest().getUserId()); + data.setCreateTime(new Date()); + } + data.setDeletedFlag(GlobalDeletedFlag.NORMAL); + data.setUpdateUserId(TokenData.takeFromRequest().getUserId()); + data.setUpdateTime(new Date()); + } + else if (t instanceof ConvertFieldmappingEntry){ + ConvertFieldmappingEntry data = (ConvertFieldmappingEntry) t; + data.setParentId(String.valueOf(id)); + if (ObjectUtil.isEmpty(data.getCreateTime())){ + data.setCreateUserId(TokenData.takeFromRequest().getUserId()); + data.setCreateTime(new Date()); + } + data.setDeletedFlag(GlobalDeletedFlag.NORMAL); + data.setUpdateUserId(TokenData.takeFromRequest().getUserId()); + data.setUpdateTime(new Date()); + } + } + @Autowired + private IOnlFormHeadService onlFormHeadService; + + @Override + public List> getPushBillList(ConvertRelationDelDto dto) { + //查询当前单据作为源单并且已启用的转换规则 + List list = this.list(new LambdaQueryWrapper().eq(ConvertRule::getEnabled, "true")); + //查询单据名称 + //全量在线表单数据 == 转map当临时表用 + List allOnlFormHeadsList = onlFormHeadService.list(new LambdaQueryWrapper()); + //过滤后的数据 + List filterOnlFormHeadList = allOnlFormHeadsList.stream().filter(a -> StringUtils.equals(a.getTableName(), dto.getBillType())).collect(Collectors.toList()); + Map longOnlFormHeadMap = allOnlFormHeadsList.stream().collect(Collectors.toMap(OnlFormHead::getId, OnlFormHead -> OnlFormHead, (k1, k2) -> k2)); + //过滤后的转换规则 + List convertRules = list.stream().filter(e -> filterOnlFormHeadList.stream().map(OnlFormHead::getId).collect(Collectors.toList()).contains(Long.valueOf(e.getSourceEntityId()))).collect(Collectors.toList()); + //重新封装数据 + List convertRuleDtosList = getConvertRuleDtos( longOnlFormHeadMap, convertRules); + //封装成前台需要的结构 + return buildToReturn(convertRuleDtosList); + } + + @Override + public List> getRuleTableFiled(String tableName) { + OnlFormHead headTableName = onlFormHeadService.getHeadTableNameCache(tableName); + List onlFormFieldList = headTableName.getOnlFormFieldList(); + String metaTable = headTableName.getMetaTable(); + if(StringUtil.isNotBlank(metaTable)){ + OnlFormHead metaTableHead = onlFormHeadService.getHeadTableNameCache(tableName); + onlFormFieldList.addAll(metaTableHead.getOnlFormFieldList()); + } + List> mapList = onlFormFieldList.stream() + .map(com.baomidou.mybatisplus.core.toolkit.BeanUtils::beanToMap) + .collect(Collectors.toList()); + return mapList; + } + + @NotNull + private static List> buildToReturn(List convertRuleDtosList) { + Map> stringListMap = convertRuleDtosList.stream().collect(Collectors.groupingBy(ConvertRuleDto::getBillType)); + //封装成文档定义格式返回 + List> resultList = new ArrayList<>(); + stringListMap.forEach((k,v)->{ + Map hashMap = new HashMap<>(); + resultList.add(hashMap); + //单据标识 + hashMap.put("billType",k); + //单据名称 + hashMap.put("billTypeName",v.get(0).getBillTypeName()); + List> billRuleList = new ArrayList<>(); + hashMap.put("billRuleList",billRuleList); + for (ConvertRuleDto convertRuleDto : v) { + Map billRuleListMap = new HashMap<>(); + billRuleList.add(billRuleListMap); + billRuleListMap.put("ruleId",convertRuleDto.getId()); + billRuleListMap.put("ruleNumber",convertRuleDto.getNumber()); + billRuleListMap.put("ruleName",convertRuleDto.getName()); + billRuleListMap.put("billEditUI",convertRuleDto.getBillEditUI()); + billRuleListMap.put("isShowEdit",convertRuleDto.getIsShowEdit()); + billRuleListMap.put("billEditUIType",convertRuleDto.getBillEditUIType()); + } + }); + return resultList; + } + @Autowired + private ISysMenuqqService sysMenuqqService; + + @NotNull + private List getConvertRuleDtos(Map longOnlFormHeadMap, List convertRules) { + List convertRuleDtosList = new ArrayList<>(); + //重新封装对象 + convertRules.forEach(e->{ + ConvertRuleDto convertRuleDto = new ConvertRuleDto(); + BeanUtils.copyProperties(e , convertRuleDto); + //单据标识 + convertRuleDto.setBillType(longOnlFormHeadMap.get(Long.valueOf(e.getTargetEntityId())).getTableName()); + //单据名称 + convertRuleDto.setBillTypeName(longOnlFormHeadMap.get(Long.valueOf(e.getTargetEntityId())).getTableTxt()); + //规则编码 + convertRuleDto.setNumber(e.getNumber()); + //规则名称 + convertRuleDto.setName(e.getName()); + //是否显示编辑页面 + convertRuleDto.setIsShowEdit(e.getVisible()); + //表单编辑页面 +// convertRuleDto.setBillEditUI(formRouterMap.get(e.getTargetEntityId())); + //1路由表单则返回路由页面,2在线表单则返回在线编辑页面 + if ("1".equals(e.getDownInterfaceType())) { + SysMenuqq sysMenu = sysMenuqqService.getById(e.getDownRouteInterface()); + if (sysMenu != null){ + convertRuleDto.setBillEditUI(sysMenu.getFormRouterName()); + } + convertRuleDto.setBillEditUIType("1"); + }else { + convertRuleDto.setBillEditUI(String.valueOf(e.getDownEditInterface())); + convertRuleDto.setBillEditUIType("2"); + } + convertRuleDtosList.add(convertRuleDto); + }); + return convertRuleDtosList; + } + + +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/service/impl/SysMenuqqServiceImpl.java b/common/common-botp/src/main/java/apelet/common/botp/service/impl/SysMenuqqServiceImpl.java new file mode 100644 index 0000000..783f9ac --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/service/impl/SysMenuqqServiceImpl.java @@ -0,0 +1,57 @@ +package apelet.common.botp.service.impl; + + +import apelet.common.botp.dao.SysMenuqqMapper; +import apelet.common.botp.model.AllField; +import apelet.common.botp.model.SysMenuqq; +import apelet.common.botp.service.ISysMenuqqService; +import apelet.common.core.base.dao.BaseDaoMapper; +import apelet.common.core.base.service.BaseService; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; + +/** + * @author admin + * @since 2024-01-18 10:31:58 + */ +@Service(value="sysMenuqqService") +@Slf4j +public class SysMenuqqServiceImpl extends BaseService implements ISysMenuqqService { + + @Autowired + private SysMenuqqMapper sysMenuqqMapper; + + + @Override + public List selectAll(String id) { + return null; + } + + @Override + public List allField(String tableName) { + return null; + } + + @Override + public Boolean removeAllById(Long id) { + return null; + } + + @Override + public Boolean editAll(SysMenuqq sysMenuqq) { + return null; + } + + @Override + public Boolean addAll(SysMenuqq sysMenuqq) { + return null; + } + + @Override + protected BaseDaoMapper mapper() { + return baseMapper; + } +} diff --git a/common/common-botp/src/main/java/apelet/common/botp/util/Constant.java b/common/common-botp/src/main/java/apelet/common/botp/util/Constant.java new file mode 100644 index 0000000..bc871ae --- /dev/null +++ b/common/common-botp/src/main/java/apelet/common/botp/util/Constant.java @@ -0,0 +1,17 @@ +package apelet.common.botp.util; + +/** + * @author Soon + * @version 1.0 + * Create by 2024/2/20 17:06 + */ +public class Constant { + + public final static String FormStatus_AddNew = "1";//新增状态 + public final static String FormStatus_Save = "2";//保存状态 + + public final static String InterfaceType_ROUTE = "1";//路由表单 + public final static String InterfaceType_ONLINE = "2";//在线表单 + + +} diff --git a/common/common-botp/src/main/resources/templates/controller.java.ftl b/common/common-botp/src/main/resources/templates/controller.java.ftl new file mode 100644 index 0000000..9d3cf42 --- /dev/null +++ b/common/common-botp/src/main/resources/templates/controller.java.ftl @@ -0,0 +1,54 @@ +package ${package.Controller}; + + +import apelet.common.core.annotation.MyRequestBody; +import apelet.common.core.constant.ErrorCodeEnum; +import apelet.common.core.object.MyOrderParam; +import apelet.common.core.object.MyPageData; +import apelet.common.core.object.MyPageParam; +import apelet.common.core.object.ResponseResult; +import apelet.common.core.util.MyPageUtil; +import apelet.tenantadmin.ape.model.ApeBase; +import apelet.tenantadmin.ape.model.service.IApeBaseService; +import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.github.pagehelper.Page; +import com.github.pagehelper.page.PageMethod; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; +<#if restControllerStyle> +import org.springframework.web.bind.annotation.RestController; +<#else> +import org.springframework.stereotype.Controller; + +<#if superControllerClassPackage??> +import ${superControllerClassPackage}; + + +/** + *

+ * ${table.comment!} 前端控制器 + *

+ * + * @author ${author} + * @since ${date} + */ +<#if restControllerStyle> +@RestController +<#else> +@Controller + +@RequestMapping("<#if package.ModuleName?? && package.ModuleName != "">/${package.ModuleName}/<#if controllerMappingHyphenStyle>${controllerMappingHyphen}<#else>${table.entityPath}") +<#if kotlin> +class ${table.controllerName}<#if superControllerClass??> : ${superControllerClass}() +<#else> +<#if superControllerClass??> +public class ${table.controllerName} extends ${superControllerClass} { +<#else> +public class ${table.controllerName} { + + +} + diff --git a/common/common-botp/src/main/resources/templates/controllertest.java.ftl b/common/common-botp/src/main/resources/templates/controllertest.java.ftl new file mode 100644 index 0000000..6df5c76 --- /dev/null +++ b/common/common-botp/src/main/resources/templates/controllertest.java.ftl @@ -0,0 +1,143 @@ +package ${package.Controller}; + + +import apelet.common.core.annotation.MyRequestBody; +import apelet.common.core.constant.ErrorCodeEnum; +import apelet.common.core.object.MyOrderParam; +import apelet.common.core.object.MyPageData; +import apelet.common.core.object.MyPageParam; +import apelet.common.core.object.ResponseResult; +import apelet.common.core.util.MyPageUtil; +import apelet.tenantadmin.ape.model.ApeBase; +import apelet.tenantadmin.ape.model.service.IApeBaseService; +import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.github.pagehelper.Page; +import com.github.pagehelper.page.PageMethod; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; +<#if restControllerStyle> +import org.springframework.web.bind.annotation.RestController; +<#else> +import org.springframework.stereotype.Controller; + +<#if superControllerClassPackage??> +import ${superControllerClassPackage}; + + +/** + *

+ * ${table.comment!} 前端控制器 + *

+ * + * @author ${author} + * @since ${date} + */ +<#if restControllerStyle> +@RestController +<#else> +@Controller + +@RequestMapping("<#if package.ModuleName?? && package.ModuleName != "">/${package.ModuleName}/<#if controllerMappingHyphenStyle>${controllerMappingHyphen}<#else>${table.entityPath}") +<#if kotlin> +class ${table.controllerName}<#if superControllerClass??> : ${superControllerClass}() +<#else> +<#if superControllerClass??> +public class ${table.controllerName} extends ${superControllerClass} { +<#else> +public class ${table.controllerName} { + + @Autowired + private ${table.controllerName}Service ${table.controllerName}Service; + + + /** + * ${table.controllerName}列表(分页) + * + * @param query 查询参数对象 + * @return + */ + @GetMapping("page") + public Result page(${table.controllerName}Query query) { + log.info("${table.controllerName}Controller.page 参数为:" + JsonUtil.toJsonFromObject(query)); + return Result.success(this.${table.controllerName}Service.page(query)); + } + + + /** + * ${table.controllerName}列表(不分页) + * + * @param query 查询参数对象 + * @return + */ + @GetMapping("list") + public Result list(${table.controllerName}Query query) { + log.info("${table.controllerName}Controller.list 参数为:" + JsonUtil.toJsonFromObject(query)); + return Result.success(this.${table.controllerName}Service.list(query)); + } + +/** +* 插入${table.comment} +* +* @param dto 待插入的${table.comment} +* @return +*/ + @PostMapping("insert") + public Result insert(@RequestBody @Validated(Insert.class) ${table.controllerName}Dto dto) { + log.info("${table.controllerName}Controller.insert 参数为:" + JsonUtil.toJsonFromObject(dto)); + return Result.success(this.${table.controllerName}Service.save(dto)); + } + + +/** +* 根据 id 获取${table.controllerName} +* +* @param id +* @return +*/ +@GetMapping("selectById") +public Result selectById(@RequestParam("id") Integer id) { + Assert.notNull(id, "id 不能为空"); + + log.info("${table.controllerName}Controller.selectById 参数为:" + id); + return Result.success(this.${table.controllerName}Service.getById(id)); +} + + +/** +* 根据 id 更新${table.controllerName} +* +* @param dto +* @return +*/ +@PostMapping("updateById") +public Result updateById(@RequestBody @Validated(Update.class) ${table.controllerName}Dto dto) { + Assert.notNull(dto.getId(), "id 不能为空"); + + log.info("${table.controllerName}Controller.updateById 参数为:" + JsonUtil.toJsonFromObject(dto)); + return Result.success(this.${table.controllerName}Service.updateById(dto)); +} + + +/** +* 根据 id 删除${table.controllerName} +* +* @param id +* @return +*/ +@PostMapping("deleteById") +public Result deleteById(@RequestParam("id") Integer id) { + Assert.notNull(id, "id 不能为空"); + + log.info("${table.controllerName}Controller.deleteById 参数为:" + id); + return Result.success(this.${table.controllerName}Service.removeById(id)); +} + + + + + +} + diff --git a/common/common-botp/src/main/resources/templates/dto.java.ftl b/common/common-botp/src/main/resources/templates/dto.java.ftl new file mode 100644 index 0000000..b536baf --- /dev/null +++ b/common/common-botp/src/main/resources/templates/dto.java.ftl @@ -0,0 +1,17 @@ +package ${package.Entity}; + + +/** + *

+ * 测试自定义DTO模板 ${table.comment!} + *

+ * + * 测试注入 ${cfg.abc} + */ + + +// 自定义的查询内容 +<#list table.fields as field> + 自定义 abc 内容: ${field.customMap.abc} + 自定义 def 内容: ${field.customMap.def} + diff --git a/common/common-botp/src/main/resources/templates/dtotest.java.ftl b/common/common-botp/src/main/resources/templates/dtotest.java.ftl new file mode 100644 index 0000000..b029fae --- /dev/null +++ b/common/common-botp/src/main/resources/templates/dtotest.java.ftl @@ -0,0 +1,25 @@ +package ${package.Entity}; + +import ${package}.${entity}#if(${moduleName} != "").${moduleName}#end.${className}; +import lombok.Data; +import lombok.experimental.Accessors; + +/** + *

+ * 测试自定义DTO模板 ${table.comment!} + *

+ * + * 测试注入 ${cfg.abc} + */ + + +/** +* @author ${author} +* @date ${date} +* @desc ${table.comment} dto +*/ +@Data +@Accessors(chain = true) +public class ${table.dtoName}Dto extends ${table.dtoName} implements Dto { + +} diff --git a/common/common-botp/src/main/resources/templates/entity.java.ftl b/common/common-botp/src/main/resources/templates/entity.java.ftl new file mode 100644 index 0000000..965211f --- /dev/null +++ b/common/common-botp/src/main/resources/templates/entity.java.ftl @@ -0,0 +1,158 @@ +package ${package.Entity}; + +<#list table.importPackages as pkg> +import ${pkg}; + +<#if springdoc> +import io.swagger.v3.oas.annotations.media.Schema; +<#elseif swagger> +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +<#if entityLombokModel> +import lombok.Data; + <#if chainModel> +import lombok.experimental.Accessors; + + + +/** + *

+ * ${table.comment!} + *

+ * + * @author ${author} + * @since ${date} + */ +<#if entityLombokModel> +@Data + <#if chainModel> +@Accessors(chain = true) + + +<#if table.convert> +@TableName("${schemaName}${table.name}") + +<#if springdoc> +@Schema(name = "${entity}", description = "${table.comment!}") +<#elseif swagger> +@ApiModel(value = "${entity}对象", description = "${table.comment!}") + +<#if superEntityClass??> +public class ${entity} extends ${superEntityClass}<#if activeRecord><${entity}> { +<#elseif activeRecord> +public class ${entity} extends Model<${entity}> { +<#elseif entitySerialVersionUID> +public class ${entity} implements Serializable { +<#else> +public class ${entity} { + +<#if entitySerialVersionUID> + + private static final long serialVersionUID = 1L; + +<#-- ---------- BEGIN 字段循环遍历 ----------> +<#list table.fields as field> + <#if field.keyFlag> + <#assign keyPropertyName="${field.propertyName}"/> + + + <#if field.comment!?length gt 0> + <#if springdoc> + @Schema(description = "${field.comment}") + <#elseif swagger> + @ApiModelProperty("${field.comment}") + <#else> + /** + * ${field.comment} + */ + + + <#if field.keyFlag> + <#-- 主键 --> + <#if field.keyIdentityFlag> + @TableId(value = "${field.annotationColumnName}", type = IdType.AUTO) + <#elseif idType??> + @TableId(value = "${field.annotationColumnName}", type = IdType.${idType}) + <#elseif field.convert> + @TableId("${field.annotationColumnName}") + + <#-- 普通字段 --> + <#elseif field.fill??> + <#-- ----- 存在字段填充设置 -----> + <#if field.convert> + @TableField(value = "${field.annotationColumnName}", fill = FieldFill.${field.fill}) + <#else> + @TableField(fill = FieldFill.${field.fill}) + + <#elseif field.convert> + @TableField("${field.annotationColumnName}") + + <#-- 乐观锁注解 --> + <#if field.versionField> + @Version + + <#-- 逻辑删除注解 --> + <#if field.logicDeleteField> + @TableLogic + + private ${field.propertyType} ${field.propertyName}; + +<#------------ END 字段循环遍历 ----------> +<#if !entityLombokModel> + <#list table.fields as field> + <#if field.propertyType == "boolean"> + <#assign getprefix="is"/> + <#else> + <#assign getprefix="get"/> + + + public ${field.propertyType} ${getprefix}${field.capitalName}() { + return ${field.propertyName}; + } + + <#if chainModel> + public ${entity} set${field.capitalName}(${field.propertyType} ${field.propertyName}) { + <#else> + public void set${field.capitalName}(${field.propertyType} ${field.propertyName}) { + + this.${field.propertyName} = ${field.propertyName}; + <#if chainModel> + return this; + + } + + +<#if entityColumnConstant> + <#list table.fields as field> + + public static final String ${field.name?upper_case} = "${field.name}"; + + +<#if activeRecord> + + @Override + public Serializable pkVal() { + <#if keyPropertyName??> + return this.${keyPropertyName}; + <#else> + return null; + + } + +<#if !entityLombokModel> + + @Override + public String toString() { + return "${entity}{" + + <#list table.fields as field> + <#if field_index==0> + "${field.propertyName} = " + ${field.propertyName} + + <#else> + ", ${field.propertyName} = " + ${field.propertyName} + + + + "}"; + } + +} diff --git a/common/common-botp/src/main/resources/templates/entity.kt.ftl b/common/common-botp/src/main/resources/templates/entity.kt.ftl new file mode 100644 index 0000000..47261c0 --- /dev/null +++ b/common/common-botp/src/main/resources/templates/entity.kt.ftl @@ -0,0 +1,122 @@ +package ${package.Entity} + +<#list table.importPackages as pkg> +import ${pkg} + +<#if springdoc> +import io.swagger.v3.oas.annotations.media.Schema; +<#elseif swagger> +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + + +/** + *

+ * ${table.comment} + *

+ * + * @author ${author} + * @since ${date} + */ +<#if table.convert> +@TableName("${schemaName}${table.name}") + +<#if springdoc> +@Schema(name = "${entity}", description = "$!{table.comment}") +<#elseif swagger> +@ApiModel(value = "${entity}对象", description = "${table.comment!}") + +<#if superEntityClass??> +class ${entity} : ${superEntityClass}<#if activeRecord><${entity}>() { +<#elseif activeRecord> +class ${entity} : Model<${entity}>() { +<#elseif entitySerialVersionUID> +class ${entity} : Serializable { +<#else> +class ${entity} { + + +<#-- ---------- BEGIN 字段循环遍历 ----------> +<#list table.fields as field> +<#if field.keyFlag> + <#assign keyPropertyName="${field.propertyName}"/> + +<#if field.comment!?length gt 0> + <#if springdoc> + @Schema(description = "${field.comment}") + <#elseif swagger> + @ApiModelProperty("${field.comment}") + <#else> + /** + * ${field.comment} + */ + + +<#if field.keyFlag> +<#-- 主键 --> +<#if field.keyIdentityFlag> + @TableId(value = "${field.annotationColumnName}", type = IdType.AUTO) +<#elseif idType ??> + @TableId(value = "${field.annotationColumnName}", type = IdType.${idType}) +<#elseif field.convert> + @TableId("${field.annotationColumnName}") + +<#-- 普通字段 --> +<#elseif field.fill??> +<#-- ----- 存在字段填充设置 -----> +<#if field.convert> + @TableField(value = "${field.annotationColumnName}", fill = FieldFill.${field.fill}) +<#else> + @TableField(fill = FieldFill.${field.fill}) + +<#elseif field.convert> + @TableField("${field.annotationColumnName}") + +<#-- 乐观锁注解 --> +<#if field.versionField> + @Version + +<#-- 逻辑删除注解 --> +<#if field.logicDeleteField> + @TableLogic + + <#if field.propertyType == "Integer"> + var ${field.propertyName}: Int? = null + <#else> + var ${field.propertyName}: ${field.propertyType}? = null + + + +<#-- ---------- END 字段循环遍历 ----------> +<#if entityColumnConstant> + companion object { +<#list table.fields as field> + + const val ${field.name?upper_case} : String = "${field.name}" + + + } + + +<#if activeRecord> + override fun pkVal(): Serializable? { +<#if keyPropertyName??> + return ${keyPropertyName} +<#else> + return null + + } + + + override fun toString(): String { + return "${entity}{" + +<#list table.fields as field> +<#if field_index==0> + "${field.propertyName}=" + ${field.propertyName} + +<#else> + ", ${field.propertyName}=" + ${field.propertyName} + + + + "}" + } +} diff --git a/common/common-botp/src/main/resources/templates/entity1.java.ftl b/common/common-botp/src/main/resources/templates/entity1.java.ftl new file mode 100644 index 0000000..f6f8f65 --- /dev/null +++ b/common/common-botp/src/main/resources/templates/entity1.java.ftl @@ -0,0 +1,152 @@ +package ${package.Entity}; + +<#list table.importPackages as pkg> +import ${pkg}; + +<#if swagger> +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +<#if entityLombokModel> +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.experimental.Accessors; + + +/** + *

+ 自定义模板 + * ${table.comment!} +<#-- 自定义属性注入abc=${cfg.abc}--> + *

+ * + * @author ${author} + * @since ${date} + */ +<#if entityLombokModel> +@Data + <#if superEntityClass??> +@EqualsAndHashCode(callSuper = true) + <#else> +@EqualsAndHashCode(callSuper = false) + +@Accessors(chain = true) + +<#if table.convert> +@TableName("${table.name}") + +<#if swagger> +@ApiModel(value="${entity}对象", description="${table.comment!}") + +<#if superEntityClass??> +public class ${entity} extends ${superEntityClass}<#if activeRecord><${entity}> { +<#elseif activeRecord> +public class ${entity} extends Model<${entity}> { +<#else> +public class ${entity} implements Serializable { + + + private static final long serialVersionUID = 1L; +<#-- ---------- BEGIN 字段循环遍历 ----------> +<#list table.fields as field> + <#if field.keyFlag> + <#assign keyPropertyName="${field.propertyName}"/> + + + <#if field.comment!?length gt 0> + <#if swagger> + @ApiModelProperty(value = "${field.comment}") + <#else> + /** + * ${field.comment} + */ + + + <#if field.keyFlag> + <#-- 主键 --> + <#if field.keyIdentityFlag> + @TableId(value = "${field.name}", type = IdType.AUTO) + <#elseif idType??> + @TableId(value = "${field.name}", type = IdType.${idType}) + <#elseif field.convert> + @TableId("${field.name}") + + <#-- 普通字段 --> + <#elseif field.fill??> + <#-- ----- 存在字段填充设置 -----> + <#if field.convert> + @TableField(value = "${field.name}", fill = FieldFill.${field.fill}) + <#else> + @TableField(fill = FieldFill.${field.fill}) + + <#elseif field.convert> + @TableField("${field.name}") + +<#-- 乐观锁注解 --> + <#if (versionFieldName!"") == field.name> + @Version + +<#-- 逻辑删除注解 --> + <#if (logicDeleteFieldName!"") == field.name> + @TableLogic + + private ${field.propertyType} ${field.propertyName}; + +<#------------ END 字段循环遍历 ----------> + +<#if !entityLombokModel> + <#list table.fields as field> + <#if field.propertyType == "boolean"> + <#assign getprefix="is"/> + <#else> + <#assign getprefix="get"/> + + public ${field.propertyType} ${getprefix}${field.capitalName}() { + return ${field.propertyName}; + } + + <#if entityBuilderModel> + public ${entity} set${field.capitalName}(${field.propertyType} ${field.propertyName}) { + <#else> + public void set${field.capitalName}(${field.propertyType} ${field.propertyName}) { + + this.${field.propertyName} = ${field.propertyName}; + <#if entityBuilderModel> + return this; + + } + + + +<#if entityColumnConstant> + <#list table.fields as field> + public static final String ${field.name?upper_case} = "${field.name}"; + + + +<#if activeRecord> + @Override + protected Serializable pkVal() { + <#if keyPropertyName??> + return this.${keyPropertyName}; + <#else> + return null; + + } + + +<#if !entityLombokModel> + @Override + public String toString() { + return "${entity}{" + + <#list table.fields as field> + <#if field_index==0> + "${field.propertyName}=" + ${field.propertyName} + + <#else> + ", ${field.propertyName}=" + ${field.propertyName} + + + + "}"; + } + +} diff --git a/common/common-botp/src/main/resources/templates/from.vue.ftl b/common/common-botp/src/main/resources/templates/from.vue.ftl new file mode 100644 index 0000000..e69de29 diff --git a/common/common-botp/src/main/resources/templates/list.vue.ftl b/common/common-botp/src/main/resources/templates/list.vue.ftl new file mode 100644 index 0000000..52917e4 --- /dev/null +++ b/common/common-botp/src/main/resources/templates/list.vue.ftl @@ -0,0 +1,535 @@ + + + diff --git a/common/common-botp/src/main/resources/templates/mapper.java.ftl b/common/common-botp/src/main/resources/templates/mapper.java.ftl new file mode 100644 index 0000000..5ccd018 --- /dev/null +++ b/common/common-botp/src/main/resources/templates/mapper.java.ftl @@ -0,0 +1,26 @@ +package ${package.Mapper}; + +import ${package.Entity}.${entity}; +import ${superMapperClassPackage}; +<#if mapperAnnotationClass??> +import ${mapperAnnotationClass.name}; + + +/** + *

+ * ${table.comment!} Mapper 接口 + *

+ * + * @author ${author} + * @since ${date} + */ +<#if mapperAnnotationClass??> +@${mapperAnnotationClass.simpleName} + +<#if kotlin> +interface ${table.mapperName} : ${superMapperClass}<${entity}> +<#else> +public interface ${table.mapperName} extends ${superMapperClass}<${entity}> { + +} + diff --git a/common/common-botp/src/main/resources/templates/mapper.xml.ftl b/common/common-botp/src/main/resources/templates/mapper.xml.ftl new file mode 100644 index 0000000..851af12 --- /dev/null +++ b/common/common-botp/src/main/resources/templates/mapper.xml.ftl @@ -0,0 +1,39 @@ + + + + +<#if enableCache> + + + + +<#if baseResultMap> + + +<#list table.fields as field> +<#if field.keyFlag><#--生成主键排在第一位--> + + + +<#list table.commonFields as field><#--生成公共字段 --> + + +<#list table.fields as field> +<#if !field.keyFlag><#--生成普通字段 --> + + + + + + +<#if baseColumnList> + + +<#list table.commonFields as field> + ${field.columnName}, + + ${table.fieldNames} + + + + diff --git a/common/common-botp/src/main/resources/templates/service.java.ftl b/common/common-botp/src/main/resources/templates/service.java.ftl new file mode 100644 index 0000000..e3232f3 --- /dev/null +++ b/common/common-botp/src/main/resources/templates/service.java.ftl @@ -0,0 +1,20 @@ +package ${package.Service}; + +import ${package.Entity}.${entity}; +import ${superServiceClassPackage}; + +/** + *

+ * ${table.comment!} 服务类 + *

+ * + * @author ${author} + * @since ${date} + */ +<#if kotlin> +interface ${table.serviceName} : ${superServiceClass}<${entity}> +<#else> +public interface ${table.serviceName} extends ${superServiceClass}<${entity}> { + +} + diff --git a/common/common-botp/src/main/resources/templates/serviceImpl.java.ftl b/common/common-botp/src/main/resources/templates/serviceImpl.java.ftl new file mode 100644 index 0000000..8368702 --- /dev/null +++ b/common/common-botp/src/main/resources/templates/serviceImpl.java.ftl @@ -0,0 +1,181 @@ +package ${package.ServiceImpl}; + +import apelet.common.core.annotation.MyDataSource; +import lombok.extern.slf4j.Slf4j; +import apelet.common.core.base.service.BaseService; +import apelet.common.core.object.TokenData; +import cn.hutool.core.util.* +import ${package.Entity}.${entity}; +import ${package.Mapper}.${table.mapperName}; +<#if table.serviceInterface> +import ${package.Service}.${table.serviceName}; + +import ${superServiceImplClassPackage}; +import org.springframework.stereotype.Service; + +/** + *

+ * ${table.comment!} 服务实现类 + *

+ * + * @author ${author} + * @since ${date} + */ +@Service +@Slf4j +<#--<#if kotlin>--> +<#--open class ${table.serviceImplName} : ${superServiceImplClass}<${table.mapperName}, ${entity}>()<#if table.serviceInterface>, ${table.serviceName}--> +<#-- {}--> +<#--<#else>--> +<#--public class ${table.serviceImplName} extends ${superServiceImplClass}<${table.mapperName}, ${entity}><#if table.serviceInterface> implements ${table.serviceName}--> +<#-- {}--> +<#----> +public class ${table.serviceImplName} extends BaseService<${entity}, Long> implements ${table.serviceName} { + @Autowired + private ${table.mapperName} ${table.mapperName}; + + @Override + protected BaseDaoMapper<${entity}> mapper() { return baseMapper; } + + + String path="C:\\导出路径后期模版修改"; + + /** + * 查询列表 + */ + @Override + public List<${entity}> get${entity}ListWithRelation(${entity} filter, String buildOrderBy) { + LambdaQueryWrapper<${entity}> queryWrapper = new LambdaQueryWrapper<>(filter); + if (StrUtil.isNotBlank(buildOrderBy)) { + queryWrapper.last(" ORDER BY " + buildOrderBy); + } + List<${entity}> resultList = baseMapper.selectList(queryWrapper); + int batchSize = resultList instanceof Page ? 0 : 1000; + this.buildRelationForDataList(resultList, MyRelationParam.normal(), batchSize); + return resultList; + } + + /** + * 新增 + */ + @Override + public Boolean addAll(${entity} base) { + //设置主数据基本信息 + addOrUpdateBaseData(base,null); + boolean save =this.save(base); + //如果有分录 +<#-- Long id = base.getId();--> +<#-- if (null==id)return false;--> +<#-- //设置分录数据基本信息,添加--> +<#-- return addChild(base,id);--> + return save; + } + /** + * 修改 + */ + @Override + public Boolean editAll(${entity} base) { + Long id = base.getId(); + if (null==id)return false; + //设置主数据基本信息 + boolean update =addOrUpdateBaseData(apeBase,null); + this.updateById(apeBase); +<#-- //删除分录数据--> +<#-- removeChild(id);--> +<#-- //设置分录数据基本信息,重新添加--> +<#-- return addChild(apeBase,id);--> + return update; + } + + /** + * 删除 + */ + @Override + public Boolean removeAllById(Long id) { + boolean remove = this.removeById(id); + //有分录情况删除 +<#-- if (remove){--> +<#-- removeChild(id);--> +<#-- }--> + return remove; + } + @Override + public void exportExcel(JSONObject data, HttpServletResponse response){ + JSONArray ids = data.getJSONArray("ids"); + List<${entity}> dataList=new ArrayList<>(); + if (ObjectUtil.isNotEmpty(ids)){ + dataList.addAll(this.listByIds(ids.toJavaList(Long.class))); + }else { + dataList.addAll(this.list()); + } +<#-- //如果有分录--> +<#-- for (${entity} base : dataList) {--> +<#-- base.setChild1(child1Mapper.selectList(new LambdaQueryWrapper<${entity}>().eq(ApeBaseChild1::getMaterId,apeBase.getId())));--> +<#-- base.setChild2(child2Mapper.selectList(new LambdaQueryWrapper<${entity}>().eq(ApeBaseChild2::getMaterId,apeBase.getId())));--> +<#-- base.setChild3(child3Mapper.selectList(new LambdaQueryWrapper<${entity}>().eq(ApeBaseChild3::getMaterId,apeBase.getId())));--> +<#-- }--> + ApeEasyPoiUtil.exportExcel(response,dataList,${entity}.class,path,"excel导出的名称","excel导出的sheet名称"); + } + /** + * 导入 + */ + @Override + public void importExcel(HttpServletRequest request){ + List<${entity}> list = ApeEasyPoiUtil.importExcel(request, ApeBase.class); + for (ApeBase apeBase : list) { + addAll(apeBase); + } + } + + + + + + +<#-- /**--> +<#-- * 如果有分录情况下且需要参数映射就需要这样命名方法--> +<#-- */--> +<#-- @Override--> +<#-- public List getChild1WithRelation(Long id) {--> +<#-- return child1Service.getChild1WithRelation(id);--> +<#-- }--> + + +<#-- /**--> +<#-- * 如果有分录且需要条件--> +<#-- */--> +<#-- private Boolean addChild(ApeBase apeBase,Long id){--> +<#-- List child = apeBase.getChild1();--> +<#-- if (ObjectUtil.isNotEmpty(child)){--> +<#-- for (child one : child) {--> +<#-- addOrUpdateBaseData(one,id);--> +<#-- childMapper.insert(one);--> +<#-- }--> +<#-- }--> +<#-- return true;--> +<#-- }--> + + +<#-- /**--> +<#-- * 有分录的情况下删除分录的方法--> +<#-- */--> +<#-- private void removeChild(Long id){--> +<#-- child1Service1.remove(new LambdaQueryWrapper().eq(child::getMaterId,id));--> +<#-- }--> + /** + * 设置基本参数方法 + */ + private void addOrUpdateBaseData(T t,Long id){ + if (t instanceof ${entity}){ + ${entity} data = (${entity}) t; + data.setDeletedFlag(GlobalDeletedFlag.NORMAL); + data.setUpdateUserId(TokenData.takeFromRequest().getUserId()); + data.setUpdateTime(new Date()); + if (ObjectUtil.isEmpty(data.getCreateTime())){ + data.setCreateUserId(TokenData.takeFromRequest().getUserId()); + data.setCreateTime(new Date()); + } + } + } +} + diff --git a/common/common-botp/src/main/resources/templates/serviceImpltest.java.ftl b/common/common-botp/src/main/resources/templates/serviceImpltest.java.ftl new file mode 100644 index 0000000..8368702 --- /dev/null +++ b/common/common-botp/src/main/resources/templates/serviceImpltest.java.ftl @@ -0,0 +1,181 @@ +package ${package.ServiceImpl}; + +import apelet.common.core.annotation.MyDataSource; +import lombok.extern.slf4j.Slf4j; +import apelet.common.core.base.service.BaseService; +import apelet.common.core.object.TokenData; +import cn.hutool.core.util.* +import ${package.Entity}.${entity}; +import ${package.Mapper}.${table.mapperName}; +<#if table.serviceInterface> +import ${package.Service}.${table.serviceName}; + +import ${superServiceImplClassPackage}; +import org.springframework.stereotype.Service; + +/** + *

+ * ${table.comment!} 服务实现类 + *

+ * + * @author ${author} + * @since ${date} + */ +@Service +@Slf4j +<#--<#if kotlin>--> +<#--open class ${table.serviceImplName} : ${superServiceImplClass}<${table.mapperName}, ${entity}>()<#if table.serviceInterface>, ${table.serviceName}--> +<#-- {}--> +<#--<#else>--> +<#--public class ${table.serviceImplName} extends ${superServiceImplClass}<${table.mapperName}, ${entity}><#if table.serviceInterface> implements ${table.serviceName}--> +<#-- {}--> +<#----> +public class ${table.serviceImplName} extends BaseService<${entity}, Long> implements ${table.serviceName} { + @Autowired + private ${table.mapperName} ${table.mapperName}; + + @Override + protected BaseDaoMapper<${entity}> mapper() { return baseMapper; } + + + String path="C:\\导出路径后期模版修改"; + + /** + * 查询列表 + */ + @Override + public List<${entity}> get${entity}ListWithRelation(${entity} filter, String buildOrderBy) { + LambdaQueryWrapper<${entity}> queryWrapper = new LambdaQueryWrapper<>(filter); + if (StrUtil.isNotBlank(buildOrderBy)) { + queryWrapper.last(" ORDER BY " + buildOrderBy); + } + List<${entity}> resultList = baseMapper.selectList(queryWrapper); + int batchSize = resultList instanceof Page ? 0 : 1000; + this.buildRelationForDataList(resultList, MyRelationParam.normal(), batchSize); + return resultList; + } + + /** + * 新增 + */ + @Override + public Boolean addAll(${entity} base) { + //设置主数据基本信息 + addOrUpdateBaseData(base,null); + boolean save =this.save(base); + //如果有分录 +<#-- Long id = base.getId();--> +<#-- if (null==id)return false;--> +<#-- //设置分录数据基本信息,添加--> +<#-- return addChild(base,id);--> + return save; + } + /** + * 修改 + */ + @Override + public Boolean editAll(${entity} base) { + Long id = base.getId(); + if (null==id)return false; + //设置主数据基本信息 + boolean update =addOrUpdateBaseData(apeBase,null); + this.updateById(apeBase); +<#-- //删除分录数据--> +<#-- removeChild(id);--> +<#-- //设置分录数据基本信息,重新添加--> +<#-- return addChild(apeBase,id);--> + return update; + } + + /** + * 删除 + */ + @Override + public Boolean removeAllById(Long id) { + boolean remove = this.removeById(id); + //有分录情况删除 +<#-- if (remove){--> +<#-- removeChild(id);--> +<#-- }--> + return remove; + } + @Override + public void exportExcel(JSONObject data, HttpServletResponse response){ + JSONArray ids = data.getJSONArray("ids"); + List<${entity}> dataList=new ArrayList<>(); + if (ObjectUtil.isNotEmpty(ids)){ + dataList.addAll(this.listByIds(ids.toJavaList(Long.class))); + }else { + dataList.addAll(this.list()); + } +<#-- //如果有分录--> +<#-- for (${entity} base : dataList) {--> +<#-- base.setChild1(child1Mapper.selectList(new LambdaQueryWrapper<${entity}>().eq(ApeBaseChild1::getMaterId,apeBase.getId())));--> +<#-- base.setChild2(child2Mapper.selectList(new LambdaQueryWrapper<${entity}>().eq(ApeBaseChild2::getMaterId,apeBase.getId())));--> +<#-- base.setChild3(child3Mapper.selectList(new LambdaQueryWrapper<${entity}>().eq(ApeBaseChild3::getMaterId,apeBase.getId())));--> +<#-- }--> + ApeEasyPoiUtil.exportExcel(response,dataList,${entity}.class,path,"excel导出的名称","excel导出的sheet名称"); + } + /** + * 导入 + */ + @Override + public void importExcel(HttpServletRequest request){ + List<${entity}> list = ApeEasyPoiUtil.importExcel(request, ApeBase.class); + for (ApeBase apeBase : list) { + addAll(apeBase); + } + } + + + + + + +<#-- /**--> +<#-- * 如果有分录情况下且需要参数映射就需要这样命名方法--> +<#-- */--> +<#-- @Override--> +<#-- public List getChild1WithRelation(Long id) {--> +<#-- return child1Service.getChild1WithRelation(id);--> +<#-- }--> + + +<#-- /**--> +<#-- * 如果有分录且需要条件--> +<#-- */--> +<#-- private Boolean addChild(ApeBase apeBase,Long id){--> +<#-- List child = apeBase.getChild1();--> +<#-- if (ObjectUtil.isNotEmpty(child)){--> +<#-- for (child one : child) {--> +<#-- addOrUpdateBaseData(one,id);--> +<#-- childMapper.insert(one);--> +<#-- }--> +<#-- }--> +<#-- return true;--> +<#-- }--> + + +<#-- /**--> +<#-- * 有分录的情况下删除分录的方法--> +<#-- */--> +<#-- private void removeChild(Long id){--> +<#-- child1Service1.remove(new LambdaQueryWrapper().eq(child::getMaterId,id));--> +<#-- }--> + /** + * 设置基本参数方法 + */ + private void addOrUpdateBaseData(T t,Long id){ + if (t instanceof ${entity}){ + ${entity} data = (${entity}) t; + data.setDeletedFlag(GlobalDeletedFlag.NORMAL); + data.setUpdateUserId(TokenData.takeFromRequest().getUserId()); + data.setUpdateTime(new Date()); + if (ObjectUtil.isEmpty(data.getCreateTime())){ + data.setCreateUserId(TokenData.takeFromRequest().getUserId()); + data.setCreateTime(new Date()); + } + } + } +} + diff --git a/common/common-botp/src/main/resources/templates/servicetest.java.ftl b/common/common-botp/src/main/resources/templates/servicetest.java.ftl new file mode 100644 index 0000000..e3232f3 --- /dev/null +++ b/common/common-botp/src/main/resources/templates/servicetest.java.ftl @@ -0,0 +1,20 @@ +package ${package.Service}; + +import ${package.Entity}.${entity}; +import ${superServiceClassPackage}; + +/** + *

+ * ${table.comment!} 服务类 + *

+ * + * @author ${author} + * @since ${date} + */ +<#if kotlin> +interface ${table.serviceName} : ${superServiceClass}<${entity}> +<#else> +public interface ${table.serviceName} extends ${superServiceClass}<${entity}> { + +} + diff --git a/common/common-botp/src/main/resources/templates/vo.java.ftl b/common/common-botp/src/main/resources/templates/vo.java.ftl new file mode 100644 index 0000000..416cdd6 --- /dev/null +++ b/common/common-botp/src/main/resources/templates/vo.java.ftl @@ -0,0 +1,16 @@ +package ${package.Entity}; + + +/** + *

+ * 测试自定义VO模板 ${table.comment!} + *

+ * + * 测试注入 ${cfg.abc} + */ + + +// 自定义的查询内容 +<#list table.fields as field> + 字段: ${field.propertyName} + -- 2.9.0.windows.1