From a85e0777e37a0c998e9d4d7ec9ba1b5671c19ef9 Mon Sep 17 00:00:00 2001 From: "youHong.ai" <774495953@qq.com> Date: Thu, 8 Dec 2022 15:32:28 +0800 Subject: [PATCH 01/33] =?UTF-8?q?=E4=BF=9D=E6=97=B6=E6=8D=B7target=20setti?= =?UTF-8?q?ng=20=E6=B5=81=E7=A8=8B=E6=8E=A7=E5=88=B6=E5=BC=80=E5=8F=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- javascript/youhong.ai/pcn/Utils.js | 40 ++++++++++ javascript/youhong.ai/pcn/dev.js | 78 +++++++++++++++++++ .../youhong.ai/pcn/workflow_code_block.js | 78 ++++++++++++++++++- .../java/youhong/ai/pcn/TestOrganization.java | 21 ----- 4 files changed, 195 insertions(+), 22 deletions(-) create mode 100644 javascript/youhong.ai/pcn/Utils.js create mode 100644 javascript/youhong.ai/pcn/dev.js diff --git a/javascript/youhong.ai/pcn/Utils.js b/javascript/youhong.ai/pcn/Utils.js new file mode 100644 index 0000000..abe0dac --- /dev/null +++ b/javascript/youhong.ai/pcn/Utils.js @@ -0,0 +1,40 @@ +$(() => { + /** + * @author youhong.ai + * @desc 获取react组件实例 + */ + function findReact(dom, traverseUp = 0) { + const key = Object.keys(dom).find(key => { + return key.startsWith("__reactFiber$") // react 17+ + || key.startsWith("__reactInternalInstance$") // react <17 + }); + const domFiber = dom[key]; + if (domFiber == null) return null; + // react <16 + if (domFiber._currentElement) { + let compFiber = domFiber._currentElement._owner; + for (let i = 0; i < traverseUp; i++) { + compFiber = compFiber._currentElement._owner; + } + return compFiber._instance; + } + // react 16+ + const GetCompFiber = fiber => { + let parentFiber = fiber.return; + while (typeof parentFiber.type == "string") { + parentFiber = parentFiber.return; + } + return parentFiber; + }; + let compFiber = GetCompFiber(domFiber); + for (let i = 0; i < traverseUp; i++) { + compFiber = GetCompFiber(compFiber); + } + return compFiber.stateNode; + } + + window.Utils = { + findReact, + } + +}) diff --git a/javascript/youhong.ai/pcn/dev.js b/javascript/youhong.ai/pcn/dev.js new file mode 100644 index 0000000..0cdfdb8 --- /dev/null +++ b/javascript/youhong.ai/pcn/dev.js @@ -0,0 +1,78 @@ +const WfForm = { + isMobile: () => { + // true表示是eMobile、微信、钉钉等移动终端,false代表PC端 + }, +} +WfForm.OPER_SAVE = '保存' +WfForm.OPER_SUBMIT = '提交/批准/提交需反馈/不需反馈等' +WfForm.OPER_SUBMITCONFIRM = '提交至确认页面,如果是确认界面,点确认触发的是SUBMIT' +WfForm.OPER_REJECT = '退回' +WfForm.OPER_REMARK = '批注提交' +WfForm.OPER_INTERVENE = '干预' +WfForm.OPER_FORWARD = '转发' +WfForm.OPER_TAKEBACK = '强制收回' +WfForm.OPER_DELETE = '删除' +WfForm.OPER_ADDROW = '添加明细行,需拼明细表序号' +WfForm.OPER_DELROW = '删除明细行,需拼明细表序号' +WfForm.OPER_PRINTPREVIEW = '打印预览 KB900190501' +WfForm.OPER_EDITDETAILROW = '移动端-编辑明细 KB900191101' +WfForm.OPER_BEFOREVERIFY = '校验必填前触发事件 KB900191201' +WfForm.OPER_TURNHANDLE = '转办 KB900201101' +WfForm.OPER_ASKOPINION = '意见征询 KB900201101' +WfForm.OPER_TAKFROWARD = '征询转办 KB900201101' +WfForm.OPER_TURNREAD = '传阅 KB900201101' +WfForm.OPER_FORCEOVER = '强制归档 KB900201101' +WfForm.OPER_BEFORECLICKBTN = '点右键按钮前 KB900201101' +WfForm.OPER_SAVECOMPLETE = '保存后页面跳转前 KB900210501' +WfForm.OPER_WITHDRAW = '撤回 KB900201101' +WfForm.OPER_CLOSE = '页面关闭' + +WfForm.registerCheckEvent = (type, callback) => { + // WfForm.registerCheckEvent(WfForm.OPER_SAVE+","+WfForm.OPER_SUBMIT,function(callback){ + // //... 执行自定义逻辑 + // callback(); + // }); +} + +WfForm.ACTION_ADDROW = '添加明细行,需拼明细表序号 KB900190407' +WfForm.ACTION_DELROW = '删除明细行,需拼明细表序号 KB900190407' +WfForm.ACTION_EDITDETAILROW = '移动端-编辑明细行,需拼明细表序号 KB900190501' +WfForm.ACTION_SWITCHDETAILPAGING = '切换明细分页 KB900191201' +WfForm.ACTION_SWITCHTABLAYOUT = '切换模板布局标签页 KB900191201' + +WfForm.registerAction = (type, callback) => { + // WfForm.registerAction(WfForm.ACTION_ADDROW+"1", function(index){ + // alert("添加行下标是"+index); + // }); //下标从1开始,明细1添加行触发事件,注册函数入参为新添加行下标 + // WfForm.registerAction(WfForm.ACTION_DELROW+"2", function(arg){ + // alert("删除行下标集合是"+arg.join(",")); + // }); //下标从1开始,明细2删除行触发事件 + // WfForm.registerAction(WfForm.ACTION_SWITCHDETAILPAGING, function(groupid){ + // alert("切换明细表"+(groupid+1)+"的页码触发事件"); + // }); + // WfForm.registerAction(WfForm.ACTION_SWITCHTABLAYOUT, function(tabid){ + // alert("切换到标签项"+tabid+"触发事件"); + // }); +} + +WfForm.convertFieldNameToId = (fieldName, table, flag) => { + // var fieldid = WfForm.convertFieldNameToId("zs"); + // var fieldid = WfForm.convertFieldNameToId("zs_mx", "detail_1"); + // var fieldid = WfForm.convertFieldNameToId("zs_mx", "detail_1", false); +} + +WfForm.getFieldValue = function (fieldMark) { + // fieldMark String 是 字段标示,格式field${字段ID}_${明细行号} + // var fieldvalue = WfForm.getFieldValue("field110"); +} + +WfForm.bindFieldChangeEvent = function (fieldMarkStr, funobj) { +// fieldMarkStr String 是 绑定字段标示,可多个拼接逗号隔开,例如:field110(主字段),field111_2(明细字段)…… +// funobj Function 是 字段值变化触发的自定义函数,函数默认传递以下三个参数,参数1:触发字段的DOM对象,参数2:触发字段的标示(field27555等),参数3:修改后的值 +// WfForm.bindFieldChangeEvent("field27555,field27556", function (obj, id, value) { +// console.log("WfForm.bindFieldChangeEvent--", obj, id, value); +// }); +} + + + diff --git a/javascript/youhong.ai/pcn/workflow_code_block.js b/javascript/youhong.ai/pcn/workflow_code_block.js index 95cbb39..2e07303 100644 --- a/javascript/youhong.ai/pcn/workflow_code_block.js +++ b/javascript/youhong.ai/pcn/workflow_code_block.js @@ -1 +1,77 @@ -// 流程代码块 +/* ******************* 保时捷target setting流程提交控制 start ******************* */ +/** + * @author youhong.ai + * @desc 禁止点击提交按钮 + */ +function doNotClickSubmit() { + let submitButton = $('.ant-btn.ant-btn-primary[ecid="_Route@vmt0lk_Comp@upn4fo_Button@2oxqe7@0_button@xq1ea3"][title="Submit "]') + if (submitButton.length === 0) { + submitButton = $('.ant-btn.ant-btn-primary[ecid="_Route@vmt0lk_Comp@upn4fo_Button@2oxqe7@0_button@xq1ea3"][title="提交"]') + } + if (submitButton.length === 0) { + submitButton = $("#weareqtop_9v5e5i_1670481049632 div.ant-row.wea-new-top-req div.ant-col-xs-18.ant-col-sm-18.ant-col-md-16.ant-col-lg-14 button[title='提交'],[title='Submit '],[title='Submit']") + } + if (submitButton.length !== 0) { + let buttonReact = window.Utils.findReact(submitButton[0]) + console.log(buttonReact) + buttonReact.props.disabled = true + buttonReact.setState({disabled: true}) + } +} + +/** + * @author youhong.ai + * @desc 允许点击按钮 + */ +function allowClickSubmit() { + let submitButton = $('.ant-btn.ant-btn-primary[ecid="_Route@vmt0lk_Comp@upn4fo_Button@2oxqe7@0_button@xq1ea3"][title="Submit "]') + if (submitButton.length === 0) { + submitButton = $('.ant-btn.ant-btn-primary[ecid="_Route@vmt0lk_Comp@upn4fo_Button@2oxqe7@0_button@xq1ea3"][title="提交"]') + } + if (submitButton.length === 0) { + submitButton = $("#weareqtop_9v5e5i_1670481049632 div.ant-row.wea-new-top-req div.ant-col-xs-18.ant-col-sm-18.ant-col-md-16.ant-col-lg-14 button[title='提交'],[title='Submit '],[title='Submit']") + } + if (submitButton.length !== 0) { + let buttonReact = window.Utils.findReact(submitButton[0]) + console.log(buttonReact) + buttonReact.props.disabled = false + buttonReact.setState({disabled: false}) + } +} + +/** + * 监听qzhj字段值改变 + * @param id 字段id + * @param value 字段值 + * @param obj 字段值对象 + */ +function onQzhjFieldChangeValue(id, value, obj) { + console.log(value) + if (value != '100') { + doNotClickSubmit() + } else { + allowClickSubmit() + } +} + +/** + * 检查qzhj字段值 + * @param fieldId qzhj字段id + */ +function checkOnQzhJfiedlChangeValue(fieldId) { + let value = WfForm.getFieldValue(fieldId); + onQzhjFieldChangeValue(null, value) +} + + +$(() => { + let qzhjFieldId = WfForm.convertFieldNameToId("qzhj") + checkOnQzhJfiedlChangeValue(qzhjFieldId) + WfForm.bindFieldChangeEvent(qzhjFieldId, onQzhjFieldChangeValue) +}) + +/* ******************* 保时捷target setting流程提交控制 end ******************* */ + + + + diff --git a/src/test/java/youhong/ai/pcn/TestOrganization.java b/src/test/java/youhong/ai/pcn/TestOrganization.java index 89992af..d2a5658 100644 --- a/src/test/java/youhong/ai/pcn/TestOrganization.java +++ b/src/test/java/youhong/ai/pcn/TestOrganization.java @@ -5,7 +5,6 @@ import aiyh.utils.httpUtil.ResponeVo; import aiyh.utils.httpUtil.util.HttpUtils; import basetest.BaseTest; import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; import com.api.youhong.ai.pcn.organization.orgchart.service.OrgChartService; import com.api.youhong.ai.pcn.organization.orgchart.vo.OrgChartNodeVo; import com.fasterxml.jackson.core.JsonProcessingException; @@ -224,24 +223,4 @@ public class TestOrganization extends BaseTest { System.out.println(JSON.toJSONString(orgChartTree)); } - @Test - public void testDownload() throws IOException { - HttpUtils httpUtils = new HttpUtils(); -// String url = "http://e-sign-dev-yace-web-alb-1694614450.cn-north-1.elb.amazonaws.com.cn:8070/contract/download?appId=100000&signType=SHA256&sign=OEI4RDA5RjMwRTE3Qzk1ODI0RkM3OENCQTA3QzZEQUFBQTgwRjM5MDdDMkIzQTIxNDFERDkyNUI5RDVFRjc4Qg==×tamp=2022-12-07%2014:32:08&bizContent=JTdCJTIyZG9jTm8lMjIlM0ElMjJjMGY5YzhjYTk5OTQ0MzZjYThjY2Y0MWVmMTZkMDUzYSUyMiU3RA=="; - String url = "https://apigwaws-lite.porsche-cloudservice.com/env-101/econtract/econtract/contract/api/v1/contract/download"; - String heard = "{\"apikey\":\"TulQxnZSRKeHoQfmeZzOUzGn6KpTDkDK\",\"appId\":\"100001\",\"bizContent\":\"JTdCJTIyY29udHJhY3RObyUyMiUzQSUyMjAwZDBkNmFlYzFkOTQzNGE4YjFlZjc5YzZjODcwNWFmJTIyJTdE\",\"sign\":\"M0I2NjhGRjgwNDY2RjM4MjRBMTg4RUQ0QUU0MkEzOUVEQTAxNTZCRTgwRDE3NzQ3RkQxMzZGOEE1M0FCODRGOA==\",\"signType\":\"SHA256\",\"Content-Type\":\"application/json\",\"timestamp\":\"2022-12-07 17:38:07\"} "; - Map map = JSONObject.parseObject(heard, Map.class); - FaRequestUtils.downContract(new HashMap() {{ - put("contractNo", "00d0d6aec1d9434a8b1ef79c6c8705af"); - }}, (map1, response) -> { - getFileName(response); - Header[] allHeaders = response.getAllHeaders(); - for (Header allHeader : allHeaders) { - System.out.println(allHeader); - } - return null; - }, url); - - - } } From 76beae6bfcc30a788f44935fbd8959df630991b1 Mon Sep 17 00:00:00 2001 From: "youHong.ai" <774495953@qq.com> Date: Thu, 8 Dec 2022 15:36:44 +0800 Subject: [PATCH 02/33] =?UTF-8?q?=E5=90=88=E5=B9=B6TestOrganization?= =?UTF-8?q?=E5=86=B2=E7=AA=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/test/java/youhong/ai/pcn/TestOrganization.java | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/test/java/youhong/ai/pcn/TestOrganization.java b/src/test/java/youhong/ai/pcn/TestOrganization.java index 794129e..60c6f09 100644 --- a/src/test/java/youhong/ai/pcn/TestOrganization.java +++ b/src/test/java/youhong/ai/pcn/TestOrganization.java @@ -222,9 +222,4 @@ public class TestOrganization extends BaseTest { List orgChartTree = orgChartService.getOrgChartTree(user); System.out.println(JSON.toJSONString(orgChartTree)); } - -<<<<<<< HEAD -======= - ->>>>>>> df1e8bb8c13ef138291cbf85631880cd9e5505c8 } From b7af6ffe34c9a0c201c69f8d1186a8eeaac0f4c4 Mon Sep 17 00:00:00 2001 From: "youHong.ai" <774495953@qq.com> Date: Fri, 9 Dec 2022 23:10:13 +0800 Subject: [PATCH 03/33] =?UTF-8?q?=E4=BF=9D=E6=97=B6=E6=8D=B7=E4=BA=BA?= =?UTF-8?q?=E4=BA=8B=E4=BF=9D=E5=AD=98=E6=B5=81=E7=A8=8B=E8=A7=A6=E5=8F=91?= =?UTF-8?q?=E6=B5=81=E7=A8=8B=E8=BD=AC=E6=95=B0=E6=8D=AE=E3=80=81=E4=B8=B0?= =?UTF-8?q?=E7=94=B0=E7=BA=BA=E7=BB=87=E6=B5=81=E7=A8=8B=E5=90=8D=E7=A7=B0?= =?UTF-8?q?=E5=8F=AF=E4=BB=A5=E6=A0=B9=E6=8D=AE=E5=AD=97=E6=AE=B5=E9=85=8D?= =?UTF-8?q?=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- javascript/common/Utils.js | 141 ++++++++++++++++ javascript/{youhong.ai/pcn => common}/dev.js | 64 ++++++- .../fentian/ecode/workflow_controller.js | 158 ++++++++++++++++++ .../youhong.ai/fentian/workflow_code_block.js | 29 ++++ javascript/youhong.ai/pcn/Utils.js | 40 ----- .../youhong.ai/pcn/workflow_code_block.js | 72 +++++++- .../TriggerWorkflowToModelController.java | 49 ++++++ .../mapper/TriggerWorkflowToModelMapper.java | 35 ++++ .../TriggerWorkflowToModelService.java | 58 +++++++ .../java/youhong/ai/pcn/TestOrganization.java | 54 ++++-- 10 files changed, 638 insertions(+), 62 deletions(-) create mode 100644 javascript/common/Utils.js rename javascript/{youhong.ai/pcn => common}/dev.js (58%) create mode 100644 javascript/youhong.ai/fentian/ecode/workflow_controller.js create mode 100644 javascript/youhong.ai/fentian/workflow_code_block.js delete mode 100644 javascript/youhong.ai/pcn/Utils.js create mode 100644 src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/controller/TriggerWorkflowToModelController.java create mode 100644 src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/mapper/TriggerWorkflowToModelMapper.java create mode 100644 src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/service/TriggerWorkflowToModelService.java diff --git a/javascript/common/Utils.js b/javascript/common/Utils.js new file mode 100644 index 0000000..700864e --- /dev/null +++ b/javascript/common/Utils.js @@ -0,0 +1,141 @@ +window.Utils = { + /** + * @author youhong.ai + * @desc 发起请求 + */ + request: function (url, type = "GET", data, isAsync = true, success = () => { + }, error = () => { + }, complete = () => { + }, contentType = 'application/json', beforeSend = () => { + }) { + let options = { + url, + type, + dataType: "json", + contentType, + async: isAsync, + data, + beforeSend, + success, + error, + complete, + } + if (contentType == 'application/json') { + options.data = JSON.stringify(data) + } + return $.ajax(options) + }, + + /** + * @author youhong.ai + * @desc 发起请求 + */ + api: function (requestOptions = { + url: "", + type: "GET", + data: "", + isAsync: true, + success: () => { + }, + error: () => { + }, + complete: () => { + }, + contentType: 'application/json', + beforeSend: () => { + } + }) { + let options = Object.assign({ + url: "", + type: "GET", + data: "", + isAsync: true, + success: () => { + }, + error: () => { + }, + complete: () => { + }, + contentType: 'application/json', + beforeSend: () => { + } + }, requestOptions) + return $.ajax(options) + }, + + /** + * @author youhong.ai + * @desc 获取react组件实例 + */ + findReact: function (dom, traverseUp = 0) { + const key = Object.keys(dom).find(key => { + return key.startsWith("__reactFiber$") // react 17+ + || key.startsWith("__reactInternalInstance$") + || key.startsWith("__reactEventHandlers$"); // react <17 + }); + const domFiber = dom[key]; + if (domFiber == null) return null; + // react <16 + if (domFiber._currentElement) { + let compFiber = domFiber._currentElement._owner; + for (let i = 0; i < traverseUp; i++) { + compFiber = compFiber._currentElement._owner; + } + return compFiber._instance; + } + // react 16+ + const GetCompFiber = fiber => { + let parentFiber = fiber.return; + while (typeof parentFiber.type == "string") { + parentFiber = parentFiber.return; + } + return parentFiber; + }; + let compFiber = GetCompFiber(domFiber); + for (let i = 0; i < traverseUp; i++) { + compFiber = GetCompFiber(compFiber); + } + return compFiber.stateNode; + }, + + + /** + * 转换字段名为字段ID + * @param fieldName 字段名称 + * @returns {*|string} + */ + convertNameToIdUtil: function (fieldName) { + let fieldIds = []; + if (fieldName instanceof Array) { + fieldName.forEach(item => { + fieldIds.push(Utils.convertNameObjToId(item)) + }) + return fieldIds.join(',') + } + return Utils.convertNameObjToId(fieldName) + }, + + /** + * 将字段名称转为字段id + * @param fieldObj 字段名称对象 {string|object} + * @returns {*} + */ + convertNameObjToId: function (fieldObj = {fieldName: '', table: 'main'}) { + if (typeof fieldObj === 'object') { + return WfForm.convertFieldNameToId(fieldObj.fieldName, fieldObj.table) + } + return WfForm.convertFieldNameToId(fieldObj) + }, + + /** + * 根据字段名称查询字段值 + * @param fieldName 字段名称 + * @param rowIndex 明细行下表(明细获取才传递) + * @returns {*} 字段值 + */ + getFiledValueByName: function (fieldName, rowIndex) { + return WfForm.getFieldValue(Utils.convertNameObjToId(fieldName) + rowIndex ? '_' + rowIndex : '') + } + + +} diff --git a/javascript/youhong.ai/pcn/dev.js b/javascript/common/dev.js similarity index 58% rename from javascript/youhong.ai/pcn/dev.js rename to javascript/common/dev.js index 0cdfdb8..3956a6f 100644 --- a/javascript/youhong.ai/pcn/dev.js +++ b/javascript/common/dev.js @@ -27,7 +27,7 @@ WfForm.OPER_SAVECOMPLETE = '保存后页面跳转前 KB900210501' WfForm.OPER_WITHDRAW = '撤回 KB900201101' WfForm.OPER_CLOSE = '页面关闭' -WfForm.registerCheckEvent = (type, callback) => { +WfForm.registerCheckEvent = (type, callback = (callback) = {}) => { // WfForm.registerCheckEvent(WfForm.OPER_SAVE+","+WfForm.OPER_SUBMIT,function(callback){ // //... 执行自定义逻辑 // callback(); @@ -66,7 +66,8 @@ WfForm.getFieldValue = function (fieldMark) { // var fieldvalue = WfForm.getFieldValue("field110"); } -WfForm.bindFieldChangeEvent = function (fieldMarkStr, funobj) { +WfForm.bindFieldChangeEvent = function (fieldMarkStr, funobj = (obj, id, value) => { +}) { // fieldMarkStr String 是 绑定字段标示,可多个拼接逗号隔开,例如:field110(主字段),field111_2(明细字段)…… // funobj Function 是 字段值变化触发的自定义函数,函数默认传递以下三个参数,参数1:触发字段的DOM对象,参数2:触发字段的标示(field27555等),参数3:修改后的值 // WfForm.bindFieldChangeEvent("field27555,field27556", function (obj, id, value) { @@ -74,5 +75,64 @@ WfForm.bindFieldChangeEvent = function (fieldMarkStr, funobj) { // }); } +WfForm.controlBtnDisabled = function (isDisabled) { + // isDisabled boolean 是 true:按钮全部置灰不可操作,false:恢复按钮可操作状态 + // function subimtForm(params){ + // WfForm.controlBtnDisabled(true); //操作按钮置灰 + // ... + // WfForm.controlBtnDisabled(false); + // } +} + + +WfForm.showMessage = function (msg, type, duration) { + // 参数 参数类型 必须 说明 + // msg String true 提示信息内容 + // type int false 提示类型,1(警告)、2(错误)、3(成功)、4(一般),默认为1,不同类型提示信息效果不同 + // duration Float false 多长时间自动消失,单位秒,默认为1.5秒 + // WfForm.showMessage("结束时间需大于开始时间"); //警告信息,1.5s后自动消失 + // WfForm.showMessage("运算错误", 2, 10); //错误信息,10s后消失 + +} + +WfForm.getBaseInfo = function () { +// console.log(WfForm.getBaseInfo()); //返回当前请求基础信息 +// //输出对象说明: + return { + f_weaver_belongto_userid: "5240", //用户信息 + f_weaver_belongto_usertype: "0", + formid: -2010, //表单id + isbill: "1", //新表单/老表单 + nodeid: 19275, //节点id + requestid: 4487931, //请求id + workflowid: 16084, //路径id + } +} + +WfForm.changeFieldValue = function (fieldMark, valueInfo) { + // fieldMark String 是 字段标示,格式field${字段ID}_${明细行号} + // valueInfo JSON 是 字段值信息,非浏览按钮字段格式为{value:”修改的值”};specialobj为浏览按钮信息,数组格式;showhtml属性只在单行文本类型且只读情况下生效; + //修改文本框、多行文本、选择框等字段类型 +// WfForm.changeFieldValue("field123", {value:"1.234"}); +// //修改浏览框字段的值,必须有specialobj数组结构对象 +// WfForm.changeFieldValue("field11_2", { +// value: "2,3", +// specialobj:[ +// {id:"2",name:"张三"}, +// {id:"3",name:"李四"} +// ] +// }); +// //修改check框字段(0不勾选、1勾选) +// WfForm.changeFieldValue("field123", {value:"1"}); +// //针对单行文本框字段类型,只读情况,支持显示值跟入库值不一致 +// WfForm.changeFieldValue("field123", { +// value: "入库真实值", +// specialobj: { +// showhtml: "界面显示值" +// } +// }); +} + + diff --git a/javascript/youhong.ai/fentian/ecode/workflow_controller.js b/javascript/youhong.ai/fentian/ecode/workflow_controller.js new file mode 100644 index 0000000..1279b85 --- /dev/null +++ b/javascript/youhong.ai/fentian/ecode/workflow_controller.js @@ -0,0 +1,158 @@ +/* ******************* 丰田纺织流程代码块 可选择流程中的字段配置流程标题生成规则******************* */ + +class ConfigWorkflowTitle { + + constructor(config) { + this.config = config + console.log(config) + } + + + /** + * 初始化参数 + */ + init = () => { + console.log("init") + let baseInfo = WfForm.getBaseInfo(); + if (baseInfo.workflowid != this.config.workflowId) { + return + } + let filedArr = [] + console.log("jahh") + this.config.rules.filter(item => item.type === RulesType.FIELD_VALUE + || item.type === RulesType.SELECT_VALUE + || item.type === RulesType.RADIO_VALUE).forEach(item => filedArr.push(item.fieldName)) + console.log("bind", filedArr) + this.addListenerEvent(filedArr) + } + + /** + * 修改流程标题字段值 + */ + changeWorkflowTitle = () => { + let workflowTitle = [] + this.config.rules.forEach(item => { + workflowTitle.push(item.type.run(item)) + }) + WfForm.changeFieldValue(this.config.titleFieldName === 'field-1' ? 'field-1' : + Utils.convertNameToIdUtil(this.config.titleFieldName), { + value: workflowTitle.join("") + }) + } + + /** + * 添加监听方法 + * @param fileNameArr 需要监听的字段数组 + */ + addListenerEvent = (fileNameArr) => { + console.log(Utils.convertNameToIdUtil(fileNameArr)) + WfForm.bindFieldChangeEvent(Utils.convertNameToIdUtil(fileNameArr), (obj, id, value) => { + this.changeWorkflowTitle() + }) + } + +} + +class RulesType { + // 固定值 + static FIX_STRING = { + value: 0, + run: item => item.value + } + // 字段值 + static FIELD_VALUE = { + value: 1, + run: item => Utils.getFiledValueByName(item.fieldName) + } + // 下拉框显示值 + static SELECT_VALUE = { + value: 2, + run: item => $(`div[data-fieldname='${item.fieldName}'] .ant-select-selection-selected-value`).text() + } + // 单选按钮 + static RADIO_VALUE = { + value: 3, + run: item => $(`div[data-fieldname='${item.fieldName}'] .ant-radio.ant-radio.ant-radio-checked.ant-radio-checked`).next().text() + } + // 当前日期 yyyy-mm-dd + static CURRENT_DATE = { + value: 4, + run: () => { + const date = new Date(); + let year = date.getFullYear(); + let month = date.getMonth() + 1; + let day = date.getDay(); + return year + "-" + month + "-" + day + } + } + // 当前时间 HH:mm:ss + static CURRENT_TIME = { + value: 5, + run: () => { + const date = new Date(); + let hours = date.getHours(); + let minutes = date.getMinutes(); + let seconds = date.getSeconds(); + return hours + ":" + minutes + ":" + seconds + } + } + // 当前年份 + static CURRENT_YEAR = { + value: 6, + run: () => new Date().getFullYear() + + } + // 当前月份 + static CURRENT_MONTH = { + value: 7, + run: () => new Date().getMonth() + 1 + + } + // 当前天数 + static CURRENT_DAY = { + value: 8, + run: () => new Date().getDay() + + } + // 当前小时 + static CURRENT_HOUR = { + value: 9, + run: () => new Date().getHours() + + } + // 当前分钟 + static CURRENT_MINUTE = { + value: 10, + run: () => new Date().getMinutes() + + } + // 当前秒数 + static CURRENT_SECOND = { + value: 11, + run: () => new Date().getSeconds() + } + // 当前时间戳 + static CURRENT_TIME_STAMP = { + value: 12, + run: () => new Date().getTime() + } + // 流水号 + static RANDOM = { + value: 13, + run: item => { + let result = [] + let range = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] + for (let i = 0; i < item.length; i++) { + let index = parseInt(Math.random(0, 10) * 10) + result.push(range[index]) + } + return result.join("") + } + } +} + + +window.RulesType = RulesType +window.ConfigWorkflowTitle = ConfigWorkflowTitle + +/* ******************* 可选择流程中的字段配置流程标题生成规则 end ******************* */ \ No newline at end of file diff --git a/javascript/youhong.ai/fentian/workflow_code_block.js b/javascript/youhong.ai/fentian/workflow_code_block.js new file mode 100644 index 0000000..5bb77b3 --- /dev/null +++ b/javascript/youhong.ai/fentian/workflow_code_block.js @@ -0,0 +1,29 @@ +/* ******************* youhong.ai 丰田纺织流程代码块 可选择流程中的字段配置流程标题生成规则******************* */ + +$(() => { + let workflowTitleConfig = { + workflowId: '44', + titleFieldName: 'field-1', + rules: [{ + type: RulesType.CURRENT_DATE + }, + { + type: RulesType.FIX_STRING, + value: '-' + }, { + type: RulesType.FIELD_VALUE, + fieldName: 'mc' + }, { + type: RulesType.FIELD_VALUE, + fieldName: 'sjid' + }, { + type: RulesType.RANDOM, + length: 5 + }, { + type: RulesType.RANDOM, + length: 5 + }] + } + new ConfigWorkflowTitle(workflowTitleConfig).init() +}) +/* ******************* 可选择流程中的字段配置流程标题生成规则 end ******************* */ diff --git a/javascript/youhong.ai/pcn/Utils.js b/javascript/youhong.ai/pcn/Utils.js deleted file mode 100644 index abe0dac..0000000 --- a/javascript/youhong.ai/pcn/Utils.js +++ /dev/null @@ -1,40 +0,0 @@ -$(() => { - /** - * @author youhong.ai - * @desc 获取react组件实例 - */ - function findReact(dom, traverseUp = 0) { - const key = Object.keys(dom).find(key => { - return key.startsWith("__reactFiber$") // react 17+ - || key.startsWith("__reactInternalInstance$") // react <17 - }); - const domFiber = dom[key]; - if (domFiber == null) return null; - // react <16 - if (domFiber._currentElement) { - let compFiber = domFiber._currentElement._owner; - for (let i = 0; i < traverseUp; i++) { - compFiber = compFiber._currentElement._owner; - } - return compFiber._instance; - } - // react 16+ - const GetCompFiber = fiber => { - let parentFiber = fiber.return; - while (typeof parentFiber.type == "string") { - parentFiber = parentFiber.return; - } - return parentFiber; - }; - let compFiber = GetCompFiber(domFiber); - for (let i = 0; i < traverseUp; i++) { - compFiber = GetCompFiber(compFiber); - } - return compFiber.stateNode; - } - - window.Utils = { - findReact, - } - -}) diff --git a/javascript/youhong.ai/pcn/workflow_code_block.js b/javascript/youhong.ai/pcn/workflow_code_block.js index 2e07303..2eab958 100644 --- a/javascript/youhong.ai/pcn/workflow_code_block.js +++ b/javascript/youhong.ai/pcn/workflow_code_block.js @@ -13,9 +13,13 @@ function doNotClickSubmit() { } if (submitButton.length !== 0) { let buttonReact = window.Utils.findReact(submitButton[0]) - console.log(buttonReact) - buttonReact.props.disabled = true - buttonReact.setState({disabled: true}) + let rightBtn = Utils.findReact($(".ant-menu-item.text-elli[ecid='_Route@vmt0lk_Comp@upn4fo_WeaRightMenu@1ok9r0_Item@eu37n0_li@zyccqn']")[0]) + setTimeout(() => { + buttonReact.props.disabled = true + buttonReact.setState({}) + rightBtn.props.disabled = true + rightBtn.setState({}) + }, 100) } } @@ -32,21 +36,21 @@ function allowClickSubmit() { submitButton = $("#weareqtop_9v5e5i_1670481049632 div.ant-row.wea-new-top-req div.ant-col-xs-18.ant-col-sm-18.ant-col-md-16.ant-col-lg-14 button[title='提交'],[title='Submit '],[title='Submit']") } if (submitButton.length !== 0) { + WfForm.controlBtnDisabled(false) let buttonReact = window.Utils.findReact(submitButton[0]) - console.log(buttonReact) buttonReact.props.disabled = false - buttonReact.setState({disabled: false}) + buttonReact.setState({}) } } /** * 监听qzhj字段值改变 + * @author youhong.ai * @param id 字段id * @param value 字段值 * @param obj 字段值对象 */ -function onQzhjFieldChangeValue(id, value, obj) { - console.log(value) +function onQzhjFieldChangeValue(obj, id, value) { if (value != '100') { doNotClickSubmit() } else { @@ -56,18 +60,70 @@ function onQzhjFieldChangeValue(id, value, obj) { /** * 检查qzhj字段值 + * @author youhong.ai * @param fieldId qzhj字段id */ function checkOnQzhJfiedlChangeValue(fieldId) { let value = WfForm.getFieldValue(fieldId); - onQzhjFieldChangeValue(null, value) + onQzhjFieldChangeValue(null, null, value) +} + + +/** + * 检查提交按钮是否符合条件 + * @author youhong.ai + * @param fieldId 字段id + * @returns {(function(function()=): void)|*} + */ +function checkClickSubmit(fieldId) { + return (callback = () => { + }) => { + let value = WfForm.getFieldValue(fieldId); + if (value != 100) { + WfForm.showMessage("~`~`7 目标设定的总值必须是100%,请检查并修改后提交。 " + "`~`8 The total value of target setting must be 100%,please check to submit after modification! " + "`~`9 目标设定的总值必须是100%,请检查并修改后提交。`~`~", 2, 5); + } else { + callback() + } + } +} + +/** + * 保存按钮触发流程转数据 + * @author youhong.ai + * @param callback 保存后页面跳转前回调 + */ +async function saveTriggerWorkflowToModel() { + let baseInfo = WfForm.getBaseInfo() + if (baseInfo && baseInfo.requestid != '-1') { + let result = await Utils.api({ + url: "/api/aiyh/workflow/target-setting/save-trigger", + type: "POST", + contentType: "application/json", + data: JSON.stringify({requestId: baseInfo.requestid}) + }) + if (result && result.code === 200) { + localStorage.setItem("saveTriggerWorkflowToModel", "false") + } + } +} + + +function saveAfterCallback(callback) { + localStorage.setItem("saveTriggerWorkflowToModel", "true") + callback() } $(() => { let qzhjFieldId = WfForm.convertFieldNameToId("qzhj") checkOnQzhJfiedlChangeValue(qzhjFieldId) + WfForm.registerCheckEvent(WfForm.OPER_SUBMIT, checkClickSubmit(qzhjFieldId)) + WfForm.registerCheckEvent(WfForm.OPER_SAVECOMPLETE, saveAfterCallback) WfForm.bindFieldChangeEvent(qzhjFieldId, onQzhjFieldChangeValue) + let flag = localStorage.getItem("saveTriggerWorkflowToModel") + if (flag === "true") { + saveTriggerWorkflowToModel() + } }) /* ******************* 保时捷target setting流程提交控制 end ******************* */ diff --git a/src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/controller/TriggerWorkflowToModelController.java b/src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/controller/TriggerWorkflowToModelController.java new file mode 100644 index 0000000..21df1b6 --- /dev/null +++ b/src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/controller/TriggerWorkflowToModelController.java @@ -0,0 +1,49 @@ +package com.api.youhong.ai.pcn.workflow.doworkflowtomodel.controller; + +import aiyh.utils.ApiResult; +import aiyh.utils.Util; +import com.api.youhong.ai.pcn.workflow.doworkflowtomodel.service.TriggerWorkflowToModelService; +import io.swagger.v3.oas.annotations.parameters.RequestBody; +import org.apache.log4j.Logger; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.Consumes; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import java.util.Map; + +/** + *

保存按钮流程转数据接口

+ * + *

create: 2022-12-08 18:09

+ * + * @author youHong.ai + */ + +@Path("/aiyh/workflow/target-setting") +public class TriggerWorkflowToModelController { + + private final TriggerWorkflowToModelService service = new TriggerWorkflowToModelService(); + private final Logger logger = Util.getLogger(); + + @Path("/save-trigger") + @POST + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public String saveTriggerWorkflowToModel(@RequestBody Map params, + @Context HttpServletRequest request, @Context HttpServletResponse response) { + try { + User user = HrmUserVarify.getUser(request, response); + return ApiResult.success(service.saveTriggerWorkflowToModel(params, request, user)); + } catch (Exception e) { + logger.error("save trigger workflow to mode data error ! \n" + Util.getErrString(e)); + return ApiResult.error(e.getMessage()); + } + } +} diff --git a/src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/mapper/TriggerWorkflowToModelMapper.java b/src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/mapper/TriggerWorkflowToModelMapper.java new file mode 100644 index 0000000..3694ede --- /dev/null +++ b/src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/mapper/TriggerWorkflowToModelMapper.java @@ -0,0 +1,35 @@ +package com.api.youhong.ai.pcn.workflow.doworkflowtomodel.mapper; + +import aiyh.utils.annotation.recordset.ParamMapper; +import aiyh.utils.annotation.recordset.Select; +import aiyh.utils.annotation.recordset.SqlMapper; + +import java.util.List; + +/** + *

查询数据库

+ * + *

create: 2022-12-09 22:26

+ * + * @author youHong.ai + */ + +@SqlMapper +public interface TriggerWorkflowToModelMapper { + + + /** + *

查询当前节点上的流程转数据acitonId

+ * 2022/12/9 22:29 + * ****************************************** + * + * @param nodeId 当前节点id + * @return List 流程转数据的actionId + * @author youHong.ai ****************************************** + */ + @Select("select ACTIONID from mode_workflowtomodeset where TRIGGERNODEID = #{nodeId} " + + " and isenable = 1 and workflowid = #{workflowId}") + List selectActionId(@ParamMapper("nodeId") String nodeId, + @ParamMapper("workflowId") String workflowId); +} + diff --git a/src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/service/TriggerWorkflowToModelService.java b/src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/service/TriggerWorkflowToModelService.java new file mode 100644 index 0000000..eafe3f4 --- /dev/null +++ b/src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/service/TriggerWorkflowToModelService.java @@ -0,0 +1,58 @@ +package com.api.youhong.ai.pcn.workflow.doworkflowtomodel.service; + +import aiyh.utils.Util; +import com.api.youhong.ai.pcn.workflow.doworkflowtomodel.mapper.TriggerWorkflowToModelMapper; +import weaver.formmode.interfaces.action.WorkflowToMode; +import weaver.hrm.User; +import weaver.soa.workflow.request.RequestInfo; +import weaver.soa.workflow.request.RequestService; +import weaver.workflow.request.RequestManager; + +import javax.servlet.http.HttpServletRequest; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +/** + *

+ * + *

create: 2022-12-09 10:49

+ * + * @author youHong.ai + */ + +public class TriggerWorkflowToModelService { + private final RequestService service = new RequestService(); + + private final TriggerWorkflowToModelMapper mapper = Util.getMapper(TriggerWorkflowToModelMapper.class); + + public String saveTriggerWorkflowToModel(Map params, HttpServletRequest request, User user) { + String requestId = String.valueOf(params.get("requestId")); + String nodeId = String.valueOf(params.get("nodeId")); + String isBill = String.valueOf(params.get("isBill")); + String formId = String.valueOf(params.get("formId")); + String workflowId = String.valueOf(params.get("workflowId")); + RequestInfo requestInfo = service.getRequest(Integer.parseInt(requestId)); + RequestManager requestManager = requestInfo.getRequestManager(); + requestManager.setRequest(request); + requestManager.setUser(user); + requestManager.setNodeid(Integer.parseInt(nodeId)); + requestManager.setIsbill(Integer.parseInt(isBill)); + requestManager.setFormid(Integer.parseInt(formId)); + WorkflowToMode workflowToMode = new WorkflowToMode(); + workflowToMode.setNodeid(Integer.parseInt(nodeId)); + List actionIds = mapper.selectActionId(nodeId, workflowId); + if (Objects.isNull(actionIds) || actionIds.isEmpty()) { + return "can not query actionIds;"; + } + List failAction = new ArrayList<>(); + for (Integer actionId : actionIds) { + workflowToMode.setActionid(actionId); + if ("0".equals(workflowToMode.execute(requestInfo))) { + failAction.add(actionId); + } + } + return "action execute finish! " + Util.intJoin(failAction, ",") + "execute fail!"; + } +} diff --git a/src/test/java/youhong/ai/pcn/TestOrganization.java b/src/test/java/youhong/ai/pcn/TestOrganization.java index 60c6f09..65e2711 100644 --- a/src/test/java/youhong/ai/pcn/TestOrganization.java +++ b/src/test/java/youhong/ai/pcn/TestOrganization.java @@ -16,8 +16,12 @@ import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.junit.Test; import weaver.conn.RecordSet; +import weaver.formmode.interfaces.action.WorkflowToMode; import weaver.general.GCONST; import weaver.hrm.User; +import weaver.soa.workflow.request.RequestInfo; +import weaver.soa.workflow.request.RequestService; +import weaver.workflow.request.RequestManager; import weaver.xiao.commons.config.entity.MultipartFile; import weaver.xiao.commons.config.entity.RequestMappingConfig; import weaver.xiao.commons.config.service.DealWithMapping; @@ -154,16 +158,16 @@ public class TestOrganization extends BaseTest { @Test public void testReadCsv() { String srcPath = GCONST.getSysFilePath() + "HRIS_PositionExport20221120" + ".csv"; -// String charset = "utf-8"; -// try (CSVReader csvReader = new CSVReaderBuilder(new BufferedReader(new InputStreamReader(new FileInputStream(new File(srcPath)), charset))).build()) { -// Iterator iterator = csvReader.iterator(); -// while (iterator.hasNext()) { -// Arrays.stream(iterator.next()).forEach(System.out::print); -// System.out.println(); -// } -// } catch (Exception e) { -// e.printStackTrace(); -// } + // String charset = "utf-8"; + // try (CSVReader csvReader = new CSVReaderBuilder(new BufferedReader(new InputStreamReader(new FileInputStream(new File(srcPath)), charset))).build()) { + // Iterator iterator = csvReader.iterator(); + // while (iterator.hasNext()) { + // Arrays.stream(iterator.next()).forEach(System.out::print); + // System.out.println(); + // } + // } catch (Exception e) { + // e.printStackTrace(); + // } BufferedReader reader = null; String line = null; @@ -176,8 +180,8 @@ public class TestOrganization extends BaseTest { String[] fieldsArr = null; int lineNum = 0; int insertResult = 0; -// TableInfo tableInfo = new TableInfo(); -// tableInfo.setTableName(tableName); + // TableInfo tableInfo = new TableInfo(); + // tableInfo.setTableName(tableName); try { List> listField = new ArrayList<>(); while ((line = reader.readLine()) != null) { @@ -222,4 +226,30 @@ public class TestOrganization extends BaseTest { List orgChartTree = orgChartService.getOrgChartTree(user); System.out.println(JSON.toJSONString(orgChartTree)); } + + + @Test + public void testWorkflowToMode() { + RequestService service = new RequestService(); + RequestInfo requestInfo = service.getRequest(18028); + requestInfo.setIspreadd("1"); + RequestManager requestManager = requestInfo.getRequestManager(); + requestManager.setUser(new User(1)); + requestManager.setNodeid(181); + requestManager.setIsbill(1); + requestManager.setWorkflowid(44); + requestInfo.setWorkflowid("44"); + requestManager.setFormid(-20); + // Util.actionTest(WorkflowToMode.class, 18020); + WorkflowToMode workflowToMode = new WorkflowToMode(); + workflowToMode.setIp("10.0.0.1"); + workflowToMode.setNodeid(181); + // requestManager.setNextNodeid(182); + // workflowToMode.setNodelinkid(199); + workflowToMode.setActionid(8); + String execute = workflowToMode.execute(requestInfo); + System.out.println(requestManager.getMessage()); + System.out.println(requestManager.getMessagecontent()); + System.out.println(execute); + } } From 7975f9b797bd016bc96d7a7ff59413eda825b58b Mon Sep 17 00:00:00 2001 From: "youHong.ai" <774495953@qq.com> Date: Sat, 10 Dec 2022 12:24:55 +0800 Subject: [PATCH 04/33] =?UTF-8?q?=E6=B7=BB=E5=8A=A0easyexcel=E4=BE=9D?= =?UTF-8?q?=E8=B5=96=EF=BC=8C=E7=BC=96=E5=86=99excel=E5=8D=95=E5=85=83?= =?UTF-8?q?=E6=A0=BC=E5=90=88=E5=B9=B6=E6=B5=8B=E8=AF=95=E4=BB=A3=E7=A0=81?= =?UTF-8?q?=EF=BC=8C=E5=88=86=E6=9E=90=E5=8F=AF=E8=A1=8C=E6=80=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 21 +- .../java/youhong/ai/pcn/TestOrganization.java | 203 +++++++++++++++++- 2 files changed, 216 insertions(+), 8 deletions(-) diff --git a/pom.xml b/pom.xml index 64e83b1..348d3ae 100644 --- a/pom.xml +++ b/pom.xml @@ -1,4 +1,4 @@ - 4.0.0 @@ -56,8 +56,8 @@ ${lombok.version} provided - - + + junit @@ -65,7 +65,20 @@ 4.12 - + + + + com.alibaba + easyexcel + 2.2.0-beta1 + + + org.slf4j + slf4j-api + + + + diff --git a/src/test/java/youhong/ai/pcn/TestOrganization.java b/src/test/java/youhong/ai/pcn/TestOrganization.java index 65e2711..5a4e797 100644 --- a/src/test/java/youhong/ai/pcn/TestOrganization.java +++ b/src/test/java/youhong/ai/pcn/TestOrganization.java @@ -4,6 +4,14 @@ import aiyh.utils.httpUtil.HttpMultipartFile; import aiyh.utils.httpUtil.ResponeVo; import aiyh.utils.httpUtil.util.HttpUtils; import basetest.BaseTest; +import com.alibaba.excel.EasyExcel; +import com.alibaba.excel.ExcelWriter; +import com.alibaba.excel.metadata.CellData; +import com.alibaba.excel.metadata.Head; +import com.alibaba.excel.write.handler.CellWriteHandler; +import com.alibaba.excel.write.metadata.WriteSheet; +import com.alibaba.excel.write.metadata.holder.WriteSheetHolder; +import com.alibaba.excel.write.metadata.holder.WriteTableHolder; import com.alibaba.fastjson.JSON; import com.api.youhong.ai.pcn.organization.orgchart.service.OrgChartService; import com.api.youhong.ai.pcn.organization.orgchart.vo.OrgChartNodeVo; @@ -14,6 +22,11 @@ import org.apache.http.Header; import org.apache.http.HeaderElement; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.CellType; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.util.CellRangeAddress; import org.junit.Test; import weaver.conn.RecordSet; import weaver.formmode.interfaces.action.WorkflowToMode; @@ -30,10 +43,7 @@ import weaver.youhong.ai.pcn.hrorganization.wesmat.model.Employee; import weaver.youhong.ai.pcn.hrorganization.wesmat.model.Position; import weaver.youhong.ai.pcn.hrorganization.wesmat.result.GetOrganizationResult; -import java.io.BufferedReader; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.IOException; +import java.io.*; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -252,4 +262,189 @@ public class TestOrganization extends BaseTest { System.out.println(requestManager.getMessagecontent()); System.out.println(execute); } + + + @Test + public void testEasyExcel() throws FileNotFoundException { + String tempPath = "/Users/aoey.oct.22/company/Fan_wei/test_file/muban.xlsx"; + String filePath = "/Users/aoey.oct.22/company/Fan_wei/test_file/muban1.xlsx"; + FileOutputStream outputStream = new FileOutputStream(filePath); + int[] mergeColumeIndex = {0, 1}; + int mergeRowIndex = 1; + ExcelWriter excelWriter = EasyExcel.write(outputStream) + .withTemplate(tempPath) + .registerWriteHandler(new ExcelFillCellMergeStrategy(mergeRowIndex, mergeColumeIndex)) + .build(); + WriteSheet sheet = EasyExcel.writerSheet().build(); + excelWriter.fill(buildList(), sheet); + + excelWriter.finish(); + try { + outputStream.close(); + } catch (IOException e) { + } + } + + public List> buildList() { + List> list = new ArrayList<>(); + list.add(new HashMap() {{ + put("addr", "北京"); + put("kinds", "生活用品"); + put("price", 10); + put("num", 80); + }}); + list.add(new HashMap() {{ + put("addr", "北京"); + put("kinds", "生活用品"); + put("price", 10); + put("num", 80); + }}); + list.add(new HashMap() {{ + put("addr", "北京"); + put("kinds", "电子产品"); + put("price", 10); + put("num", 80); + }}); + list.add(new HashMap() {{ + put("addr", "北京"); + put("kinds", "电子产品"); + put("price", 10); + put("num", 80); + }}); + list.add(new HashMap() {{ + put("addr", "上海"); + put("kinds", "生活用品"); + put("price", 10); + put("num", 80); + }}); + list.add(new HashMap() {{ + put("addr", "上海"); + put("kinds", "生活用品"); + put("price", 10); + put("num", 80); + }}); + list.add(new HashMap() {{ + put("addr", "上海"); + put("kinds", "电子商品"); + put("price", 10); + put("num", 80); + }}); + list.add(new HashMap() {{ + put("addr", "云南"); + put("kinds", "生活用品"); + put("price", 10); + put("num", 80); + }}); + list.add(new HashMap() {{ + put("addr", "云南"); + put("kinds", "电子铲平"); + put("price", 10); + put("num", 80); + }}); + list.add(new HashMap() {{ + put("addr", "云南"); + put("kinds", "蘑菇"); + put("price", 10); + put("num", 80); + }}); + list.add(new HashMap() {{ + put("addr", "云南"); + put("kinds", "蘑菇"); + put("price", 10); + put("num", 80); + }}); + + return list; + } } + +class ExcelFillCellMergeStrategy implements CellWriteHandler { + + /** 需要进行单元格合并的列数组 **/ + private int[] mergeColumnIndex; + /** 单元格合并从第几行开始 **/ + private int mergeRowIndex; + + public ExcelFillCellMergeStrategy() {} + + public ExcelFillCellMergeStrategy(int mergeRowIndex, int[] mergeColumnIndex) { + this.mergeRowIndex = mergeRowIndex; + this.mergeColumnIndex = mergeColumnIndex; + } + + + @Override + public void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Head head, Integer integer, Integer integer1, Boolean aBoolean) { + + } + + @Override + public void afterCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Cell cell, Head head, Integer integer, Boolean aBoolean) { + + } + + @Override + public void afterCellDataConverted(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, CellData cellData, Cell cell, Head head, Integer integer, Boolean aBoolean) { + + } + + @Override + public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, + List list, Cell cell, Head head, Integer integer, Boolean isHead) { + int curRowIndex = cell.getRowIndex(); + int curColIndex = cell.getColumnIndex(); + if (curRowIndex > mergeRowIndex) { + for (int i = 0; i < mergeColumnIndex.length; i++) { + if (curColIndex == mergeColumnIndex[i]) { + mergeWithPrevRow(writeSheetHolder, cell, curRowIndex, curColIndex); + break; + } + } + } + } + + /** + * 当前单元格向上合并 + * + * @param writeSheetHolder + * @param cell 当前单元格 + * @param curRowIndex 当前行 + * @param curColIndex 当前列 + */ + private void mergeWithPrevRow(WriteSheetHolder writeSheetHolder, Cell cell, int curRowIndex, int curColIndex) { + Object curData = + cell.getCellTypeEnum() == CellType.STRING ? cell.getStringCellValue() : cell.getNumericCellValue(); + Sheet sheet1 = cell.getSheet(); + Row row = sheet1.getRow(curRowIndex - 1); + if (row == null) { + row = sheet1.getRow(curRowIndex); + } + Cell preCell = row.getCell(curColIndex); + Object preData = + preCell.getCellTypeEnum() == CellType.STRING ? preCell.getStringCellValue() : preCell.getNumericCellValue(); + // 将当前单元格数据与上一个单元格数据比较 + Boolean dataBool = preData.equals(curData); + if (dataBool) { + Sheet sheet = writeSheetHolder.getSheet(); + List mergeRegions = sheet.getMergedRegions(); + boolean isMerged = false; + for (int i = 0; i < mergeRegions.size() && !isMerged; i++) { + CellRangeAddress cellRangeAddr = mergeRegions.get(i); + // 若上一个单元格已经被合并,则先移出原有的合并单元,再重新添加合并单元 + if (cellRangeAddr.isInRange(curRowIndex - 1, curColIndex)) { + sheet.removeMergedRegion(i); + cellRangeAddr.setLastRow(curRowIndex); + sheet.addMergedRegion(cellRangeAddr); + isMerged = true; + } + } + // 若上一个单元格未被合并,则新增合并单元 + if (!isMerged) { + CellRangeAddress cellRangeAddress = + new CellRangeAddress(curRowIndex - 1, curRowIndex, curColIndex, curColIndex); + sheet.addMergedRegion(cellRangeAddress); + } + } + } +} + From 50989aa997f62644f9eb22978a075cc9ce638b9f Mon Sep 17 00:00:00 2001 From: "youHong.ai" <774495953@qq.com> Date: Sat, 10 Dec 2022 16:45:29 +0800 Subject: [PATCH 05/33] =?UTF-8?q?=E6=B7=BB=E5=8A=A0ecode=E6=9B=B4=E5=8A=A0?= =?UTF-8?q?=E5=AE=89=E5=85=A8=E7=9A=84=E5=8F=91=E5=B8=83=E6=A0=B7=E5=BC=8F?= =?UTF-8?q?=E6=96=87=E4=BB=B6=E4=BB=A5=E5=8F=8A=E5=BC=95=E5=85=A5=E7=AC=AC?= =?UTF-8?q?=E4=B8=89=E6=96=B9=E5=BA=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/youhong/ai/pcn/TestOrganization.java | 5 +- 常用信息.md | 92 ++++++++++++++++++- 2 files changed, 92 insertions(+), 5 deletions(-) diff --git a/src/test/java/youhong/ai/pcn/TestOrganization.java b/src/test/java/youhong/ai/pcn/TestOrganization.java index 5a4e797..321c7a8 100644 --- a/src/test/java/youhong/ai/pcn/TestOrganization.java +++ b/src/test/java/youhong/ai/pcn/TestOrganization.java @@ -406,15 +406,18 @@ class ExcelFillCellMergeStrategy implements CellWriteHandler { /** * 当前单元格向上合并 * - * @param writeSheetHolder + * @param writeSheetHolder 表格数据写入处理对象 * @param cell 当前单元格 * @param curRowIndex 当前行 * @param curColIndex 当前列 */ private void mergeWithPrevRow(WriteSheetHolder writeSheetHolder, Cell cell, int curRowIndex, int curColIndex) { + // 获取当前单元格的数据 Object curData = cell.getCellTypeEnum() == CellType.STRING ? cell.getStringCellValue() : cell.getNumericCellValue(); + // 获取当前shert表 Sheet sheet1 = cell.getSheet(); + // 获取当前的行,有可能获取到空行 Row row = sheet1.getRow(curRowIndex - 1); if (row == null) { row = sheet1.getRow(curRowIndex); diff --git a/常用信息.md b/常用信息.md index e04590c..e9d0518 100644 --- a/常用信息.md +++ b/常用信息.md @@ -119,7 +119,7 @@ myComp.setState({test1: test2}); ```css /*修改url,字体文件上传到cloudstore/iconfont/xx/下,没有目录自己创建*/ -/*修改font-family,命名为其他名称,防止与系统自带的或与其他iconfont冲突*/ +/*修改font-family,命名为其他名称,防止与系统自带的或与其他iconfont冲突,并将修改后的css文件内容copy到ecode中,将文件夹发布,并且将css样式文件前置加载*/ @font-face { font-family: "cus_iconfont"; /* Project id 3789451 */ src: url('/cloudstore/iconfont/pcn/iconfont.woff2?t=1669223019749') format('woff2'), @@ -137,6 +137,90 @@ myComp.setState({test1: test2}); } ``` +**7.ecode组件样式引入(非前值加载)** +> 维护人员 youhong.ai + +在ecode开发时,需要编写css样式文件,但是偶尔会出现className与其他组件的className一样,导致样式发生覆盖或影响原来的组件的样式(前置加载会将css文件合并到init。css中,并且会全局引入,所以可能会造成样式污染) +在ecode中,找到config文件夹,找到config.js文件,可以看到的是js文件属于前置加载,我们只需要在这个js文件中将css文件动态添加到页面中就可以了 + +```js + +$(() => { + if (window.location.hash.indexOf("${appId}_organization-chart") !== -1) { + loadCssArr(['index.css']) + /* ******************** 下面两个文件为开发新页面时候,如果用户登陆超时,用于集成系统登陆弹窗的依赖和css样式文件 ******************* */ + // loadJs('/spa/portal/public/index.js') + // loadCss('/spa/portal/public/index.css') + // 使用方法,当请求结果返回的errorCode === '002',然后调用下面的方法 + // doLoginPop() + } +}) + +/** + * 加载当前appId下的css资源文件 + * @param cssArr css文件名称数组 (所有的css会被合并为index.css) + */ +function loadCssArr(cssArr) { + cssArr.forEach(item => { + let href = '/cloudstore/release/${appId}/' + item; + loadCss(href) + }) +} + + +/** + * 加载自定义的css样式文件,可以用于加载上传到resources文件加下的css文件,需要自己拼接路径 + * @param url 样式文件的路径 + */ +function loadCss(url) { + const head = document.getElementsByTagName('head')[0]; + const link = document.createElement('link'); + link.type = 'text/css'; + link.rel = 'stylesheet'; + link.href = url; + head.appendChild(link); +} + +/** + * 加载当前ecode文件夹下的js文件,一般js文件会被打包成index.js文件 + * @param jsArr js文件名数组 + */ +function loadJsArr(jsArr) { + jsArr.forEach(item => { + let src = href = '/cloudstore/release/${appId}/' + item; + loadJs(src) + }) +} + +/** + * 加载自定义js文件,可用于加载第三方js库 + * @param url js文件路径 + * @param callback 加载完成后回调方法 + */ +function loadJs(url, callback) { + let script = document.createElement('script'), + fn = callback || function () { + }; + script.type = 'text/javascript'; + //IE + if (script.readyState) { + script.onreadystatechange = function () { + if (script.readyState == 'loaded' || script.readyState == 'complete') { + script.onreadystatechange = null; + fn(); + } + }; + } else { + //其他浏览器 + script.onload = function () { + fn(); + }; + } + script.src = url; + document.getElementsByTagName('head')[0].appendChild(script); +} +``` + ### 数据库 **备份mysql数据库** @@ -418,9 +502,9 @@ from workflow_nodebase nb ```java //@Context HttpServletRequest request, @Context HttpServletResponse response User logInUser=HrmUserVarify.getUser(request,response); -// 传入id会将此人员信息带出 + // 传入id会将此人员信息带出 User user=new User(id); -// 获取人员id + // 获取人员id user.getUID(); ``` @@ -489,7 +573,7 @@ public class SendSms implements SmsService { DocImagefileToPdfUseWps toPdfUseWps=new DocImagefileToPdfUseWps(); newimagefileid=toPdfUseWps.officeDocumetnToPdfByImagefileid(docimagefileid); -//永中转PDF: + //永中转PDF: DocImagefileToPdf yozoToPdf=new DocImagefileToPdf(); newimagefileid=yozoToPdf.officeDocumetnToPdfByImagefileid(docimagefileid); ``` \ No newline at end of file From 2d4bce951376af73dec012398e4f7688ace48982 Mon Sep 17 00:00:00 2001 From: "youHong.ai" <774495953@qq.com> Date: Sun, 11 Dec 2022 16:51:14 +0800 Subject: [PATCH 06/33] =?UTF-8?q?=E5=88=86=E5=B8=83=E5=BC=8F=E9=9D=9E?= =?UTF-8?q?=E5=85=AC=E5=B9=B3=E9=94=81=E5=AE=9E=E7=8E=B0=E3=80=81=E8=B7=AF?= =?UTF-8?q?=E5=BE=84=E5=8F=82=E6=95=B0=E6=AD=A3=E5=88=99=E8=A1=A8=E8=BE=BE?= =?UTF-8?q?=E5=BC=8F=E4=BF=AE=E6=94=B9=E5=A2=9E=E5=BC=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/aiyh/utils/Util.java | 89 ++--- src/main/java/aiyh/utils/lock/LockEntity.java | 27 ++ src/main/java/aiyh/utils/lock/LockPojo.java | 33 ++ .../java/aiyh/utils/lock/LockUtilMapper.java | 129 +++++++ src/main/java/aiyh/utils/lock/LockUtils.java | 346 ++++++++++++++++++ .../config/service/DealWithMapping.java | 49 +-- .../java/youhong/ai/pcn/TestOrganization.java | 16 + 7 files changed, 623 insertions(+), 66 deletions(-) create mode 100644 src/main/java/aiyh/utils/lock/LockEntity.java create mode 100644 src/main/java/aiyh/utils/lock/LockPojo.java create mode 100644 src/main/java/aiyh/utils/lock/LockUtilMapper.java create mode 100644 src/main/java/aiyh/utils/lock/LockUtils.java diff --git a/src/main/java/aiyh/utils/Util.java b/src/main/java/aiyh/utils/Util.java index e4891bc..7aec07b 100644 --- a/src/main/java/aiyh/utils/Util.java +++ b/src/main/java/aiyh/utils/Util.java @@ -186,7 +186,7 @@ public class Util extends weaver.general.Util { String str = sqlBuilder.toString().trim(); String removeSeparator = ","; if (str.endsWith(removeSeparator)) { -// 如果以分割号结尾,则去除分割号 + // 如果以分割号结尾,则去除分割号 str = str.substring(0, str.length() - 1); } if (str.trim().startsWith(removeSeparator)) { @@ -205,7 +205,7 @@ public class Util extends weaver.general.Util { public static String removeSeparator(StringBuilder sqlBuilder, String removeSeparator) { String str = sqlBuilder.toString().trim(); if (str.endsWith(removeSeparator)) { -// 如果以分割号结尾,则去除分割号 + // 如果以分割号结尾,则去除分割号 str = str.substring(0, str.length() - 1); } if (str.trim().startsWith(removeSeparator)) { @@ -224,7 +224,7 @@ public class Util extends weaver.general.Util { public static String removeSeparator(String string, String removeSeparator) { String str = string.trim(); if (str.endsWith(removeSeparator)) { -// 如果以分割号结尾,则去除分割号 + // 如果以分割号结尾,则去除分割号 str = str.substring(0, str.length() - 1); } if (str.trim().startsWith(removeSeparator)) { @@ -1212,8 +1212,8 @@ public class Util extends weaver.general.Util { inputStream = new BufferedInputStream(new FileInputStream(path)); is = new InputStreamReader(inputStream, StandardCharsets.UTF_8); prop.load(is); -// Enumeration enumeration = prop.propertyNames(); -// 顺序读取 + // Enumeration enumeration = prop.propertyNames(); + // 顺序读取 Enumeration enumeration = prop.keys(); while (enumeration.hasMoreElements()) { String key = (String) enumeration.nextElement(); @@ -1256,7 +1256,7 @@ public class Util extends weaver.general.Util { Pattern compile = Pattern.compile(objRegex); Matcher matcher = compile.matcher(key); if (matcher.find()) { -// 只匹配前缀.key=value模式的 + // 只匹配前缀.key=value模式的 String resultKey = matcher.group("key"); preResult.put(resultKey, prop2MapPutValue(value)); } @@ -1264,7 +1264,7 @@ public class Util extends weaver.general.Util { compile = Pattern.compile(moreKey); matcher = compile.matcher(key); if (matcher.find()) { -// 匹配前缀.key1.key2=value模式的 + // 匹配前缀.key1.key2=value模式的 String objKey = matcher.group("objKey"); String prefixStr = prePrefix + "." + objKey; Map valueMap; @@ -1282,11 +1282,11 @@ public class Util extends weaver.general.Util { compile = Pattern.compile(strList); matcher = compile.matcher(key); if (matcher.find()) { -// 匹配前缀.key[0]=value模式的 + // 匹配前缀.key[0]=value模式的 String objKey = matcher.group("key"); int index = Integer.parseInt(matcher.group("index")); if (preResult.containsKey(objKey)) { -// 存在值 + // 存在值 List valueList = (List) preResult.get(objKey); if (index >= valueList.size()) { valueList.add(prop2MapPutValue(value)); @@ -1301,19 +1301,19 @@ public class Util extends weaver.general.Util { return null; } String objArray = "^(" + prePrefix + "\\.)(?(\\w+))(\\[(?([0-9])+)])\\.(?(\\S)+)$"; -// String objArray = "^("+prePrefix+"\\.)(?(\\w+))(\\[(?([0-9])+)])(\\.(?(\\S)+))+"; + // String objArray = "^("+prePrefix+"\\.)(?(\\w+))(\\[(?([0-9])+)])(\\.(?(\\S)+))+"; compile = Pattern.compile(objArray); matcher = compile.matcher(key); if (matcher.find()) { -// 匹配前缀.key[0].name=value的模式 + // 匹配前缀.key[0].name=value的模式 String arrKey = matcher.group("arrKey"); String objKey = matcher.group("objKey"); int index = Integer.parseInt(matcher.group("index")); List> mapList; if (preResult.containsKey(arrKey)) { -// 存在 + // 存在 mapList = (List>) preResult.get(arrKey); -// mapList + // mapList Map valueMap; if (index >= mapList.size()) { valueMap = new HashMap<>(); @@ -1346,7 +1346,7 @@ public class Util extends weaver.general.Util { int arrMoreIndex = Integer.parseInt(arrMoreKeyMatcher.group("index")); List arrMoreListValue; if (valueMap.containsKey(arrMoreArrKey)) { -// 存在值 + // 存在值 arrMoreListValue = (List) valueMap.get(arrMoreArrKey); if (arrMoreIndex >= arrMoreListValue.size()) { arrMoreListValue.add(prop2MapPutValue(value)); @@ -1361,11 +1361,11 @@ public class Util extends weaver.general.Util { return null; } -// 直接添加 + // 直接添加 valueMap.put(objKey, prop2MapPutValue(value)); return null; } -// 不存在 + // 不存在 mapList = new ArrayList<>(); Map valueMap = new HashMap<>(); valueMap.put(objKey, prop2MapPutValue(value)); @@ -1494,7 +1494,7 @@ public class Util extends weaver.general.Util { // private static Predicate distinctByKey(Function keyExtractor) { Map seen = new ConcurrentHashMap<>(); -// putIfAbsent添加不存在的键,返回null,如果为null表示不重复 + // putIfAbsent添加不存在的键,返回null,如果为null表示不重复 return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null; } @@ -1585,7 +1585,7 @@ public class Util extends weaver.general.Util { for (int i = 0; i < inputList.size(); i++) { T item = inputList.get(i); if (item instanceof InputStream) { -// 属于单级文件,直接压缩并返回 + // 属于单级文件,直接压缩并返回 try { zipOut.putNextEntry(new ZipEntry(base + i)); } catch (IOException e) { @@ -1618,7 +1618,7 @@ public class Util extends weaver.general.Util { if (item instanceof ListZipEntity) { ListZipEntity listZipEntity = (ListZipEntity) item; if (listZipEntity.isDirectory()) { -// 表示属于文件夹,循环添加处理文件夹 + // 表示属于文件夹,循环添加处理文件夹 handlerDirectory(listZipEntity.getFileList(), zipOut, base + listZipEntity.getDirectory() + File.separator); } else { List aInputStreams = listZipEntity.getaInputStreamList(); @@ -1649,7 +1649,7 @@ public class Util extends weaver.general.Util { int catchLen = 10 * 1024; for (ListZipEntity listZipEntity : fileList) { if (listZipEntity.isDirectory()) { -// 如果是文件夹 + // 如果是文件夹 handlerDirectory(listZipEntity.getFileList(), zipOut, base + listZipEntity.getDirectory() + File.separator); } else { List aInputStreams = listZipEntity.getaInputStreamList(); @@ -1759,8 +1759,8 @@ public class Util extends weaver.general.Util { @Deprecated public static String getDocCategorysById(String workflowId, String docFieldId) { RecordSet rs = new RecordSet(); -// rs.executeQuery("select formid from workflow_base where id = ?",workflowId); -// String formId = Util.recordeSet2Entity(rs, String.class); + // rs.executeQuery("select formid from workflow_base where id = ?",workflowId); + // String formId = Util.recordeSet2Entity(rs, String.class); String query = "select doccategory from workflow_fileupload where workflowid = ? and fieldid = ?"; rs.executeQuery(query, workflowId, docFieldId); String docCategorys = Util.null2String(Util.recordeSet2Entity(rs, String.class)); @@ -2303,7 +2303,7 @@ public class Util extends weaver.general.Util { continue; } dataMap.put(id, item); -// 判断是否属于根节点,如果是根节点,则将数据添加到树中 + // 判断是否属于根节点,如果是根节点,则将数据添加到树中 if (predicate.test(parentId)) { if (childMap.containsKey(id)) { continue; @@ -2311,29 +2311,29 @@ public class Util extends weaver.general.Util { treeList.add(item); childMap.put(id, item); } else { -// 如果不是根节点,则通过id查找到父级 + // 如果不是根节点,则通过id查找到父级 T parent = dataMap.get(parentId); if (Objects.isNull(parent)) { -// 如果父级为空,则说明他的父级还没有遍历到,需要从之后的数据进行遍历,直到找到父级为止 + // 如果父级为空,则说明他的父级还没有遍历到,需要从之后的数据进行遍历,直到找到父级为止 List list = buildTree(dataList, dataMap, childMap, index, getIdFn, getParentId, setChildFn, predicate); parent = dataMap.get(parentId); if (Objects.isNull(parent)) { -// 如果还是没有查询到父节点,则表明是顶层节点,将他添加到顶层节点中 + // 如果还是没有查询到父节点,则表明是顶层节点,将他添加到顶层节点中 treeList.add(item); } else { -// 如果找到了父节点,则将自己挂到父节点上 + // 如果找到了父节点,则将自己挂到父节点上 if (childMap.containsKey(id)) { continue; } setChildFn.accept(parent, item); childMap.put(id, item); } -// 如果查找的list不为空并且有值,那就说明属于根节点 + // 如果查找的list不为空并且有值,那就说明属于根节点 if (list != null && list.size() > 0) { treeList.addAll(list); } } else { -// 如果找到了父节点,则将自己挂到父节点上 + // 如果找到了父节点,则将自己挂到父节点上 if (childMap.containsKey(id)) { continue; } @@ -2375,7 +2375,7 @@ public class Util extends weaver.general.Util { continue; } dataMap.put(id, item); -// 判断是否属于根节点,如果是根节点,则将数据添加到树中 + // 判断是否属于根节点,如果是根节点,则将数据添加到树中 if (predicate.test(parentId)) { if (childMap.containsKey(id)) { continue; @@ -2383,17 +2383,17 @@ public class Util extends weaver.general.Util { treeList.add(item); childMap.put(id, item); } else { -// 如果不是根节点,则通过id查找到父级 + // 如果不是根节点,则通过id查找到父级 T parent = dataMap.get(parentId); if (Objects.isNull(parent)) { -// 如果父级为空,则说明他的父级还没有遍历到,需要从之后的数据进行遍历,直到找到父级为止 + // 如果父级为空,则说明他的父级还没有遍历到,需要从之后的数据进行遍历,直到找到父级为止 List list = buildTree(dataList, dataMap, childMap, index, getIdFn, getParentId, getChildFn, setChildFn, predicate); parent = dataMap.get(parentId); if (Objects.isNull(parent)) { -// 如果还是没有查询到父节点,则表明是顶层节点,将他添加到顶层节点中 + // 如果还是没有查询到父节点,则表明是顶层节点,将他添加到顶层节点中 treeList.add(item); } else { -// 如果找到了父节点,则将自己挂到父节点上 + // 如果找到了父节点,则将自己挂到父节点上 if (childMap.containsKey(id)) { continue; } @@ -2402,12 +2402,12 @@ public class Util extends weaver.general.Util { setChildFn.accept(parent, childList); childMap.put(id, item); } -// 如果查找的list不为空并且有值,那就说明属于根节点 + // 如果查找的list不为空并且有值,那就说明属于根节点 if (list != null && list.size() > 0) { treeList.addAll(list); } } else { -// 如果找到了父节点,则将自己挂到父节点上 + // 如果找到了父节点,则将自己挂到父节点上 if (childMap.containsKey(id)) { continue; } @@ -2468,7 +2468,7 @@ public class Util extends weaver.general.Util { throw new RuntimeException("invoke method err, cant not invoke method set" + name.substring(0, 1).toUpperCase() + name.substring(1)); } } -// TODO 复制bean + // TODO 复制bean return target; } @@ -3229,7 +3229,7 @@ public class Util extends weaver.general.Util { action = cronJobClass.newInstance(); if (declaredFields.length > 0) { for (Field declaredField : declaredFields) { -// 必填参数验证 + // 必填参数验证 boolean hasRequiredMark = declaredField.isAnnotationPresent(RequiredMark.class); String name = declaredField.getName(); String setMethodName = getSetMethodName(name); @@ -3310,7 +3310,7 @@ public class Util extends weaver.general.Util { action = actionClass.newInstance(); if (declaredFields.length > 0) { for (Field declaredField : declaredFields) { -// 必填参数验证 + // 必填参数验证 boolean hasRequiredMark = declaredField.isAnnotationPresent(RequiredMark.class); String name = declaredField.getName(); String setMethodName = getSetMethodName(name); @@ -3458,10 +3458,12 @@ public class Util extends weaver.general.Util { value:#sql{select workcode from hrmresource where id = #{main.zd1} and test = #{h-hah} and a in (${hrmids})} key:hah value:haode*/ -// 最终通过反射调用weaver.aiyh_jitu.pushdata.service.GetAssignProcessorProcessorImpl类,将参数传递给这个类, - // String pattern = "&?(?([#.\\w\\u4E00-\\u9FA5]+))=(?((#(\\{|sql\\{))?([()\\-$#={ }.\\w\\u4E00-\\u9FA5?]+)?}?))&?"; + // 最终通过反射调用weaver.aiyh_jitu.pushdata.service.GetAssignProcessorProcessorImpl类,将参数传递给这个类, + //String pattern = "&?(?([#.\\w\\u4E00-\\u9FA5]+))=" + + // "(?(`([\\s():/\\t\\-&*'?$#={ }.\\w\\u4E00-\\u9FA5]*)`|" + + // "((#(\\{|sql\\{))?([():/\\-$#={ }.\\w\\u4E00-\\u9FA5?]+)?}?)))&?"; String pattern = "&?(?([#.\\w\\u4E00-\\u9FA5]+))=" + - "(?((`([():/\\-&?$#={ }.\\w\\u4E00-\\u9FA5?]*)`)|" + + "(?(`([^`]*)`|" + "((#(\\{|sql\\{))?([():/\\-$#={ }.\\w\\u4E00-\\u9FA5?]+)?}?)))&?"; Pattern compile = Pattern.compile(pattern); Matcher matcher = compile.matcher(paramStr); @@ -3470,6 +3472,9 @@ public class Util extends weaver.general.Util { while (matcher.find()) { String key = matcher.group("key"); String paramValue = matcher.group("value"); + if (paramValue.startsWith("`") && paramValue.endsWith("`")) { + paramValue = paramValue.substring(1, paramValue.length() - 1); + } pathParamMap.put(key, paramValue); } return pathParamMap; diff --git a/src/main/java/aiyh/utils/lock/LockEntity.java b/src/main/java/aiyh/utils/lock/LockEntity.java new file mode 100644 index 0000000..ba8f225 --- /dev/null +++ b/src/main/java/aiyh/utils/lock/LockEntity.java @@ -0,0 +1,27 @@ +package aiyh.utils.lock; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** + *

锁参数信息

+ * + *

create: 2022-12-11 02:07

+ * + * @author youHong.ai + */ + +@Getter +@Setter +@ToString +public class LockEntity { + /** 锁住次数 */ + private Integer times; + + /** 锁标识 */ + private Thread lockMark; + + /** 过期时间 */ + private Long expirationTime; +} diff --git a/src/main/java/aiyh/utils/lock/LockPojo.java b/src/main/java/aiyh/utils/lock/LockPojo.java new file mode 100644 index 0000000..d1cc18b --- /dev/null +++ b/src/main/java/aiyh/utils/lock/LockPojo.java @@ -0,0 +1,33 @@ +package aiyh.utils.lock; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** + *

锁对应数据库的实体类

+ * + *

create: 2022-12-11 00:24

+ * + * @author youHong.ai + */ + +@Setter +@Getter +@ToString +public class LockPojo { + /** + * 数据库id + */ + private Integer id; + + /** 过期时间 */ + private Long expirationTime; + + /** 锁的键 */ + private String lockName; + + /** 锁状态 */ + private Integer lockStatus; + +} diff --git a/src/main/java/aiyh/utils/lock/LockUtilMapper.java b/src/main/java/aiyh/utils/lock/LockUtilMapper.java new file mode 100644 index 0000000..3cd6a86 --- /dev/null +++ b/src/main/java/aiyh/utils/lock/LockUtilMapper.java @@ -0,0 +1,129 @@ +package aiyh.utils.lock; + +import aiyh.utils.annotation.recordset.ParamMapper; +import aiyh.utils.annotation.recordset.Select; +import aiyh.utils.annotation.recordset.SqlMapper; +import aiyh.utils.annotation.recordset.Update; + +/** + *

分布式锁数据库查询

+ * + *

create: 2022-12-11 00:22

+ * + * @author youHong.ai + */ + +@SqlMapper +public interface LockUtilMapper { + + + /** + *

根据锁名称获取锁状态

+ * 2022/12/11 00:37 + * ****************************************** + * + * @param lockKey 锁名称 + * @return LockPojo 锁参数对象 + * @author youHong.ai ****************************************** + */ + @Select("select id, lock_name, lock_status, expiration_time " + + "from uf_cus_lock " + + "where lock_name = #{lockKey}") + LockPojo selectLock(@ParamMapper("lockKey") String lockKey); + + + /** + *

根据锁名称释放锁资源

+ * 2022/12/11 00:46 + * ****************************************** + * + * @param id 锁id + * @return boolean 是否更新成功 + * @author youHong.ai ****************************************** + */ + @Update("update uf_cus_lock " + + "set lock_status = 0 " + + "where id = #{id} " + + " and lock_status = 1") + boolean unLock(@ParamMapper("id") Integer id); + + /** + *

根据锁名称释放锁资源

+ * 2022/12/11 00:46 + * ****************************************** + * + * @param lockKey 锁名称 + * @return boolean 是否更新成功 + * @author youHong.ai ****************************************** + */ + @Update("update uf_cus_lock " + + "set lock_status = 0 " + + "where lock_name = #{lockKey} " + + " and lock_status = 1") + boolean unLock(@ParamMapper("lockKey") String lockKey); + + + /** + *

更新锁状态,锁住资源

+ * 2022/12/11 00:49 + * ****************************************** + * + * @param id 数据id + * @param lockKey 锁名称 + * @param time 过期时间 + * @return boolean 是否成功锁住资源 + * @author youHong.ai ****************************************** + */ + @Update("update uf_cus_lock " + + "set lock_name = #{lockKey}," + + " expiration_time = #{time}," + + " lock_status = 1 " + + "where id = #{id} " + + " and (lock_status = 0 or expiration_time < #{time})") + boolean lock(@ParamMapper("id") Integer id, + @ParamMapper("lockKey") String lockKey, + @ParamMapper("time") Long time); + + + /** + *

更新锁过期时间,续期

+ * 2022/12/11 00:52 + * ****************************************** + * + * @param lockKey 锁名称 + * @param time 过期时间 + * @return boolean 是否更新成功 + * @author youHong.ai ****************************************** + */ + @Update("update uf_cus_lock " + + "set expiration_time = #{time} " + + "where lock_name = #{lockKey} " + + " and lock_status = 1") + boolean updateLockTime(@ParamMapper("lockKey") String lockKey, + @ParamMapper("time") Long time); + + + /** + *

对过期锁重新设置锁

+ * 2022/12/11 15:02 + * ****************************************** + * + * @param id 锁id + * @param lockKey 锁名称 + * @param time 锁过期时间 + * @param expirationTime 上一个锁的过期时间 + * @return boolean 是否重新上锁成功 + * @author youHong.ai ****************************************** + */ + @Update("update uf_cus_lock " + + "set lock_name = #{lockKey}, " + + " expiration_time = #{time}, " + + " lock_status = 1 " + + "where id = #{id} " + + " and lock_status = 1 " + + " and expiration_time = #{expirationTime}") + boolean reLock(@ParamMapper("id") Integer id, + @ParamMapper("lockKey") String lockKey, + @ParamMapper("time") Long time, + @ParamMapper("expirationTime") Long expirationTime); +} diff --git a/src/main/java/aiyh/utils/lock/LockUtils.java b/src/main/java/aiyh/utils/lock/LockUtils.java new file mode 100644 index 0000000..487189a --- /dev/null +++ b/src/main/java/aiyh/utils/lock/LockUtils.java @@ -0,0 +1,346 @@ +package aiyh.utils.lock; + +import aiyh.utils.Util; +import aiyh.utils.excention.CustomerException; +import cn.hutool.core.thread.ThreadUtil; +import ebu7common.youhong.ai.bean.Builder; + +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; + +/** + *

分布式锁

+ * + *

create: 2022-12-11 00:21

+ * + * @author youHong.ai + */ + +public class LockUtils { + + private static final LockUtilMapper mapper = Util.getMapper(LockUtilMapper.class); + + private static final Map LOCK_MAP = new HashMap<>(); + + /** 默认过期时间 10s */ + private static final Long DEFAULT_OVERDUE_TIME = 1_000 * 10L; + + private static final String UF_CUS_LOCK = "uf_cus_lock"; + + /** + *

上锁

+ * 2022/12/11 15:40 + * ****************************************** + * + * @param lockName 锁名称 + * @param reentrant 是否可重入 + * @return boolean 是否抢占成功 + * @author youHong.ai ****************************************** + */ + public static boolean lock(String lockName, boolean reentrant) { + return lock(lockName, DEFAULT_OVERDUE_TIME, reentrant); + } + + + /** + *

上锁

+ * 2022/12/11 15:40 + * ****************************************** + * + * @param lockName 锁名称 + * @param overdueTime 超时时间 + * @param reentrant 是否可重入 + * @return boolean 是否抢占成功 + * @author youHong.ai ****************************************** + */ + public static boolean lock(String lockName, Long overdueTime, boolean reentrant) { + LockPojo lockPojo = mapper.selectLock(lockName); + if (Objects.isNull(lockPojo) || lockPojo.getId() <= 0) { + return insertLock(lockName, overdueTime); + } else { + // 存在当前的锁的锁名称 + if (lockPojo.getLockStatus() == 1) { + // 锁处于锁定状态 + return onLock(lockName, overdueTime, reentrant, lockPojo); + } else { + // 处于未锁定状态开始对资源上锁 + boolean lock = mapper.lock(lockPojo.getId(), lockName, overdueTime); + if (lock) { + // 锁定成功 + LOCK_MAP.put(lockName, + Builder.builder(LockEntity::new) + .with(LockEntity::setTimes, 1) + .with(LockEntity::setLockMark, Thread.currentThread()) + .with(LockEntity::setExpirationTime, overdueTime) + .build()); + return true; + } else { + // 抢占锁失败 + lockPojo = mapper.selectLock(lockName); + return retryGetLock(lockName, overdueTime, lockPojo); + } + } + } + } + + /** + *

处于锁状态

+ * 2022/12/11 12:23 + * ****************************************** + * + * @param lockName 锁名称 + * @param overdueTime 锁超时时间 + * @param reentrant 是否可重入锁 + * @param lockPojo 锁信息对象 + * @return boolean 是否获取锁成功 + * @author youHong.ai ****************************************** + */ + private static boolean onLock(String lockName, Long overdueTime, boolean reentrant, LockPojo lockPojo) { + Long time = lockPojo.getExpirationTime(); + if (time > System.currentTimeMillis()) { + // 锁过期了 如果要使锁生效就将日期加长 + return lockExpiration(lockName, overdueTime, lockPojo); + } else { + //锁没有过期 + return inLockTime(lockName, overdueTime, reentrant); + } + } + + /** + *

锁未过期

+ * 2022/12/11 12:24 + * ****************************************** + * + * @param lockName 锁名称 + * @param overdueTime 锁过期时间 + * @param reentrant 是否可重入 + * @return boolean 是否成功获取锁 + * @author youHong.ai ****************************************** + */ + private static boolean inLockTime(String lockName, Long overdueTime, boolean reentrant) { + //判断是否存在本地锁对象中 + LockPojo lockPojo = mapper.selectLock(lockName); + if (!LOCK_MAP.containsKey(lockName)) { + // 不是本地锁,不支持可重入,使线程进入等待状态 + int n = 0; + return retryGetLock(lockName, overdueTime, lockPojo); + } + // 是本地锁 + return getLock(lockName, overdueTime, reentrant); + } + + /** + *

尝试抢占资源锁

+ * 2022/12/11 15:34 + * ****************************************** + * + * @param lockName 锁名称 + * @param overdueTime 锁过期时间 + * @param lockPojo 锁参数对象 + * @return boolean 是否抢占锁成功 + * @author youHong.ai ****************************************** + */ + private static boolean retryGetLock(String lockName, Long overdueTime, LockPojo lockPojo) { + while (lockPojo.getExpirationTime() > System.currentTimeMillis()) { + // 锁还没过期,使线程休眠 + long l = lockPojo.getExpirationTime() - System.currentTimeMillis(); + if (l > 10) { + ThreadUtil.safeSleep(l - 10L); + } + // 尝试获取锁 + lockExpiration(lockName, overdueTime + l, lockPojo); + } + return true; + } + + /** + *

获取锁

+ * 2022/12/11 13:57 + * ****************************************** + * + * @param lockName 锁名称 + * @param overdueTime 超时时间 + * @param reentrant 是否可重入 + * @return boolean 锁是否获取成功 + * @author youHong.ai ****************************************** + */ + private static boolean getLock(String lockName, Long overdueTime, boolean reentrant) { + if (reentrant) { + LockEntity lockEntity = LOCK_MAP.get(lockName); + lockEntity.setTimes(lockEntity.getTimes() + 1); + } else { + LockPojo lockPojo = mapper.selectLock(lockName); + retryGetLock(lockName, overdueTime, lockPojo); + } + return true; + } + + /** + *

锁过期

+ * 2022/12/11 12:25 + * ****************************************** + * + * @param lockName 锁名称 + * @param overdueTime 锁过期时间 + * @return boolean 是否成功获取锁 + * @author youHong.ai ****************************************** + */ + private static boolean lockExpiration(String lockName, Long overdueTime, LockPojo lockPojo) { + boolean lock = mapper.reLock(lockPojo.getId(), lockName, overdueTime, lockPojo.getExpirationTime()); + if (lock) { + //更新锁状态成功 + LockEntity lockEntity = Builder.builder(LockEntity::new) + .with(LockEntity::setTimes, 1) + .with(LockEntity::setLockMark, Thread.currentThread()) + .with(LockEntity::setExpirationTime, overdueTime) + .build(); + LOCK_MAP.put(lockName, lockEntity); + return true; + } else { + // 更新失败,可能是其他服务器抢先获得了锁 + LockPojo newLockPojo = mapper.selectLock(lockName); + if (Objects.isNull(newLockPojo)) { + // 锁被释放了 + boolean isLock = insertLock(lockName, overdueTime); + if (!isLock) { + throw new CustomerException("can not getLock!"); + } + return true; + } + if (newLockPojo.getExpirationTime() > lockPojo.getExpirationTime()) { + // 锁被其他机器抢占 + return retryGetLock(lockName, overdueTime, newLockPojo); + } + } + return false; + } + + /** + *

新增锁记录

+ * 2022/12/11 12:25 + * ****************************************** + * + * @param lockName 锁名称 + * @param overdueTime 锁过期时间 + * @return boolean 是否是可重入锁 + * @author youHong.ai ****************************************** + */ + private static boolean insertLock(String lockName, Long overdueTime) { + // 没有锁需要新增一条锁记录 + String modeId = Util.getModeIdByTableName(UF_CUS_LOCK); + int dataId = Util.getModeDataId(UF_CUS_LOCK, Integer.parseInt(modeId), 1); + long currentTime = System.currentTimeMillis(); + Long expirationTime = currentTime + overdueTime; + boolean lock = mapper.lock(dataId, lockName, expirationTime); + if (lock) { + // 锁成功 + LockEntity lockEntity = Builder.builder(LockEntity::new) + .with(LockEntity::setTimes, 1) + .with(LockEntity::setLockMark, Thread.currentThread()) + .with(LockEntity::setExpirationTime, overdueTime) + .build(); + LOCK_MAP.put(lockName, lockEntity); + } else { + // 锁失败 + retryLock(dataId, lockName, expirationTime, 0); + } + return true; + } + + + /** + *

重试锁

+ * 2022/12/11 01:39 + * ****************************************** + * + * @param dataId 数据id + * @param lockName 锁名称 + * @param expirationTime 过期时间 + * @param n 重试次数 + * @author youHong.ai ****************************************** + */ + private static void retryLock(int dataId, String lockName, Long expirationTime, int n) { + if (n > 5) { + throw new CustomerException("get lock error! 5 failed attempts to update the database!"); + } + ThreadUtil.safeSleep((n + 1) * 500); + boolean lock = mapper.lock(dataId, lockName, expirationTime + (n + 1) * 500L); + if (lock) { + // 锁成功 + LockEntity lockEntity = Builder.builder(LockEntity::new) + .with(LockEntity::setTimes, 1) + .with(LockEntity::setLockMark, Thread.currentThread()) + .with(LockEntity::setExpirationTime, expirationTime + (1 + n) * 500L) + .build(); + LOCK_MAP.put(lockName, lockEntity); + } else { + // 锁失败 + retryLock(dataId, lockName, expirationTime, n + 1); + } + } + + + /** + *

锁续期

+ * 2022/12/11 15:49 + * ****************************************** + * + * @param lockKey 锁名字 + * @param expirationTime 锁过期时间 + * @return boolean 是否续期成功 + * @author youHong.ai ****************************************** + */ + public boolean updateLockTime(String lockKey, Long expirationTime) { + if (!mapper.updateLockTime(lockKey, expirationTime)) { + // 更新失败 + int n = 0; + do { + if (n++ > 5) { + return false; + } + } while (!mapper.updateLockTime(lockKey, expirationTime)); + } + if (LOCK_MAP.containsKey(lockKey)) { + // 存在本地锁,更新锁信息 + LockEntity lockEntity = LOCK_MAP.get(lockKey); + lockEntity.setExpirationTime(expirationTime); + } + return true; + } + + + /** + *

释放锁

+ * 2022/12/11 15:56 + * ****************************************** + * + * @param lockName 锁名称 + * @author youHong.ai ****************************************** + */ + public void unLock(String lockName) { + if (LOCK_MAP.containsKey(lockName)) { + // 存在本地锁 + LockEntity lockEntity = LOCK_MAP.get(lockName); + if (!lockEntity.getLockMark().equals(Thread.currentThread())) { + // 并非当前上锁的线程在释放锁 + return; + } + Integer times = lockEntity.getTimes(); + if (times - 1 == 0) { + boolean unlock = mapper.unLock(lockName); + if (!unlock) { + int n = 0; + do { + if (n++ > 5) { + throw new CustomerException("can not unLock!Failed to release the lock after five attempts!"); + } + } while (!mapper.unLock(lockName)); // 释放锁失败 + } + return; + } + lockEntity.setTimes(lockEntity.getTimes() - 1); + } + } +} + diff --git a/src/main/java/weaver/xiao/commons/config/service/DealWithMapping.java b/src/main/java/weaver/xiao/commons/config/service/DealWithMapping.java index 0217882..14c5946 100644 --- a/src/main/java/weaver/xiao/commons/config/service/DealWithMapping.java +++ b/src/main/java/weaver/xiao/commons/config/service/DealWithMapping.java @@ -380,7 +380,7 @@ public class DealWithMapping extends ToolUtil { List tempList = new ArrayList(); for (Object o : list) { if (o instanceof Map) { -// map处理 key->1的类型 + // map处理 key->1的类型 Map mapItem = (Map) o; Map> tempMap = new HashMap<>(8); for (Map.Entry entry : mapItem.entrySet()) { @@ -426,11 +426,11 @@ public class DealWithMapping extends ToolUtil { } } } -// tempList.addAll(list); + // tempList.addAll(list); requestParam.put(paramName, tempList); -// if (!tempList.isEmpty()) { -// requestParam.put(paramName, tempList); -// } + // if (!tempList.isEmpty()) { + // requestParam.put(paramName, tempList); + // } } else { Object value = this.normalValueDeal(mainMap, detailMap, mappingDetail); if (!Objects.isNull(value)) { @@ -471,7 +471,7 @@ public class DealWithMapping extends ToolUtil { List tempList = new ArrayList(); for (Object o : list) { if (o instanceof Map) { -// map处理 + // map处理 Map mapItem = (Map) o; Map> tempMap = new HashMap<>(8); for (Map.Entry entry : mapItem.entrySet()) { @@ -517,11 +517,11 @@ public class DealWithMapping extends ToolUtil { } } } -// tempList.addAll(list); + // tempList.addAll(list); requestParam.put(paramName, tempList); -// if (!tempList.isEmpty()) { -// requestParam.put(paramName, tempList); -// } + // if (!tempList.isEmpty()) { + // requestParam.put(paramName, tempList); + // } } else { Object value = this.normalValueDeal(mainMap, detailMap, relationRs, mappingDetail); if (!Objects.isNull(value)) { @@ -618,7 +618,7 @@ public class DealWithMapping extends ToolUtil { } else { value = Util.null2String(mainMap.get("id")); } -// value = Util.null2String(main.getString("id")); + // value = Util.null2String(main.getString("id")); } break; // 随机数 @@ -657,7 +657,7 @@ public class DealWithMapping extends ToolUtil { } return null; } -// 自定义接口 + // 自定义接口 case CUS_INTERFACE: { if (null == valueContext || valueContext.length() == 0) { } else { @@ -943,7 +943,7 @@ public class DealWithMapping extends ToolUtil { } return null; } -// 自定义接口 + // 自定义接口 case CUS_INTERFACE: { if (null == valueContext || valueContext.length() == 0) { } else { @@ -1124,10 +1124,10 @@ public class DealWithMapping extends ToolUtil { list.add(o); } } -// for (MappingDetail mappingDetail : childList) { -// Object o = this.normalValueDeal(recordSet, null, mappingDetail); -// list.add(o); -// } + // for (MappingDetail mappingDetail : childList) { + // Object o = this.normalValueDeal(recordSet, null, mappingDetail); + // list.add(o); + // } } else if ("2".equals(childSource)) { // 自定义接口 Map pathParamMap = new HashMap<>(8); @@ -1203,10 +1203,10 @@ public class DealWithMapping extends ToolUtil { list.add(o); } } -// for (MappingDetail mappingDetail : childList) { -// Object o = this.normalValueDeal(recordSet, null, mappingDetail); -// list.add(o); -// } + // for (MappingDetail mappingDetail : childList) { + // Object o = this.normalValueDeal(recordSet, null, mappingDetail); + // list.add(o); + // } } else if ("2".equals(childSource)) { // 自定义接口 Map pathParamMap = new HashMap<>(8); @@ -1241,8 +1241,9 @@ public class DealWithMapping extends ToolUtil { /** *

请求结果赋值到配置信息中

+ * * @param responseMappingList 回写信息配置列表 - * @param requestRes 请求结果 + * @param requestRes 请求结果 * @return 要插入的信息 */ public Map> dealResponse(List responseMappingList, Map requestRes) { @@ -1374,9 +1375,9 @@ public class DealWithMapping extends ToolUtil { value:#sql{select workcode from hrmresource where id = #{main.zd1} and test = #{h-hah} and a in (${hrmids})} key:hah value:haode*/ -// 最终通过反射调用weaver.aiyh_jitu.pushdata.service.GetAssignProcessorProcessorImpl类,将参数传递给这个类, 使用``包裹的字符串会被解析为一个字符串 + // 最终通过反射调用weaver.aiyh_jitu.pushdata.service.GetAssignProcessorProcessorImpl类,将参数传递给这个类, 使用``包裹的字符串会被解析为一个字符串 String pattern = "&?(?([#.\\w\\u4E00-\\u9FA5]+))=" + - "(?((`([():/\\-&$?#={ }.\\w\\u4E00-\\u9FA5?]*)`)|" + + "(?((`([^`]*)`)|" + "((#(\\{|sql\\{))?([():/\\-$#={ }.\\w\\u4E00-\\u9FA5?]+)?}?)))&?"; Pattern compile = Pattern.compile(pattern); Matcher matcher = compile.matcher(paramStr); diff --git a/src/test/java/youhong/ai/pcn/TestOrganization.java b/src/test/java/youhong/ai/pcn/TestOrganization.java index 321c7a8..cae7065 100644 --- a/src/test/java/youhong/ai/pcn/TestOrganization.java +++ b/src/test/java/youhong/ai/pcn/TestOrganization.java @@ -1,5 +1,6 @@ package youhong.ai.pcn; +import aiyh.utils.Util; import aiyh.utils.httpUtil.HttpMultipartFile; import aiyh.utils.httpUtil.ResponeVo; import aiyh.utils.httpUtil.util.HttpUtils; @@ -108,6 +109,21 @@ public class TestOrganization extends BaseTest { @Test public void testStaticLog() { log.info("哈哈哈好的方式"); + String testStr = "slflas.fasjdflaf.fasdf?hah=liuliu&cus=`select? * fr$%&#@!)(<>?/\\{}「」【【】[]~、asfom table where id = '' and teset = #{name}`&niua=卧槽"; + Map stringStringMap = Util.parseCusInterfacePathParam(testStr); + System.out.println(JSON.toJSONString(stringStringMap)); + //String pattern = "&?(?([#.\\w\\u4E00-\\u9FA5]+))=" + + // "(?(`([():/\\-&$#='*{ }.\\w\\u4E00-\\u9FA5?]*)`|((#(\\{|sql\\{))?([():/\\-$#={ }.\\w\\u4E00-\\u9FA5?]+)?}?)))&?"; + //String pattern = "=`(?(([\\u4E00-\\u9FA5\\w.'#=?${ }*])*))`"; + //String pattern = "&?(?([#.\\w\\u4E00-\\u9FA5]+))=(?(`([():/\\-&?%#\\t\\n='{ }.\\w\\u4E00-\\u9FA5]*)*`))"; + //Pattern compile = Pattern.compile(pattern); + //Matcher matcher = compile.matcher(testStr); + //while (matcher.find()) { + // String key = matcher.group("key"); + // System.out.println(key); + //String paramValue = matcher.group("value"); + //System.out.println(paramValue); + //} } From 8e8b6376e6c13242e117f3fe135474e5800cbf41 Mon Sep 17 00:00:00 2001 From: "youHong.ai" <774495953@qq.com> Date: Sun, 11 Dec 2022 22:57:35 +0800 Subject: [PATCH 07/33] =?UTF-8?q?=E4=BF=AE=E6=94=B9cus=E6=97=A5=E5=BF=97?= =?UTF-8?q?=E8=BE=93=E5=87=BA=E8=8C=83=E5=9B=B4=EF=BC=8C=E5=88=86=E5=B8=83?= =?UTF-8?q?=E5=BC=8F=E9=94=81=E6=96=B0=E5=A2=9E=E6=B7=BB=E5=8A=A0=E6=96=B0?= =?UTF-8?q?=E5=A2=9E=E5=A4=B1=E8=B4=A5=E5=8F=AF=E8=83=BD=E6=98=AF=E5=85=B6?= =?UTF-8?q?=E4=BB=96=E6=9C=8D=E5=8A=A1=E5=99=A8=E6=8A=A2=E5=8D=A0=E7=9A=84?= =?UTF-8?q?=E9=80=BB=E8=BE=91=E6=8E=A7=E5=88=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/aiyh/utils/Util.java | 2 ++ src/main/java/aiyh/utils/lock/LockUtils.java | 10 ++++++++-- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/src/main/java/aiyh/utils/Util.java b/src/main/java/aiyh/utils/Util.java index 7aec07b..d015f2b 100644 --- a/src/main/java/aiyh/utils/Util.java +++ b/src/main/java/aiyh/utils/Util.java @@ -2080,6 +2080,7 @@ public class Util extends weaver.general.Util { appender.setAppend(true); appender.activateOptions(); log.addAppender(appender); + log.setAdditivity(false); log.setLevel(Level.INFO); /* boolean enableDebug = false; @@ -2127,6 +2128,7 @@ public class Util extends weaver.general.Util { appender.setAppend(true); appender.activateOptions(); cusLog.addAppender(appender); + cusLog.setAdditivity(false); /* boolean enableDebug = false; try { diff --git a/src/main/java/aiyh/utils/lock/LockUtils.java b/src/main/java/aiyh/utils/lock/LockUtils.java index 487189a..c06d8e9 100644 --- a/src/main/java/aiyh/utils/lock/LockUtils.java +++ b/src/main/java/aiyh/utils/lock/LockUtils.java @@ -242,8 +242,14 @@ public class LockUtils { .build(); LOCK_MAP.put(lockName, lockEntity); } else { - // 锁失败 - retryLock(dataId, lockName, expirationTime, 0); + LockPojo lockPojo = mapper.selectLock(lockName); + if (Objects.isNull(lockPojo)) { + // 锁失败 + retryLock(dataId, lockName, expirationTime, 0); + } else { + // 其他服务器抢占了锁资源 + return retryGetLock(lockName, overdueTime, lockPojo); + } } return true; } From ffd51db3ff6e14a372f0dcb494ae8313cbc7a336 Mon Sep 17 00:00:00 2001 From: "youHong.ai" <774495953@qq.com> Date: Sun, 11 Dec 2022 23:10:32 +0800 Subject: [PATCH 08/33] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=9C=AC=E5=9C=B0?= =?UTF-8?q?=E9=94=81map=E5=AF=B9=E8=B1=A1=E4=B8=BA=E7=BA=BF=E7=A8=8B?= =?UTF-8?q?=E5=AE=89=E5=85=A8=E7=9A=84map?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/aiyh/utils/lock/LockUtils.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/aiyh/utils/lock/LockUtils.java b/src/main/java/aiyh/utils/lock/LockUtils.java index c06d8e9..0967be0 100644 --- a/src/main/java/aiyh/utils/lock/LockUtils.java +++ b/src/main/java/aiyh/utils/lock/LockUtils.java @@ -5,9 +5,9 @@ import aiyh.utils.excention.CustomerException; import cn.hutool.core.thread.ThreadUtil; import ebu7common.youhong.ai.bean.Builder; -import java.util.HashMap; import java.util.Map; import java.util.Objects; +import java.util.concurrent.ConcurrentHashMap; /** *

分布式锁

@@ -21,7 +21,7 @@ public class LockUtils { private static final LockUtilMapper mapper = Util.getMapper(LockUtilMapper.class); - private static final Map LOCK_MAP = new HashMap<>(); + private static final Map LOCK_MAP = new ConcurrentHashMap<>(); /** 默认过期时间 10s */ private static final Long DEFAULT_OVERDUE_TIME = 1_000 * 10L; From 24a1db60accc9149a43586dd4d8dc269dfa16d1c Mon Sep 17 00:00:00 2001 From: wangxuanran <3055088966@qq.com> Date: Mon, 12 Dec 2022 14:17:20 +0800 Subject: [PATCH 09/33] =?UTF-8?q?2022-12-12=20=E6=96=87=E4=BB=B6=E6=8F=90?= =?UTF-8?q?=E7=A4=BA=E6=8F=92=E4=BB=B6=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../CusCreateWorkFlowController.java | 9 ++-- ...delAsync.java => CusDataToModelAsync.java} | 4 +- .../service/DataAsyncConfigService.java | 6 +-- .../schroeder/action/PushSealTaskAction.java | 19 ++++---- .../PushSealTaskSealValue.java | 26 ++++++----- .../service/SchroederQRCodeService.java | 46 ++++++++++--------- .../model_data_async/AsyncTest.java | 16 +++++-- .../download_file/DownLoadFileTest.java | 39 ++++++++++++++-- 8 files changed, 104 insertions(+), 61 deletions(-) rename src/main/java/weaver/xuanran/wang/saic_travel/model_data_async/job/{HrmDataToModelAsync.java => CusDataToModelAsync.java} (92%) diff --git a/src/main/java/com/api/xuanran/wang/saic_travel/model_create_workflow/controller/CusCreateWorkFlowController.java b/src/main/java/com/api/xuanran/wang/saic_travel/model_create_workflow/controller/CusCreateWorkFlowController.java index 3abb495..626d929 100644 --- a/src/main/java/com/api/xuanran/wang/saic_travel/model_create_workflow/controller/CusCreateWorkFlowController.java +++ b/src/main/java/com/api/xuanran/wang/saic_travel/model_create_workflow/controller/CusCreateWorkFlowController.java @@ -6,7 +6,7 @@ import com.alibaba.fastjson.JSONObject; import org.apache.log4j.Logger; import weaver.hrm.HrmUserVarify; import weaver.hrm.User; -import weaver.xuanran.wang.common.util.CommonUtil; +import weaver.xuanran.wang.common.util.CommonUtil; // 工具类 import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -26,7 +26,7 @@ import java.util.stream.Collectors; @Path("/wxr/saicTravel/") public class CusCreateWorkFlowController { - private final Logger logger = Util.getLogger(); + private final Logger logger = Util.getLogger(); // 获取日志对象 @Path("cusCreateWorkFlow") @POST @@ -39,14 +39,15 @@ public class CusCreateWorkFlowController { String choiceData = request.getParameter("choiceData"); int modelId = Util.getIntValue(request.getParameter("modelId"), -1); List dataList = Arrays.stream(choiceData.split(",")).collect(Collectors.toList()); - List requestIds = CommonUtil.doCreateWorkFlow(modelId, dataList); + List requestIds = CommonUtil.doCreateWorkFlow(modelId, dataList); // 通过数据审批生成流程 List errorData = new ArrayList<>(); for (int i = 0; i < requestIds.size(); i++) { if (Util.getIntValue(requestIds.get(i), -1) < 0) { errorData.add(dataList.get(i)); } } - logger.error(Util.logStr("执行创建流程失败集合: {}",JSONObject.toJSONString(errorData))); + logger.error(Util.logStr("执行创建流程失败集合: {}",JSONObject.toJSONString(errorData))); // 构建日志字符串 return ApiResult.success(errorData); } } + diff --git a/src/main/java/weaver/xuanran/wang/saic_travel/model_data_async/job/HrmDataToModelAsync.java b/src/main/java/weaver/xuanran/wang/saic_travel/model_data_async/job/CusDataToModelAsync.java similarity index 92% rename from src/main/java/weaver/xuanran/wang/saic_travel/model_data_async/job/HrmDataToModelAsync.java rename to src/main/java/weaver/xuanran/wang/saic_travel/model_data_async/job/CusDataToModelAsync.java index 05b9fff..5145d79 100644 --- a/src/main/java/weaver/xuanran/wang/saic_travel/model_data_async/job/HrmDataToModelAsync.java +++ b/src/main/java/weaver/xuanran/wang/saic_travel/model_data_async/job/CusDataToModelAsync.java @@ -10,12 +10,12 @@ import weaver.xuanran.wang.saic_travel.model_data_async.service.DataAsyncConfigS /** - *

员工信息同步至建模

+ *

信息同步至建模

* * @Author xuanran.wang * @Date 2022/12/1 15:20 */ -public class HrmDataToModelAsync extends BaseCronJob { +public class CusDataToModelAsync extends BaseCronJob { private final Logger logger = Util.getLogger(); diff --git a/src/main/java/weaver/xuanran/wang/saic_travel/model_data_async/service/DataAsyncConfigService.java b/src/main/java/weaver/xuanran/wang/saic_travel/model_data_async/service/DataAsyncConfigService.java index fef8ddf..c2fc8e8 100644 --- a/src/main/java/weaver/xuanran/wang/saic_travel/model_data_async/service/DataAsyncConfigService.java +++ b/src/main/java/weaver/xuanran/wang/saic_travel/model_data_async/service/DataAsyncConfigService.java @@ -2,7 +2,6 @@ package weaver.xuanran.wang.saic_travel.model_data_async.service; import aiyh.utils.Util; import aiyh.utils.excention.CustomerException; -import com.alibaba.fastjson.JSONObject; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; import org.springframework.util.Assert; @@ -14,8 +13,6 @@ import weaver.xuanran.wang.saic_travel.model_data_async.config.eneity.DataAsyncD import weaver.xuanran.wang.saic_travel.model_data_async.config.eneity.DataAsyncMain; import weaver.xuanran.wang.saic_travel.model_data_async.config.mapper.DataAsyncConfigMapper; import weaver.xuanran.wang.saic_travel.model_data_async.constant.DataAsyncConstant; -import weaver.xuanran.wang.saic_travel.model_data_async.mapper.DataAsyncMapper; -import weaver.zwl.common.ToolUtil; import java.util.*; import java.util.stream.Collectors; @@ -99,8 +96,7 @@ public class DataAsyncConfigService { linkedHashMapList.add(copyMap); } } - List list = CusInfoToOAUtil.executeBatch(modelId, linkedHashMapList); - return list; + return CusInfoToOAUtil.executeBatch(modelId, linkedHashMapList); } /** *

根据配置将值转换

diff --git a/src/main/java/weaver/xuanran/wang/schroeder/action/PushSealTaskAction.java b/src/main/java/weaver/xuanran/wang/schroeder/action/PushSealTaskAction.java index d559208..5e53045 100644 --- a/src/main/java/weaver/xuanran/wang/schroeder/action/PushSealTaskAction.java +++ b/src/main/java/weaver/xuanran/wang/schroeder/action/PushSealTaskAction.java @@ -1,9 +1,9 @@ package weaver.xuanran.wang.schroeder.action; import aiyh.utils.Util; -import aiyh.utils.action.CusBaseAction; +import aiyh.utils.action.CusBaseAction; // 基础的action,实现一些基础的参数 import aiyh.utils.annotation.RequiredMark; -import aiyh.utils.excention.CustomerException; +import aiyh.utils.excention.CustomerException; // 自定义异常类 create 2022/3/9 2:20 PM import weaver.conn.RecordSetTrans; import weaver.hrm.User; import weaver.workflow.request.RequestManager; @@ -16,7 +16,7 @@ import weaver.xuanran.wang.schroeder.service.SchroederQRCodeService; * @Author xuanran.wang * @Date 2022/11/30 16:08 */ -public class PushSealTaskAction extends CusBaseAction { +public class PushSealTaskAction extends CusBaseAction { // 基础的action,实现一些基础的参数 /** *

建模配置唯一标识

@@ -30,24 +30,25 @@ public class PushSealTaskAction extends CusBaseAction { @RequiredMark private String QRCodeField; - private final SchroederQRCodeService schroederQRCodeService = new SchroederQRCodeService(); + private final SchroederQRCodeService schroederQRCodeService = new SchroederQRCodeService(); // 施罗德业务方法 施罗德业务方法 - @Override + @Override // action 提交流程业务处理方法 具体业务逻辑实现 public void doSubmit(String requestId, String billTable, int workflowId, User user, RequestManager requestManager) { log.info("---------- PushSealTaskSealValue Begin " + requestId + "----------"); - String scanNum = schroederQRCodeService.pushSealTask(onlyMark, billTable, requestId); + String scanNum = schroederQRCodeService.pushSealTask(onlyMark, billTable, requestId); // 推送数据创建任务 建模配置唯一标识 RecordSetTrans trans = requestManager.getRsTrans(); trans.setAutoCommit(false); - String updateSql = "update " + billTable + " set " + QRCodeField + " = ? where requestid = ?"; + String updateSql = "update " + billTable + " set " + QRCodeField + " = ? where requestid = ?"; // 二维码来源字段 try{ if(!trans.executeUpdate(updateSql, scanNum, requestId)){ - throw new CustomerException(Util.logStr("更新表单sql执行失败!sql : {}, 参数 scanNum : {}, requestId : {}", scanNum, requestId)); + throw new CustomerException(Util.logStr("更新表单sql执行失败!sql : {}, 参数 scanNum : {}, requestId : {}", scanNum, requestId)); // 自定义异常类 create 2022/3/9 2:20 PM 构建日志字符串 } }catch (Exception e){ trans.rollback(); - throw new CustomerException(Util.logStr("执行提交方法异常:{}", e.getMessage())); + throw new CustomerException(Util.logStr("执行提交方法异常:{}", e.getMessage())); // 自定义异常类 create 2022/3/9 2:20 PM 构建日志字符串 } trans.commit(); } } + diff --git a/src/main/java/weaver/xuanran/wang/schroeder/cus_field_value/PushSealTaskSealValue.java b/src/main/java/weaver/xuanran/wang/schroeder/cus_field_value/PushSealTaskSealValue.java index 1ccb5d0..d4859d7 100644 --- a/src/main/java/weaver/xuanran/wang/schroeder/cus_field_value/PushSealTaskSealValue.java +++ b/src/main/java/weaver/xuanran/wang/schroeder/cus_field_value/PushSealTaskSealValue.java @@ -1,14 +1,14 @@ package weaver.xuanran.wang.schroeder.cus_field_value; import aiyh.utils.Util; -import aiyh.utils.excention.CustomerException; +import aiyh.utils.excention.CustomerException; // 自定义异常类 create 2022/3/9 2:20 PM import com.alibaba.fastjson.JSONObject; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; import weaver.conn.RecordSet; -import weaver.xiao.commons.config.interfacies.CusInterfaceGetValue; -import weaver.zwl.common.ToolUtil; +import weaver.xiao.commons.config.interfacies.CusInterfaceGetValue; // 自定义获取参数值 +import weaver.zwl.common.ToolUtil; // 常用工具方法-公用类 import java.util.*; import java.util.stream.Collectors; @@ -19,14 +19,14 @@ import java.util.stream.Collectors; * @Author xuanran.wang * @Date 2022/12/2 16:10 */ -public class PushSealTaskSealValue implements CusInterfaceGetValue { - private final ToolUtil toolUtil = new ToolUtil(); +public class PushSealTaskSealValue implements CusInterfaceGetValue { // 自定义获取参数值 + private final ToolUtil toolUtil = new ToolUtil(); // 常用工具方法-公用类 构造方法 - private final Logger logger = Util.getLogger(); + private final Logger logger = Util.getLogger(); // 获取日志对象 - @Override + @Override // 获取参数值 public Object execute(Map mainMap, Map detailMap, String currentValue, Map pathParam) { - logger.info(Util.logStr("路径参数:[{}]", JSONObject.toJSONString(pathParam))); + logger.info(Util.logStr("路径参数:[{}]", JSONObject.toJSONString(pathParam))); // 构建日志字符串 // 接口字段 String sealSnField = pathParam.get("sealSnField"); String sealNumField = pathParam.get("sealNumField"); @@ -36,9 +36,9 @@ public class PushSealTaskSealValue implements CusInterfaceGetValue { String sealNumCusSql = pathParam.get("sealNumCusSql"); // 非空校验 if(checkBlank(sealSnField, sealNumField, sealSnCusSql, sealNumCusSql)){ - throw new CustomerException(Util.logStr("自定义类路径中必要参数为空,请检查!当前pathParam : {}", JSONObject.toJSONString(pathParam))); + throw new CustomerException(Util.logStr("自定义类路径中必要参数为空,请检查!当前pathParam : {}", JSONObject.toJSONString(pathParam))); // 自定义异常类 create 2022/3/9 2:20 PM 构建日志字符串 } - logger.info(Util.logStr("当前值 : {}", currentValue)); + logger.info(Util.logStr("当前值 : {}", currentValue)); // 构建日志字符串 // 如果为空返回空集合 if(StringUtils.isBlank(currentValue)){ return Collections.emptyList(); @@ -50,8 +50,8 @@ public class PushSealTaskSealValue implements CusInterfaceGetValue { } for (String val : currentValue.split(",")) { // 印章类型转换执行自定义sql - String inSealVal = Util.null2DefaultStr(toolUtil.getValueByChangeRule(sealSnCusSql, val, String.valueOf(mainMap.get("requestid")), detailId),""); - String inSealNumVal = Util.null2DefaultStr(toolUtil.getValueByChangeRule(sealNumCusSql, val, String.valueOf(mainMap.get("requestid")), detailId),""); + String inSealVal = Util.null2DefaultStr(toolUtil.getValueByChangeRule(sealSnCusSql, val, String.valueOf(mainMap.get("requestid")), detailId),""); // 用数据库值,根据规则转换,获取其最终结果 + String inSealNumVal = Util.null2DefaultStr(toolUtil.getValueByChangeRule(sealNumCusSql, val, String.valueOf(mainMap.get("requestid")), detailId),""); // 用数据库值,根据规则转换,获取其最终结果 HashMap map = new HashMap<>(); map.put(sealSnField, inSealVal); map.put(sealNumField, inSealNumVal); @@ -64,3 +64,5 @@ public class PushSealTaskSealValue implements CusInterfaceGetValue { return Arrays.stream(args).anyMatch(StringUtils::isBlank); } } + + diff --git a/src/main/java/weaver/xuanran/wang/schroeder/service/SchroederQRCodeService.java b/src/main/java/weaver/xuanran/wang/schroeder/service/SchroederQRCodeService.java index d85909f..6b28b52 100644 --- a/src/main/java/weaver/xuanran/wang/schroeder/service/SchroederQRCodeService.java +++ b/src/main/java/weaver/xuanran/wang/schroeder/service/SchroederQRCodeService.java @@ -1,7 +1,7 @@ package weaver.xuanran.wang.schroeder.service; import aiyh.utils.Util; -import aiyh.utils.excention.CustomerException; +import aiyh.utils.excention.CustomerException; // 自定义异常类 create 2022/3/9 2:20 PM import aiyh.utils.httpUtil.ResponeVo; import aiyh.utils.httpUtil.util.HttpUtils; import com.alibaba.fastjson.JSON; @@ -44,10 +44,10 @@ public class SchroederQRCodeService { **/ private static final String STATUS_FIELD = "status"; private final DealWithMapping dealWithMapping = new DealWithMapping(); - private final Logger log = Util.getLogger(); + private final Logger log = Util.getLogger(); // 获取日志对象 private final HttpUtils httpUtils = new HttpUtils(); { - httpUtils.getGlobalCache().header.put("Content-Type", MediaType.APPLICATION_JSON); + httpUtils.getGlobalCache().header.put("Content-Type", MediaType.APPLICATION_JSON); // 全局请求头 } /** @@ -61,10 +61,10 @@ public class SchroederQRCodeService { **/ public String pushSealTask(String onlyMark, String billTable, String requestId){ String res = ""; - RequestMappingConfig requestMappingConfig = dealWithMapping.treeDealWithUniqueCode(onlyMark); + RequestMappingConfig requestMappingConfig = dealWithMapping.treeDealWithUniqueCode(onlyMark); // 将配置参数通过唯一标识查询处理成树形结构 String cusWhere = Util.null2DefaultStr(requestMappingConfig.getCusWhereSql(),""); if(StringUtils.isNotBlank(cusWhere)){ - cusWhere = DealWithMapping.sbc2dbcCase(cusWhere); + cusWhere = DealWithMapping.sbc2dbcCase(cusWhere); // 全角转半角 } String selectMainSql = "select * from " + billTable + " where requestid = ? " + cusWhere; log.info("查询主表数据sql { " + selectMainSql + " }, requestId { " + requestId + " }"); @@ -72,43 +72,45 @@ public class SchroederQRCodeService { recordSet.executeQuery(selectMainSql, requestId); if (recordSet.next()) { dealWithMapping.setMainTable(billTable); - Map requestParam = dealWithMapping.getRequestParam(recordSet, requestMappingConfig); - log.info(Util.logStr("请求json : {}", JSONObject.toJSONString(requestParam))); + Map requestParam = dealWithMapping.getRequestParam(recordSet, requestMappingConfig); // 解析请求参数配置树,转换成请求参数 + log.info(Util.logStr("请求json : {}", JSONObject.toJSONString(requestParam))); // 构建日志字符串 String url = requestMappingConfig.getRequestUrl(); ResponeVo responeVo = null; try { responeVo = httpUtils.apiPost(url, requestParam); } catch (IOException e) { - throw new CustomerException(Util.logStr("发送印章请求发生异常! : {}", e.getMessage())); + throw new CustomerException(Util.logStr("发送印章请求发生异常! : {}", e.getMessage())); // 自定义异常类 create 2022/3/9 2:20 PM 构建日志字符串 } - Map headers = httpUtils.getGlobalCache().header; - if (responeVo.getCode() != SUCCESS_CODE) { - log.error(Util.logStr("can not fetch [{}],this request params is [{}]," + + Map headers = httpUtils.getGlobalCache().header; // 全局请求头 + if (responeVo.getCode() != SUCCESS_CODE) { // 相应状态码 + log.error(Util.logStr("can not fetch [{}],this request params is [{}]," + // 构建日志字符串 "this request heard is [{}],but response status code is [{}]," + - "this response is [{}]", url, JSON.toJSON(requestParam), JSON.toJSONString(headers), responeVo.getCode(), - responeVo.getEntityString())); - throw new CustomerException(Util.logStr("can not fetch [{}]", url)); + "this response is [{}]", url, JSON.toJSON(requestParam), JSON.toJSONString(headers), responeVo.getCode(), // 相应状态码 + responeVo.getEntityString())); // 相应内容 + throw new CustomerException(Util.logStr("can not fetch [{}]", url)); // 自定义异常类 create 2022/3/9 2:20 PM 构建日志字符串 } Map response; - log.info(Util.logStr("this response is [{}]", responeVo.getEntityString())); + log.info(Util.logStr("this response is [{}]", responeVo.getEntityString())); // 构建日志字符串 相应内容 try { - response = responeVo.getEntityMap(); - log.info(Util.logStr("接口响应:{}", JSONObject.toJSONString(response))); + response = responeVo.getEntityMap(); // 根据相应结果转化为map集合 + log.info(Util.logStr("接口响应:{}", JSONObject.toJSONString(response))); // 构建日志字符串 } catch (JsonProcessingException e) { - log.error(Util.logStr("push data error, can not parse response to map," + + log.error(Util.logStr("push data error, can not parse response to map," + // 构建日志字符串 "this response is [{}], url is [{}],request params is [{}], request heard is [{}];", - responeVo.getEntityString(), url, JSON.toJSONString(requestParam), JSON.toJSONString(headers))); - throw new CustomerException(Util.logStr("push data error, can not parse response to map")); + responeVo.getEntityString(), url, JSON.toJSONString(requestParam), JSON.toJSONString(headers))); // 相应内容 + throw new CustomerException(Util.logStr("push data error, can not parse response to map")); // 自定义异常类 create 2022/3/9 2:20 PM 构建日志字符串 } int status = (int) response.get(STATUS_FIELD); if(SUCCESS_STATUS != status){ - throw new CustomerException(Util.logStr("接口响应码不为0,接口响应信息:{}", Util.null2DefaultStr(response.get(MESSAGE_FIELD),""))); + throw new CustomerException(Util.logStr("接口响应码不为0,接口响应信息:{}", Util.null2DefaultStr(response.get(MESSAGE_FIELD),""))); // 自定义异常类 create 2022/3/9 2:20 PM 构建日志字符串 } res = Util.null2DefaultStr(response.get(SCAN_NUM_FIELD),""); } if(StringUtils.isBlank(res)){ - throw new CustomerException("获取接口中响应任务字段为空, 请检查!"); + throw new CustomerException("获取接口中响应任务字段为空, 请检查!"); // 自定义异常类 create 2022/3/9 2:20 PM } return res; } } + + diff --git a/src/test/java/xuanran/wang/saic_travel/model_data_async/AsyncTest.java b/src/test/java/xuanran/wang/saic_travel/model_data_async/AsyncTest.java index fe7657e..a95e623 100644 --- a/src/test/java/xuanran/wang/saic_travel/model_data_async/AsyncTest.java +++ b/src/test/java/xuanran/wang/saic_travel/model_data_async/AsyncTest.java @@ -5,6 +5,7 @@ import com.alibaba.fastjson.JSONObject; import org.apache.commons.lang3.StringUtils; import org.junit.Test; import weaver.formmode.data.ModeDataApproval; +import weaver.general.Util; import weaver.hrm.User; import weaver.xuanran.wang.common.util.CommonUtil; import weaver.xuanran.wang.saic_travel.model_data_async.config.eneity.DataAsyncMain; @@ -44,10 +45,17 @@ public class AsyncTest extends BaseTest { @Test public void testAsync(){ - DataAsyncMain config = dataAsyncConfigService.getDataAsyncConfigByUniqueCode("hrmAsyncTest"); - List data = dataAsyncConfigService.asyncModelData(config, 109); - List list = CommonUtil.doCreateWorkFlow(109, data); - log.info("触发成功 : " + JSONObject.toJSONString(list)); +// try { +// DataAsyncMain config = dataAsyncConfigService.getDataAsyncConfigByUniqueCode("wacoTest"); +// List data = dataAsyncConfigService.asyncModelData(config, 109); +// log.info("生成的数据id : " + JSONObject.toJSONString(data)); +// }catch (Exception e){ +// log.error("生成建模数据异常 : " + e.getMessage()); +// } +// List list = CommonUtil.doCreateWorkFlow(109, data); +// log.info("触发成功 : " + JSONObject.toJSONString(list)); + log.info("select hr.email from HrmResource hr where status in (0,1,2,3) AND "+ Util.getSubINClause("1,3,323,124,544","id","in") + " and " + Util.getSubINClause("1","id","not in")); + log.info(Util.getSubINClause("1,3,323,124,544","id","in",2)); } @Test diff --git a/src/test/java/xuanran/wang/schroeder/download_file/DownLoadFileTest.java b/src/test/java/xuanran/wang/schroeder/download_file/DownLoadFileTest.java index 70fe195..48ef944 100644 --- a/src/test/java/xuanran/wang/schroeder/download_file/DownLoadFileTest.java +++ b/src/test/java/xuanran/wang/schroeder/download_file/DownLoadFileTest.java @@ -4,8 +4,11 @@ import aiyh.utils.Util; import basetest.BaseTest; import com.alibaba.fastjson.JSONObject; import com.api.xuanran.wang.schroeder.download_file.mapper.DownLoadFileMapper; +import com.icbc.api.internal.apache.http.impl.cookie.S; +import org.apache.commons.lang3.StringUtils; import org.junit.Test; import weaver.file.ImageFileManager; +import weaver.general.TimeUtil; import weaver.xuanran.wang.common.util.CommonUtil; import java.io.FileInputStream; @@ -14,7 +17,10 @@ import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Paths; -import java.util.Map; +import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; /** *

@@ -39,7 +45,34 @@ public class DownLoadFileTest extends BaseTest { @Test public void testImageFileInputSteam(){ - InputStream inputStreamById = ImageFileManager.getInputStreamById(705); - System.out.println("============="); + HashMap header = new HashMap<>(); + header.put("Content-Type", "application/json;charset=utf-8"); + header.put("Authorization", ""); + header.put("reqFrom", "1212"); + header.put("reqId", UUID.randomUUID().toString()); + header.put("reqTime", TimeUtil.getCurrentTimeString()); + log.info("header " + header); + } + + @Test + public void testParseStr(){ + + String str = ""; + String pattern = "(?<=\\{).+(?=})"; + Pattern compile = Pattern.compile(pattern); + Matcher matcher = compile.matcher(str); + while (matcher.find()){ + String group = matcher.group(); + if(StringUtils.isNotBlank(group)){ + if(group.startsWith("main.")){ + String replaceAll = group.replaceAll("#\\{.+}","黄齑淡饭"); + log.info("replaceAll : " + replaceAll); + }else if(group.startsWith("detail.")){ + + }else if(group.startsWith("sql.")){ + + } + } + } } } From d59ed4f677f10a7ba58bb16dfe6d5837d7fe24c4 Mon Sep 17 00:00:00 2001 From: "youHong.ai" <774495953@qq.com> Date: Tue, 13 Dec 2022 10:35:10 +0800 Subject: [PATCH 10/33] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=B5=81=E7=A8=8B?= =?UTF-8?q?=E4=BF=9D=E5=AD=98=E8=A7=A6=E5=8F=91=E6=B5=81=E7=A8=8B=E8=BD=AC?= =?UTF-8?q?=E6=95=B0=E6=8D=AE=E6=8E=A5=E5=8F=A3=EF=BC=8C=E4=BF=AE=E6=94=B9?= =?UTF-8?q?=E5=88=86=E5=B8=83=E5=BC=8F=E9=94=81=EF=BC=8C=E6=B7=BB=E5=8A=A0?= =?UTF-8?q?=E5=BB=BA=E6=A8=A1targetSetting=E6=8C=89=E9=92=AE=E7=BD=AE?= =?UTF-8?q?=E7=81=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- javascript/common/Utils.js | 10 +- javascript/common/dev.js | 15 + .../fentian/ecode/workflow_controller.js | 4 - .../youhong.ai/pcn/workflow_code_block.js | 319 ++++++++++++------ src/main/java/aiyh/utils/LabelHtmlUtils.java | 6 +- src/main/java/aiyh/utils/MybatisUtil.java | 16 +- src/main/java/aiyh/utils/lock/LockUtils.java | 68 ++-- .../NotAllowedClickTGSController.java | 46 +++ .../mapper/NotAllowedClickTGSMapper.java | 46 +++ .../service/NotAllowedClickTGSService.java | 47 +++ .../TriggerWorkflowToModelService.java | 32 +- .../java/youhong/ai/pcn/WorkflowTest.java | 31 ++ 12 files changed, 477 insertions(+), 163 deletions(-) create mode 100644 src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/controller/NotAllowedClickTGSController.java create mode 100644 src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/mapper/NotAllowedClickTGSMapper.java create mode 100644 src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/service/NotAllowedClickTGSService.java create mode 100644 src/test/java/youhong/ai/pcn/WorkflowTest.java diff --git a/javascript/common/Utils.js b/javascript/common/Utils.js index 700864e..75aa117 100644 --- a/javascript/common/Utils.js +++ b/javascript/common/Utils.js @@ -135,7 +135,15 @@ window.Utils = { */ getFiledValueByName: function (fieldName, rowIndex) { return WfForm.getFieldValue(Utils.convertNameObjToId(fieldName) + rowIndex ? '_' + rowIndex : '') + }, + + /** + * 通过字段名称修改字段值 + * @param fieldName 字段名称 + * @param value 值 + */ + changeFieldValueByName: function (fieldName, value) { + WfForm.changeFieldValue(Utils.convertNameObjToId(fieldName), {value}) } - } diff --git a/javascript/common/dev.js b/javascript/common/dev.js index 3956a6f..0ceb3ed 100644 --- a/javascript/common/dev.js +++ b/javascript/common/dev.js @@ -134,5 +134,20 @@ WfForm.changeFieldValue = function (fieldMark, valueInfo) { } +/* ******************* 建模表开发依赖 ******************* */ + +const ModeList = {} +ModeList.dataLoadAfter = function (data) { + // 描述:在列表数据加载完,对列表的数据进行二次加工,并渲染。 dataLoadAfter传入dataHandle方法,用来接收并处理数据,dataHandle有两个参数。 + // var dataHandle = function(datas,displayType){ + // //Changes to 'datas' do not directly modify the real database data, but modify the data received at the front end. + // var newDatas = datas; + // if(displayType == 'normal'){ + // console.log(newDatas); + // } + // return newDatas; + // } + // ModeList.dataLoadAfter(dataHandle); +}; diff --git a/javascript/youhong.ai/fentian/ecode/workflow_controller.js b/javascript/youhong.ai/fentian/ecode/workflow_controller.js index 1279b85..3205701 100644 --- a/javascript/youhong.ai/fentian/ecode/workflow_controller.js +++ b/javascript/youhong.ai/fentian/ecode/workflow_controller.js @@ -4,7 +4,6 @@ class ConfigWorkflowTitle { constructor(config) { this.config = config - console.log(config) } @@ -12,17 +11,14 @@ class ConfigWorkflowTitle { * 初始化参数 */ init = () => { - console.log("init") let baseInfo = WfForm.getBaseInfo(); if (baseInfo.workflowid != this.config.workflowId) { return } let filedArr = [] - console.log("jahh") this.config.rules.filter(item => item.type === RulesType.FIELD_VALUE || item.type === RulesType.SELECT_VALUE || item.type === RulesType.RADIO_VALUE).forEach(item => filedArr.push(item.fieldName)) - console.log("bind", filedArr) this.addListenerEvent(filedArr) } diff --git a/javascript/youhong.ai/pcn/workflow_code_block.js b/javascript/youhong.ai/pcn/workflow_code_block.js index 2eab958..928b1ee 100644 --- a/javascript/youhong.ai/pcn/workflow_code_block.js +++ b/javascript/youhong.ai/pcn/workflow_code_block.js @@ -1,133 +1,232 @@ /* ******************* 保时捷target setting流程提交控制 start ******************* */ -/** - * @author youhong.ai - * @desc 禁止点击提交按钮 - */ -function doNotClickSubmit() { - let submitButton = $('.ant-btn.ant-btn-primary[ecid="_Route@vmt0lk_Comp@upn4fo_Button@2oxqe7@0_button@xq1ea3"][title="Submit "]') - if (submitButton.length === 0) { - submitButton = $('.ant-btn.ant-btn-primary[ecid="_Route@vmt0lk_Comp@upn4fo_Button@2oxqe7@0_button@xq1ea3"][title="提交"]') - } - if (submitButton.length === 0) { - submitButton = $("#weareqtop_9v5e5i_1670481049632 div.ant-row.wea-new-top-req div.ant-col-xs-18.ant-col-sm-18.ant-col-md-16.ant-col-lg-14 button[title='提交'],[title='Submit '],[title='Submit']") - } - if (submitButton.length !== 0) { - let buttonReact = window.Utils.findReact(submitButton[0]) - let rightBtn = Utils.findReact($(".ant-menu-item.text-elli[ecid='_Route@vmt0lk_Comp@upn4fo_WeaRightMenu@1ok9r0_Item@eu37n0_li@zyccqn']")[0]) - setTimeout(() => { - buttonReact.props.disabled = true +window.workflowCus = Object.assign(window.workflowCus ? window.workflowCus : {}, { + /** + * @author youhong.ai + * @desc 禁止点击提交按钮 + */ + doNotClickSubmit: function () { + let submitButton = $('.ant-btn.ant-btn-primary[ecid="_Route@vmt0lk_Comp@upn4fo_Button@2oxqe7@0_button@xq1ea3"][title="Submit "]') + if (submitButton.length === 0) { + submitButton = $('.ant-btn.ant-btn-primary[ecid="_Route@vmt0lk_Comp@upn4fo_Button@2oxqe7@0_button@xq1ea3"][title="提交"]') + } + if (submitButton.length === 0) { + submitButton = $("#weareqtop_9v5e5i_1670481049632 div.ant-row.wea-new-top-req div.ant-col-xs-18.ant-col-sm-18.ant-col-md-16.ant-col-lg-14 button[title='提交'],[title='Submit '],[title='Submit']") + } + if (submitButton.length !== 0) { + let buttonReact = window.Utils.findReact(submitButton[0]) + let rightBtn = Utils.findReact($(".ant-menu-item.text-elli[ecid='_Route@vmt0lk_Comp@upn4fo_WeaRightMenu@1ok9r0_Item@eu37n0_li@zyccqn']")[0]) + setTimeout(() => { + buttonReact.props.disabled = true + buttonReact.setState({}) + rightBtn.props.disabled = true + rightBtn.setState({}) + }, 100) + } + }, + + /** + * @author youhong.ai + * @desc 允许点击按钮 + */ + allowClickSubmit: function () { + let submitButton = $('.ant-btn.ant-btn-primary[ecid="_Route@vmt0lk_Comp@upn4fo_Button@2oxqe7@0_button@xq1ea3"][title="Submit "]') + if (submitButton.length === 0) { + submitButton = $('.ant-btn.ant-btn-primary[ecid="_Route@vmt0lk_Comp@upn4fo_Button@2oxqe7@0_button@xq1ea3"][title="提交"]') + } + if (submitButton.length === 0) { + submitButton = $("#weareqtop_9v5e5i_1670481049632 div.ant-row.wea-new-top-req div.ant-col-xs-18.ant-col-sm-18.ant-col-md-16.ant-col-lg-14 button[title='提交'],[title='Submit '],[title='Submit']") + } + if (submitButton.length !== 0) { + WfForm.controlBtnDisabled(false) + let buttonReact = window.Utils.findReact(submitButton[0]) + buttonReact.props.disabled = false buttonReact.setState({}) - rightBtn.props.disabled = true - rightBtn.setState({}) - }, 100) - } -} + } + }, -/** - * @author youhong.ai - * @desc 允许点击按钮 - */ -function allowClickSubmit() { - let submitButton = $('.ant-btn.ant-btn-primary[ecid="_Route@vmt0lk_Comp@upn4fo_Button@2oxqe7@0_button@xq1ea3"][title="Submit "]') - if (submitButton.length === 0) { - submitButton = $('.ant-btn.ant-btn-primary[ecid="_Route@vmt0lk_Comp@upn4fo_Button@2oxqe7@0_button@xq1ea3"][title="提交"]') - } - if (submitButton.length === 0) { - submitButton = $("#weareqtop_9v5e5i_1670481049632 div.ant-row.wea-new-top-req div.ant-col-xs-18.ant-col-sm-18.ant-col-md-16.ant-col-lg-14 button[title='提交'],[title='Submit '],[title='Submit']") - } - if (submitButton.length !== 0) { - WfForm.controlBtnDisabled(false) - let buttonReact = window.Utils.findReact(submitButton[0]) - buttonReact.props.disabled = false - buttonReact.setState({}) - } -} - -/** - * 监听qzhj字段值改变 - * @author youhong.ai - * @param id 字段id - * @param value 字段值 - * @param obj 字段值对象 - */ -function onQzhjFieldChangeValue(obj, id, value) { - if (value != '100') { - doNotClickSubmit() - } else { - allowClickSubmit() - } -} - -/** - * 检查qzhj字段值 - * @author youhong.ai - * @param fieldId qzhj字段id - */ -function checkOnQzhJfiedlChangeValue(fieldId) { - let value = WfForm.getFieldValue(fieldId); - onQzhjFieldChangeValue(null, null, value) -} - - -/** - * 检查提交按钮是否符合条件 - * @author youhong.ai - * @param fieldId 字段id - * @returns {(function(function()=): void)|*} - */ -function checkClickSubmit(fieldId) { - return (callback = () => { - }) => { - let value = WfForm.getFieldValue(fieldId); - if (value != 100) { - WfForm.showMessage("~`~`7 目标设定的总值必须是100%,请检查并修改后提交。 " + "`~`8 The total value of target setting must be 100%,please check to submit after modification! " + "`~`9 目标设定的总值必须是100%,请检查并修改后提交。`~`~", 2, 5); + /** + * 监听qzhj字段值改变 + * @author youhong.ai + * @param id 字段id + * @param value 字段值 + * @param obj 字段值对象 + */ + onQzhjFieldChangeValue: function (obj, id, value) { + if (value != '100') { + window.workflowCus.doNotClickSubmit() } else { - callback() + window.workflowCus.allowClickSubmit() } - } -} + }, -/** - * 保存按钮触发流程转数据 - * @author youhong.ai - * @param callback 保存后页面跳转前回调 - */ -async function saveTriggerWorkflowToModel() { - let baseInfo = WfForm.getBaseInfo() - if (baseInfo && baseInfo.requestid != '-1') { - let result = await Utils.api({ - url: "/api/aiyh/workflow/target-setting/save-trigger", - type: "POST", - contentType: "application/json", - data: JSON.stringify({requestId: baseInfo.requestid}) - }) - if (result && result.code === 200) { - localStorage.setItem("saveTriggerWorkflowToModel", "false") + /** + * 检查qzhj字段值 + * @author youhong.ai + * @param fieldId qzhj字段id + */ + checkOnQzhJfiedlChangeValue: function (fieldId) { + let value = WfForm.getFieldValue(fieldId); + window.workflowCus.onQzhjFieldChangeValue(null, null, value) + }, + + + /** + * 检查提交按钮是否符合条件 + * @author youhong.ai + * @param fieldId 字段id + * @returns {(function(function()=): void)|*} + */ + checkClickSubmit: function (fieldId) { + return (callback = () => { + }) => { + let value = WfForm.getFieldValue(fieldId); + if (value != 100) { + WfForm.showMessage("~`~`7 目标设定的总值必须是100%,请检查并修改后提交。 " + "`~`8 The total value of target setting must be 100%,please check to submit after modification! " + "`~`9 目标设定的总值必须是100%,请检查并修改后提交。`~`~", 2, 5); + } else { + callback() + } } + }, + + /** + * 保存按钮触发流程转数据 + * @author youhong.ai + */ + saveTriggerWorkflowToModel: async function () { + let baseInfo = WfForm.getBaseInfo() + if (baseInfo && baseInfo.requestid != '-1') { + let result = await Utils.api({ + url: "/api/aiyh/workflow/target-setting/save-trigger", + type: "POST", + contentType: "application/json", + data: JSON.stringify({ + requestId: baseInfo.requestid, + nodeId: baseInfo.nodeid, + isBill: baseInfo.isbill, + formId: baseInfo.formid, + workflowId: baseInfo.workflowid + }) + }) + if (result && result.code === 200) { + localStorage.setItem("saveTriggerWorkflowToModel", "false") + } + } + }, + + + saveAfterCallback: function (callback) { + localStorage.setItem("saveTriggerWorkflowToModel", "true") + callback() } -} +}) -function saveAfterCallback(callback) { - localStorage.setItem("saveTriggerWorkflowToModel", "true") - callback() -} - +/* ******************* 保时捷target setting流程提交控制 end ******************* */ +/* ******************* 保时捷target setting流程提交控制 start ******************* */ $(() => { let qzhjFieldId = WfForm.convertFieldNameToId("qzhj") - checkOnQzhJfiedlChangeValue(qzhjFieldId) - WfForm.registerCheckEvent(WfForm.OPER_SUBMIT, checkClickSubmit(qzhjFieldId)) - WfForm.registerCheckEvent(WfForm.OPER_SAVECOMPLETE, saveAfterCallback) - WfForm.bindFieldChangeEvent(qzhjFieldId, onQzhjFieldChangeValue) + window.workflowCus.checkOnQzhJfiedlChangeValue(qzhjFieldId) + WfForm.registerCheckEvent(WfForm.OPER_SUBMIT, window.workflowCus.checkClickSubmit(qzhjFieldId)) + WfForm.registerCheckEvent(WfForm.OPER_SAVECOMPLETE, window.workflowCus.saveAfterCallback) + WfForm.bindFieldChangeEvent(qzhjFieldId, window.workflowCus.onQzhjFieldChangeValue) let flag = localStorage.getItem("saveTriggerWorkflowToModel") if (flag === "true") { - saveTriggerWorkflowToModel() + window.workflowCus.saveTriggerWorkflowToModel() } }) /* ******************* 保时捷target setting流程提交控制 end ******************* */ +/* ******************* 保时捷个人目标台账查询target setting按钮默认置灰色 ******************* */ +window.workflowCus = Object.assign(window.workflowCus ? window.workflowCus : {}, { + + notAllowedTargetSetting: function () { + window.workflowCus.changeBtnDisabledValue(true) + }, + + changeBtnDisabledValue: function (disable) { + if ($(".ant-btn.ant-btn-primary[ecid='_Route@9uoqid_Com@knmejd_ButtonNew@813let@0_Button@tegwjx_button@xq1ea3']").length === 0) { + return + } + let button = Utils.findReact($(".ant-btn.ant-btn-primary[ecid='_Route@9uoqid_Com@knmejd_ButtonNew@813let@0_Button@tegwjx_button@xq1ea3']")[0]) + if (button) { + button.props.disabled = disable + button.setState({}) + } + }, + + allowedTargetSettingBtnClick: function () { + window.workflowCus.changeBtnDisabledValue(false) + }, + + queryTotalWeight: function () { + Utils.api({ + url: "/api/ayh/target-setting/btn/can-allowed" + }).then(res => { + if (res && res.code === 200) { + if (res.data) { + window.workflowCus.allowedTargetSettingBtnClick() + } else { + window.workflowCus.notAllowedTargetSetting() + } + } + }).catch(error => { + console.log(err) + }) + }, + + reRender: function () { + const dataHandle = function (datas, displayType) { + window.workflowCus.notAllowedTargetSetting() + //Changes to 'datas' do not directly modify the real database data, but modify the data received at the front end. + $(() => { + window.workflowCus.queryTotalWeight() + }) + return datas + + } + ModeList.dataLoadAfter(dataHandle) + } + +}) + +$(() => { + window.workflowCus.notAllowedTargetSetting() + setTimeout(() => { + window.workflowCus.notAllowedTargetSetting() + }, 10) + window.workflowCus.reRender() +}) +/* ******************* 保时捷个人目标台账查询target setting按钮默认置灰色 END ******************* */ +/* ******************* apa流程通过apa分数字段带出level字段 ******************* */ + +window.workflowCus = Object.assign(window.workflowCus ? window.workflowCus : {}, { + getLevelByScore: async function (config) { + let scoreFiled = config.scoreFiled + let score = Utils.getFiledValueByName(scoreFiled); + let result = await Utils.api({ + url: "/api/ayh/workflow/apa/level", + data: { + score + } + }) + if (result && result.code === 200) { + Utils.changeFieldValueByName(config.levelField, result.data) + } + } +}) + +$(() => { + let config = { + scoreFiled: "", + levelField: "" + } + window.workflowCus.getLevelByScore(config) +}) + + +/* ******************* apa流程通过apa分数字段带出level字段eng ******************* */ diff --git a/src/main/java/aiyh/utils/LabelHtmlUtils.java b/src/main/java/aiyh/utils/LabelHtmlUtils.java index a74186d..ed5759b 100644 --- a/src/main/java/aiyh/utils/LabelHtmlUtils.java +++ b/src/main/java/aiyh/utils/LabelHtmlUtils.java @@ -10,9 +10,9 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; /** - * @author EBU7-dev1-ayh - * create 2021/12/13 0013 10:29 - * 多语言工具类 + *

多语言工具类

+ * + * @author EBU7-dev1-ayh create 2021/12/13 0013 10:29 */ diff --git a/src/main/java/aiyh/utils/MybatisUtil.java b/src/main/java/aiyh/utils/MybatisUtil.java index 69cdbc5..2c3f0d5 100644 --- a/src/main/java/aiyh/utils/MybatisUtil.java +++ b/src/main/java/aiyh/utils/MybatisUtil.java @@ -7,24 +7,26 @@ import java.io.File; import java.io.Reader; /** - * @author EBU7-dev1-ayh - * create 2021/12/14 0014 15:57 + *

mybatis集成工具

+ * + * @author EBU7-dev1-ayh create 2021/12/14 0014 15:57 */ public class MybatisUtil { private static SqlSessionManager sqlSessionManager = null; - private synchronized static void init(String config){ + private synchronized static void init(String config) { try { - Reader resourceAsReader = Resources.getResourceAsReader("WEB-INF" + File.separator +config); + Reader resourceAsReader = Resources.getResourceAsReader("WEB-INF" + File.separator + config); sqlSessionManager = SqlSessionManager.newInstance(resourceAsReader); } catch (Exception e) { e.printStackTrace(); } } - public static SqlSessionManager getSessionManager(String config){ - if(sqlSessionManager == null){ + + public static SqlSessionManager getSessionManager(String config) { + if (sqlSessionManager == null) { synchronized (MybatisUtil.class) { if (sqlSessionManager == null) { init(config); @@ -34,7 +36,7 @@ public class MybatisUtil { return sqlSessionManager; } - public static T getMapper(Class tClass){ + public static T getMapper(Class tClass) { return sqlSessionManager.getMapper(tClass); } } diff --git a/src/main/java/aiyh/utils/lock/LockUtils.java b/src/main/java/aiyh/utils/lock/LockUtils.java index 0967be0..7c3fe1e 100644 --- a/src/main/java/aiyh/utils/lock/LockUtils.java +++ b/src/main/java/aiyh/utils/lock/LockUtils.java @@ -258,7 +258,7 @@ public class LockUtils { /** *

重试锁

* 2022/12/11 01:39 - * ****************************************** + * ************************************************************ * * @param dataId 数据id * @param lockName 锁名称 @@ -286,6 +286,38 @@ public class LockUtils { } } + /** + *

释放锁

+ * 2022/12/11 15:56 + * ****************************************** + * + * @param lockName 锁名称 + * @author youHong.ai ****************************************** + */ + public static void unLock(String lockName) { + if (LOCK_MAP.containsKey(lockName)) { + // 存在本地锁 + LockEntity lockEntity = LOCK_MAP.get(lockName); + if (!lockEntity.getLockMark().equals(Thread.currentThread())) { + // 并非当前上锁的线程在释放锁 + return; + } + Integer times = lockEntity.getTimes(); + if (times - 1 == 0) { + boolean unlock = mapper.unLock(lockName); + if (!unlock) { + int n = 0; + do { + if (n++ > 5) { + throw new CustomerException("can not unLock!Failed to release the lock after five attempts!"); + } + } while (!mapper.unLock(lockName)); // 释放锁失败 + } + return; + } + lockEntity.setTimes(lockEntity.getTimes() - 1); + } + } /** *

锁续期

@@ -314,39 +346,5 @@ public class LockUtils { } return true; } - - - /** - *

释放锁

- * 2022/12/11 15:56 - * ****************************************** - * - * @param lockName 锁名称 - * @author youHong.ai ****************************************** - */ - public void unLock(String lockName) { - if (LOCK_MAP.containsKey(lockName)) { - // 存在本地锁 - LockEntity lockEntity = LOCK_MAP.get(lockName); - if (!lockEntity.getLockMark().equals(Thread.currentThread())) { - // 并非当前上锁的线程在释放锁 - return; - } - Integer times = lockEntity.getTimes(); - if (times - 1 == 0) { - boolean unlock = mapper.unLock(lockName); - if (!unlock) { - int n = 0; - do { - if (n++ > 5) { - throw new CustomerException("can not unLock!Failed to release the lock after five attempts!"); - } - } while (!mapper.unLock(lockName)); // 释放锁失败 - } - return; - } - lockEntity.setTimes(lockEntity.getTimes() - 1); - } - } } diff --git a/src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/controller/NotAllowedClickTGSController.java b/src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/controller/NotAllowedClickTGSController.java new file mode 100644 index 0000000..7445e47 --- /dev/null +++ b/src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/controller/NotAllowedClickTGSController.java @@ -0,0 +1,46 @@ +package com.api.youhong.ai.pcn.workflow.doworkflowtomodel.controller; + +import aiyh.utils.ApiResult; +import aiyh.utils.Util; +import com.api.youhong.ai.pcn.workflow.doworkflowtomodel.service.NotAllowedClickTGSService; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; + +/** + *

是否允许当前用户点击targetSetting按钮

+ * + *

create: 2022-12-12 15:36

+ * + * @author youHong.ai + */ + +@Path("/ayh/target-setting/btn") +public class NotAllowedClickTGSController { + + private final NotAllowedClickTGSService service = new NotAllowedClickTGSService(); + + @Path("/can-allowed") + @GET + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) + public String canAllowedClickTGSBtn(@Context HttpServletRequest request, @Context HttpServletResponse response) { + User user = HrmUserVarify.getUser(request, response); + try { + return ApiResult.success(service.canAllowedClickTGSBtn(user)); + } catch (Exception e) { + Util.getLogger().error("get can allowed click target setting button error!\n" + Util.getErrString(e)); + return ApiResult.error("system error!"); + } + + } + +} diff --git a/src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/mapper/NotAllowedClickTGSMapper.java b/src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/mapper/NotAllowedClickTGSMapper.java new file mode 100644 index 0000000..e5b2594 --- /dev/null +++ b/src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/mapper/NotAllowedClickTGSMapper.java @@ -0,0 +1,46 @@ +package com.api.youhong.ai.pcn.workflow.doworkflowtomodel.mapper; + +import aiyh.utils.annotation.recordset.ParamMapper; +import aiyh.utils.annotation.recordset.Select; +import aiyh.utils.annotation.recordset.SqlMapper; + +import java.util.List; + +/** + *

+ * + *

create: 2022-12-12 15:56

+ * + * @author youHong.ai + */ + +@SqlMapper +public interface NotAllowedClickTGSMapper { + + /** + *

根据用户id和当前年份查询个人目标台账主表id

+ * 2022/12/12 17:27 + * ************************************************************ + * + * @param userId 用户id + * @param currentYear 当前年年份 + * @return List 主表id数组 + * @author youHong.ai ****************************************** + */ + @Select("select id from uf_targetsettingdat where sqr = #{userId} and nf = #{currentYear}") + List selectMainIdsByUserIdAndYear(@ParamMapper("userId") Integer userId, + @ParamMapper("currentYear") String currentYear); + + + /** + *

根据主表id查询明细数据

+ * 2022/12/12 17:28 + * ************************************************************ + * + * @param list 主表id数组 + * @return List 明细权重 + * @author youHong.ai ****************************************** + */ + @Select("select qz from uf_targetsettingdat_dt1 where mainid in (${list})") + List selectWeightByMainIds(List list); +} diff --git a/src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/service/NotAllowedClickTGSService.java b/src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/service/NotAllowedClickTGSService.java new file mode 100644 index 0000000..6a4f7b1 --- /dev/null +++ b/src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/service/NotAllowedClickTGSService.java @@ -0,0 +1,47 @@ +package com.api.youhong.ai.pcn.workflow.doworkflowtomodel.service; + +import aiyh.utils.Util; +import com.api.youhong.ai.pcn.workflow.doworkflowtomodel.mapper.NotAllowedClickTGSMapper; +import weaver.hrm.User; + +import java.util.List; +import java.util.Objects; + +/** + *

+ * + *

create: 2022-12-12 15:38

+ * + * @author youHong.ai + */ + +public class NotAllowedClickTGSService { + + + private final NotAllowedClickTGSMapper mapper = Util.getMapper(NotAllowedClickTGSMapper.class); + + /** + *

查询是否可以点击创建targetSetting流程

+ * 2022/12/12 17:29 + * ************************************************************ + * + * @param user 当前登陆用户 + * @return boolean 是否可以点击创建按钮 + * @author youHong.ai ****************************************** + */ + public boolean canAllowedClickTGSBtn(User user) { + List mainIdList = mapper.selectMainIdsByUserIdAndYear(user.getUID(), Util.getTime("yyyy")); + if (Objects.isNull(mainIdList) || mainIdList.isEmpty()) { + return true; + } + List qzList = mapper.selectWeightByMainIds(mainIdList); + if (Objects.isNull(qzList) || qzList.isEmpty()) { + return true; + } + Integer sum = qzList.stream() + .filter(item -> !Util.isNullOrEmpty(item)) + .map(Integer::parseInt) + .reduce(0, Integer::sum); + return sum < 100; + } +} diff --git a/src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/service/TriggerWorkflowToModelService.java b/src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/service/TriggerWorkflowToModelService.java index eafe3f4..15ec446 100644 --- a/src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/service/TriggerWorkflowToModelService.java +++ b/src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/service/TriggerWorkflowToModelService.java @@ -1,7 +1,9 @@ package com.api.youhong.ai.pcn.workflow.doworkflowtomodel.service; import aiyh.utils.Util; +import com.alibaba.fastjson.JSON; import com.api.youhong.ai.pcn.workflow.doworkflowtomodel.mapper.TriggerWorkflowToModelMapper; +import org.apache.log4j.Logger; import weaver.formmode.interfaces.action.WorkflowToMode; import weaver.hrm.User; import weaver.soa.workflow.request.RequestInfo; @@ -26,33 +28,57 @@ public class TriggerWorkflowToModelService { private final RequestService service = new RequestService(); private final TriggerWorkflowToModelMapper mapper = Util.getMapper(TriggerWorkflowToModelMapper.class); + private final Logger log = Util.getLogger(); public String saveTriggerWorkflowToModel(Map params, HttpServletRequest request, User user) { + log.info("request param:" + JSON.toJSONString(params)); String requestId = String.valueOf(params.get("requestId")); String nodeId = String.valueOf(params.get("nodeId")); String isBill = String.valueOf(params.get("isBill")); String formId = String.valueOf(params.get("formId")); String workflowId = String.valueOf(params.get("workflowId")); RequestInfo requestInfo = service.getRequest(Integer.parseInt(requestId)); + requestInfo.setIspreadd("1"); + requestInfo.setWorkflowid(workflowId); RequestManager requestManager = requestInfo.getRequestManager(); requestManager.setRequest(request); requestManager.setUser(user); requestManager.setNodeid(Integer.parseInt(nodeId)); requestManager.setIsbill(Integer.parseInt(isBill)); requestManager.setFormid(Integer.parseInt(formId)); + requestManager.setWorkflowid(Integer.parseInt(workflowId)); WorkflowToMode workflowToMode = new WorkflowToMode(); workflowToMode.setNodeid(Integer.parseInt(nodeId)); + workflowToMode.setIp(getRemoteHost(request)); List actionIds = mapper.selectActionId(nodeId, workflowId); if (Objects.isNull(actionIds) || actionIds.isEmpty()) { return "can not query actionIds;"; } - List failAction = new ArrayList<>(); + List failAction = new ArrayList<>(); for (Integer actionId : actionIds) { workflowToMode.setActionid(actionId); if ("0".equals(workflowToMode.execute(requestInfo))) { - failAction.add(actionId); + failAction.add("[" + actionId + "]: " + requestManager.getMessagecontent() + "\t" + requestManager.getMessage()); } } - return "action execute finish! " + Util.intJoin(failAction, ",") + "execute fail!"; + if (failAction.isEmpty()) { + return "success"; + } + log.error(Util.join(failAction, "\n")); + return "action execute finish! execute fail!"; + } + + private String getRemoteHost(HttpServletRequest request) { + String ip = request.getHeader("x-forwarded-for"); + if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { + ip = request.getHeader("Proxy-Client-IP"); + } + if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { + ip = request.getHeader("WL-Proxy-Client-IP"); + } + if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { + ip = request.getRemoteAddr(); + } + return ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip; } } diff --git a/src/test/java/youhong/ai/pcn/WorkflowTest.java b/src/test/java/youhong/ai/pcn/WorkflowTest.java new file mode 100644 index 0000000..71f6738 --- /dev/null +++ b/src/test/java/youhong/ai/pcn/WorkflowTest.java @@ -0,0 +1,31 @@ +package youhong.ai.pcn; + +import aiyh.utils.Util; +import basetest.BaseTest; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** + *

流程相关测试

+ * + *

create: 2022-12-12 16:13

+ * + * @author youHong.ai + */ + +public class WorkflowTest extends BaseTest { + + @Test + public void test() { + List qzList = new ArrayList<>(); + Collections.addAll(qzList, null, "", "1", "2", "3", "4"); + Integer sum = qzList.stream() + .filter(item -> !Util.isNullOrEmpty(item)) + .map(Integer::parseInt) + .reduce(0, Integer::sum); + System.out.println(sum); + } +} From 1f59f96dace205eede8949b046081fe4afd16572 Mon Sep 17 00:00:00 2001 From: "youHong.ai" <774495953@qq.com> Date: Tue, 13 Dec 2022 15:30:18 +0800 Subject: [PATCH 11/33] =?UTF-8?q?apa=E7=AD=89=E7=BA=A7=E5=B8=A6=E5=87=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../youhong.ai/pcn/workflow_code_block.js | 4 +- src/main/java/aiyh/utils/Util.java | 2 +- .../controller/ApaLevelByScoreController.java | 38 +++++++++++++++++++ .../mapper/ApaLevelByScoreMapper.java | 28 ++++++++++++++ .../service/ApaLevelByScoreService.java | 34 +++++++++++++++++ .../config/service/DealWithMapping.java | 2 +- .../java/youhong/ai/pcn/TestOrganization.java | 13 +++++++ 7 files changed, 118 insertions(+), 3 deletions(-) create mode 100644 src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/controller/ApaLevelByScoreController.java create mode 100644 src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/mapper/ApaLevelByScoreMapper.java create mode 100644 src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/service/ApaLevelByScoreService.java diff --git a/javascript/youhong.ai/pcn/workflow_code_block.js b/javascript/youhong.ai/pcn/workflow_code_block.js index 928b1ee..290ce16 100644 --- a/javascript/youhong.ai/pcn/workflow_code_block.js +++ b/javascript/youhong.ai/pcn/workflow_code_block.js @@ -219,7 +219,10 @@ window.workflowCus = Object.assign(window.workflowCus ? window.workflowCus : {}, } } }) +/* ******************* apa流程通过apa分数字段带出level字段eng ******************* */ + +/* ******************* apa流程通过apa分数字段带出level字段 ******************* */ $(() => { let config = { scoreFiled: "", @@ -228,5 +231,4 @@ $(() => { window.workflowCus.getLevelByScore(config) }) - /* ******************* apa流程通过apa分数字段带出level字段eng ******************* */ diff --git a/src/main/java/aiyh/utils/Util.java b/src/main/java/aiyh/utils/Util.java index d015f2b..12fb320 100644 --- a/src/main/java/aiyh/utils/Util.java +++ b/src/main/java/aiyh/utils/Util.java @@ -3466,7 +3466,7 @@ public class Util extends weaver.general.Util { // "((#(\\{|sql\\{))?([():/\\-$#={ }.\\w\\u4E00-\\u9FA5?]+)?}?)))&?"; String pattern = "&?(?([#.\\w\\u4E00-\\u9FA5]+))=" + "(?(`([^`]*)`|" + - "((#(\\{|sql\\{))?([():/\\-$#={ }.\\w\\u4E00-\\u9FA5?]+)?}?)))&?"; + "((#(\\{|sql\\{))?([():/\\-$_*#={ }.\\w\\u4E00-\\u9FA5?]+)?}?)))&?"; Pattern compile = Pattern.compile(pattern); Matcher matcher = compile.matcher(paramStr); Map pathParamMap = new HashMap<>(8); diff --git a/src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/controller/ApaLevelByScoreController.java b/src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/controller/ApaLevelByScoreController.java new file mode 100644 index 0000000..5476d7c --- /dev/null +++ b/src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/controller/ApaLevelByScoreController.java @@ -0,0 +1,38 @@ +package com.api.youhong.ai.pcn.workflow.doworkflowtomodel.controller; + +import aiyh.utils.ApiResult; +import aiyh.utils.Util; +import com.api.youhong.ai.pcn.workflow.doworkflowtomodel.service.ApaLevelByScoreService; +import org.apache.log4j.Logger; + +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; + +/** + *

通过apa分数获取apalevel

+ * + *

create: 2022-12-13 10:37

+ * + * @author youHong.ai + */ + +@Path("ayh/workflow/apa") +public class ApaLevelByScoreController { + + private final Logger log = Util.getLogger(); + private final ApaLevelByScoreService service = new ApaLevelByScoreService(); + + @Path("/level") + @GET + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) + public String getLevelByScore(@QueryParam("score") Double score) { + try { + Integer level = service.getLevelByScore(score); + return ApiResult.success(level); + } catch (Exception e) { + log.error("get level error \n" + Util.getErrString(e)); + return ApiResult.error("get level error " + e.getMessage()); + } + } +} \ No newline at end of file diff --git a/src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/mapper/ApaLevelByScoreMapper.java b/src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/mapper/ApaLevelByScoreMapper.java new file mode 100644 index 0000000..f011991 --- /dev/null +++ b/src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/mapper/ApaLevelByScoreMapper.java @@ -0,0 +1,28 @@ +package com.api.youhong.ai.pcn.workflow.doworkflowtomodel.mapper; + +import aiyh.utils.annotation.recordset.Select; +import aiyh.utils.annotation.recordset.SqlMapper; + +/** + *

+ * + *

create: 2022-12-13 10:42

+ * + * @author youHong.ai + */ + +@SqlMapper +public interface ApaLevelByScoreMapper { + + /** + *

通过apa分数查询对应的分数等级

+ * 2022/12/13 10:47 + * ************************************************************ + * + * @param score 分数 + * @return Integer 当前分数对应的等级 + * @author youHong.ai ****************************************** + */ + @Select("select level1 from uf_APAlevel where #{score} between zdf and zgf") + Integer selectLevelByScore(Double score); +} diff --git a/src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/service/ApaLevelByScoreService.java b/src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/service/ApaLevelByScoreService.java new file mode 100644 index 0000000..8302ceb --- /dev/null +++ b/src/main/java/com/api/youhong/ai/pcn/workflow/doworkflowtomodel/service/ApaLevelByScoreService.java @@ -0,0 +1,34 @@ +package com.api.youhong.ai.pcn.workflow.doworkflowtomodel.service; + +import aiyh.utils.Util; +import aiyh.utils.excention.CustomerException; +import com.api.youhong.ai.pcn.workflow.doworkflowtomodel.mapper.ApaLevelByScoreMapper; + +/** + *

+ * + *

create: 2022-12-13 10:40

+ * + * @author youHong.ai + */ + +public class ApaLevelByScoreService { + private final ApaLevelByScoreMapper mapper = Util.getMapper(ApaLevelByScoreMapper.class); + + /** + *

根据分数查询等级

+ * 2022/12/13 10:55 + * ************************************************************ + * + * @param score 分数 + * @return Integer 等级 + * @author youHong.ai ****************************************** + */ + public Integer getLevelByScore(Double score) { + Integer level = mapper.selectLevelByScore(score); + if (level < -1) { + throw new CustomerException("query level error, score is [" + score + ""); + } + return level; + } +} diff --git a/src/main/java/weaver/xiao/commons/config/service/DealWithMapping.java b/src/main/java/weaver/xiao/commons/config/service/DealWithMapping.java index 14c5946..d64a447 100644 --- a/src/main/java/weaver/xiao/commons/config/service/DealWithMapping.java +++ b/src/main/java/weaver/xiao/commons/config/service/DealWithMapping.java @@ -1378,7 +1378,7 @@ public class DealWithMapping extends ToolUtil { // 最终通过反射调用weaver.aiyh_jitu.pushdata.service.GetAssignProcessorProcessorImpl类,将参数传递给这个类, 使用``包裹的字符串会被解析为一个字符串 String pattern = "&?(?([#.\\w\\u4E00-\\u9FA5]+))=" + "(?((`([^`]*)`)|" + - "((#(\\{|sql\\{))?([():/\\-$#={ }.\\w\\u4E00-\\u9FA5?]+)?}?)))&?"; + "((#(\\{|sql\\{))?([():/\\-$_#={ }.\\w\\u4E00-\\u9FA5?]+)?}?)))&?"; Pattern compile = Pattern.compile(pattern); Matcher matcher = compile.matcher(paramStr); while (matcher.find()) { diff --git a/src/test/java/youhong/ai/pcn/TestOrganization.java b/src/test/java/youhong/ai/pcn/TestOrganization.java index cae7065..3c6f640 100644 --- a/src/test/java/youhong/ai/pcn/TestOrganization.java +++ b/src/test/java/youhong/ai/pcn/TestOrganization.java @@ -124,6 +124,19 @@ public class TestOrganization extends BaseTest { //String paramValue = matcher.group("value"); //System.out.println(paramValue); //} + String pattern = "&?(?([#.\\w\\u4E00-\\u9FA5]+))=" + + "(?((`([^`]*)`)|" + + "((#(\\{|sql\\{))?([():/\\-$_#={ }.\\w\\u4E00-\\u9FA5?]+)?}?)))&?"; + Pattern compile = Pattern.compile(pattern); + Matcher matcher = compile.matcher(testStr); + while (matcher.find()) { + String key = matcher.group("key"); + String paramValue = matcher.group("value"); + System.out.println(key); + System.out.println(paramValue); + if (paramValue != null && paramValue.startsWith("`") && paramValue.endsWith("`")) { + } + } } From 3a2234cbcce1a00a85290287c841629503ce80bf Mon Sep 17 00:00:00 2001 From: "youHong.ai" <774495953@qq.com> Date: Tue, 13 Dec 2022 15:43:15 +0800 Subject: [PATCH 12/33] =?UTF-8?q?=E8=B7=AF=E5=BE=84=E5=8F=82=E6=95=B0?= =?UTF-8?q?=E8=8E=B7=E5=8F=96=EF=BC=9Fbug=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/aiyh/utils/Util.java | 2 +- .../weaver/xiao/commons/config/service/DealWithMapping.java | 2 +- src/test/java/youhong/ai/pcn/TestOrganization.java | 5 ++++- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/main/java/aiyh/utils/Util.java b/src/main/java/aiyh/utils/Util.java index 12fb320..22e6544 100644 --- a/src/main/java/aiyh/utils/Util.java +++ b/src/main/java/aiyh/utils/Util.java @@ -3432,7 +3432,7 @@ public class Util extends weaver.general.Util { String classPath = split[0]; String paramStr = ""; if (split.length > 1) { - paramStr = Arrays.stream(split).skip(1).collect(Collectors.joining("")); + paramStr = Arrays.stream(split).skip(1).collect(Collectors.joining("?")); } /* 获取?后的参数:"weaver.aiyh_jitu.pushdata.service.toones.GetRequestValueCusGetValueImpl?" + "requestType=get&apiOnlyMark=getAssign&valueKey=data&assign=#{main.zd2}&" + diff --git a/src/main/java/weaver/xiao/commons/config/service/DealWithMapping.java b/src/main/java/weaver/xiao/commons/config/service/DealWithMapping.java index d64a447..ebc7b22 100644 --- a/src/main/java/weaver/xiao/commons/config/service/DealWithMapping.java +++ b/src/main/java/weaver/xiao/commons/config/service/DealWithMapping.java @@ -1347,7 +1347,7 @@ public class DealWithMapping extends ToolUtil { String classPath = split[0]; String paramStr = ""; if (split.length > 1) { - paramStr = Arrays.stream(split).skip(1).collect(Collectors.joining("")); + paramStr = Arrays.stream(split).skip(1).collect(Collectors.joining("?")); } /* 获取?后的参数:"weaver.aiyh_jitu.pushdata.service.toones.GetRequestValueCusGetValueImpl?" + "requestType=get&apiOnlyMark=getAssign&valueKey=data&assign=#{main.zd2}&" + diff --git a/src/test/java/youhong/ai/pcn/TestOrganization.java b/src/test/java/youhong/ai/pcn/TestOrganization.java index 3c6f640..07921f2 100644 --- a/src/test/java/youhong/ai/pcn/TestOrganization.java +++ b/src/test/java/youhong/ai/pcn/TestOrganization.java @@ -109,8 +109,11 @@ public class TestOrganization extends BaseTest { @Test public void testStaticLog() { log.info("哈哈哈好的方式"); - String testStr = "slflas.fasjdflaf.fasdf?hah=liuliu&cus=`select? * fr$%&#@!)(<>?/\\{}「」【【】[]~、asfom table where id = '' and teset = #{name}`&niua=卧槽"; + String testStr = "weaver.xuanran.wang.schroeder.cus_field_value.PushSealTaskSealValue?sealSnField=sealSn&sealNumField=sealNum&sealSnCusSql=`select\n" + + "? from jkfdjsfk where id\n" + + "=1`&sealNumCusSql=`select case ? when 0 then htzyzcs when 1 then gzcs else frzcs end from formtable_main_22_dt1 where id = {?dt.id}`&cus=`select * from table id = ? and test = ?`"; Map stringStringMap = Util.parseCusInterfacePathParam(testStr); + System.out.println(stringStringMap); System.out.println(JSON.toJSONString(stringStringMap)); //String pattern = "&?(?([#.\\w\\u4E00-\\u9FA5]+))=" + // "(?(`([():/\\-&$#='*{ }.\\w\\u4E00-\\u9FA5?]*)`|((#(\\{|sql\\{))?([():/\\-$#={ }.\\w\\u4E00-\\u9FA5?]+)?}?)))&?"; From 0dde57349dd90ac4bd7b69d07b02fc8fb7568aef Mon Sep 17 00:00:00 2001 From: "youHong.ai" <774495953@qq.com> Date: Tue, 13 Dec 2022 16:13:25 +0800 Subject: [PATCH 13/33] =?UTF-8?q?=E5=AD=97=E7=AC=A6=E4=B8=B2=E6=A0=BC?= =?UTF-8?q?=E5=BC=8F=E5=8C=96=E8=BE=93=E5=87=BA=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/aiyh/utils/Util.java | 25 +++++++++++-------- .../aiyh/utils/httpUtil/util/HttpUtils.java | 22 ++++++++++------ .../java/youhong/ai/pcn/TestOrganization.java | 8 ++++-- 3 files changed, 36 insertions(+), 19 deletions(-) diff --git a/src/main/java/aiyh/utils/Util.java b/src/main/java/aiyh/utils/Util.java index 22e6544..962df09 100644 --- a/src/main/java/aiyh/utils/Util.java +++ b/src/main/java/aiyh/utils/Util.java @@ -3072,20 +3072,25 @@ public class Util extends weaver.general.Util { Matcher matcher = compile.matcher(logStr); int n = 0; while (matcher.find()) { + if (n + 1 > args.length) { + break; + } logStr = logStr.replaceFirst(pattern, "{" + n++ + "}"); } - Object arg = args[args.length - 1]; - if (arg instanceof Throwable) { - for (int i = 0; i < args.length - 1; i++) { - pattern = "\\{" + i + "}"; - logStr = logStr.replaceFirst(pattern, String.valueOf(args[i].toString())); + try { + Object arg = args[args.length - 1]; + if (arg instanceof Throwable) { + for (int i = 0; i < args.length - 1; i++) { + pattern = "\\{" + i + "}"; + logStr = logStr.replaceFirst(pattern, String.valueOf(args[i])); + } + return logStr + "\n" + getErrString((Throwable) arg); } - return logStr + "\n" + getErrString((Throwable) arg); + } catch (Exception ignore) { } - int i = 0; - for (Object o : args) { - pattern = "\\{" + i++ + "}"; - logStr = logStr.replaceFirst(pattern, String.valueOf(o)); + for (int i = 0; i < args.length; i++) { + pattern = "\\{" + i + "}"; + logStr = logStr.replaceFirst(pattern, String.valueOf(args[i])); } return logStr; } catch (Exception e) { diff --git a/src/main/java/aiyh/utils/httpUtil/util/HttpUtils.java b/src/main/java/aiyh/utils/httpUtil/util/HttpUtils.java index 2c3e946..6ea581f 100644 --- a/src/main/java/aiyh/utils/httpUtil/util/HttpUtils.java +++ b/src/main/java/aiyh/utils/httpUtil/util/HttpUtils.java @@ -121,11 +121,11 @@ public class HttpUtils { String str = sqlBuilder.toString().trim(); String removeSeparator = "&"; if (str.endsWith(removeSeparator)) { -// 如果以分&号结尾,则去除&号 + // 如果以分&号结尾,则去除&号 str = str.substring(0, str.length() - 1); } if (str.trim().startsWith(removeSeparator)) { -// 如果以&开头,则去除& + // 如果以&开头,则去除& str = str.substring(1); } return str; @@ -991,7 +991,7 @@ public class HttpUtils { nvps.add(new BasicNameValuePair(entry.getKey(), JSON.toJSONString(entry.getValue()))); } httpPost.setEntity(new UrlEncodedFormEntity(nvps)); -// } else if (contentType.toUpperCase().startsWith(HttpArgsType.APPLICATION_JSON.toUpperCase())) { + // } else if (contentType.toUpperCase().startsWith(HttpArgsType.APPLICATION_JSON.toUpperCase())) { } else { StringEntity stringEntity; if (params.containsKey(JSON_PARAM_KEY)) { @@ -1020,8 +1020,12 @@ public class HttpUtils { */ private HttpPost uploadFileByInputStream(String url, List multipartFileList, Map params, Map headers) { - log.info(Util.logStr("start request : url is [{}]" + - "", url)); + log.info(Util.logStr("start request : url is [{}],other param [\n{}\n],heard [\n{}\n]", url, JSONObject.toJSONString(params, + SerializerFeature.PrettyFormat, + SerializerFeature.WriteDateUseDateFormat), + JSONObject.toJSONString(headers, + SerializerFeature.PrettyFormat, + SerializerFeature.WriteDateUseDateFormat))); HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo(); httpUtilParamInfo.setParams(params); httpUtilParamInfo.setUrl(url); @@ -1069,8 +1073,12 @@ public class HttpUtils { */ private HttpPut uploadFileByInputStreamPut(String url, List multipartFileList, Map params, Map headers) { - log.info(Util.logStr("start request : url is [{}]" + - "", url)); + log.info(Util.logStr("start request : url is [{}],other param [\n{}\n],heard [\n{}\n]", url, JSONObject.toJSONString(params, + SerializerFeature.PrettyFormat, + SerializerFeature.WriteDateUseDateFormat), + JSONObject.toJSONString(headers, + SerializerFeature.PrettyFormat, + SerializerFeature.WriteDateUseDateFormat))); HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo(); httpUtilParamInfo.setParams(params); httpUtilParamInfo.setUrl(url); diff --git a/src/test/java/youhong/ai/pcn/TestOrganization.java b/src/test/java/youhong/ai/pcn/TestOrganization.java index 07921f2..81c4f3b 100644 --- a/src/test/java/youhong/ai/pcn/TestOrganization.java +++ b/src/test/java/youhong/ai/pcn/TestOrganization.java @@ -110,8 +110,8 @@ public class TestOrganization extends BaseTest { public void testStaticLog() { log.info("哈哈哈好的方式"); String testStr = "weaver.xuanran.wang.schroeder.cus_field_value.PushSealTaskSealValue?sealSnField=sealSn&sealNumField=sealNum&sealSnCusSql=`select\n" + - "? from jkfdjsfk where id\n" + - "=1`&sealNumCusSql=`select case ? when 0 then htzyzcs when 1 then gzcs else frzcs end from formtable_main_22_dt1 where id = {?dt.id}`&cus=`select * from table id = ? and test = ?`"; + " ? from jkfdjsfk where id\n" + + " =1`&sealNumCusSql=`select case ? when 0 then htzyzcs when 1 then gzcs else frzcs end from formtable_main_22_dt1 where id = {?dt.id}`&hah=liuliu&cus=`select? * fr$%&#@!)(<>?/\\{}「」【【】[]~、asfom table where id = '' and teset = #{name}`&niua=卧槽"; Map stringStringMap = Util.parseCusInterfacePathParam(testStr); System.out.println(stringStringMap); System.out.println(JSON.toJSONString(stringStringMap)); @@ -140,7 +140,11 @@ public class TestOrganization extends BaseTest { if (paramValue != null && paramValue.startsWith("`") && paramValue.endsWith("`")) { } } + } + @Test + public void testLogStr() { + System.out.println(Util.logStr("ajsdf {} jasjdf {}", "asf", "asdfeag")); } @Test From 8b55a4bd64dc9b7869830bbd0edd346d62060174 Mon Sep 17 00:00:00 2001 From: "youHong.ai" <774495953@qq.com> Date: Tue, 13 Dec 2022 16:55:52 +0800 Subject: [PATCH 14/33] =?UTF-8?q?=E5=AD=97=E7=AC=A6=E4=B8=B2=E6=A0=BC?= =?UTF-8?q?=E5=BC=8F=E5=8C=96=E8=BE=93=E5=87=BA=E4=BF=AE=E5=A4=8D,?= =?UTF-8?q?=E6=9B=BF=E6=8D=A2$=E5=BC=95=E5=8F=91=E7=9A=84Illegal=20group?= =?UTF-8?q?=20reference=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/aiyh/utils/Util.java | 4 ++-- src/test/java/youhong/ai/pcn/TestOrganization.java | 3 ++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/main/java/aiyh/utils/Util.java b/src/main/java/aiyh/utils/Util.java index 962df09..9e9a5dc 100644 --- a/src/main/java/aiyh/utils/Util.java +++ b/src/main/java/aiyh/utils/Util.java @@ -3082,7 +3082,7 @@ public class Util extends weaver.general.Util { if (arg instanceof Throwable) { for (int i = 0; i < args.length - 1; i++) { pattern = "\\{" + i + "}"; - logStr = logStr.replaceFirst(pattern, String.valueOf(args[i])); + logStr = logStr.replaceFirst(pattern, Matcher.quoteReplacement(String.valueOf(args[i]))); } return logStr + "\n" + getErrString((Throwable) arg); } @@ -3090,7 +3090,7 @@ public class Util extends weaver.general.Util { } for (int i = 0; i < args.length; i++) { pattern = "\\{" + i + "}"; - logStr = logStr.replaceFirst(pattern, String.valueOf(args[i])); + logStr = logStr.replaceFirst(pattern, Matcher.quoteReplacement(String.valueOf(args[i]))); } return logStr; } catch (Exception e) { diff --git a/src/test/java/youhong/ai/pcn/TestOrganization.java b/src/test/java/youhong/ai/pcn/TestOrganization.java index 81c4f3b..dd9f2a5 100644 --- a/src/test/java/youhong/ai/pcn/TestOrganization.java +++ b/src/test/java/youhong/ai/pcn/TestOrganization.java @@ -144,7 +144,8 @@ public class TestOrganization extends BaseTest { @Test public void testLogStr() { - System.out.println(Util.logStr("ajsdf {} jasjdf {}", "asf", "asdfeag")); + System.out.println(Util.logStr("ajsdf {} jasjdf {}", "{\"cus\":\"select? * fr$%&#@!)(<>?/\\\\「」【【】[]~、asfom table where id = '' and teset = #{name}\",\"sealSnCusSql\":\"select \\n? from jkfdjsfk where id \\n=1\",\"niua\":\"卧槽\",\"sealSnField\":\"sealSn\",\"sealNumField\":\"sealNum\",\"sealNumCusSql\":\"select case ? when 0 then htzyzcs when 1 then gzcs else frzcs end from formtable_main_22_dt1 where id = {?dt.id}\",\"hah\":\"liuliu\"} ")); + System.out.println("{0} {} ".replaceFirst("\\{0}", Matcher.quoteReplacement("{\"cus\":\"select? * fr$%&#@!)(<>?/\\\\「」【【】[]~、asfom table where id = '' and teset = #{name}\",\"sealSnCusSql\":\"select \\n? from jkfdjsfk where id \\n=1\",\"niua\":\"卧槽\",\"sealSnField\":\"sealSn\",\"sealNumField\":\"sealNum\",\"sealNumCusSql\":\"select case ? when 0 then htzyzcs when 1 then gzcs else frzcs end from formtable_main_22_dt1 where id = {?dt.id}\",\"hah\":\"liuliu\"} "))); } @Test From 4170596ba1ddb4c276edc5339bbbfc4b5b2fa1f1 Mon Sep 17 00:00:00 2001 From: "youHong.ai" <774495953@qq.com> Date: Tue, 13 Dec 2022 17:38:15 +0800 Subject: [PATCH 15/33] =?UTF-8?q?=E4=BF=AE=E6=94=B9action=E6=A8=A1?= =?UTF-8?q?=E6=9D=BF=E6=96=B9=E6=B3=95=EF=BC=8C=E8=A7=A3=E5=86=B3=E6=BD=9C?= =?UTF-8?q?=E5=9C=A8=E7=9A=84=E7=BA=BF=E7=A8=8B=E4=B8=8D=E5=AE=89=E5=85=A8?= =?UTF-8?q?=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/aiyh/utils/action/CusBaseAction.java | 35 +-- .../action/CusBaseActionHandleFunction.java | 1 + .../aiyh/utils/action/SafeCusBaseAction.java | 288 ++++++++++++++++++ .../SafeCusBaseActionHandleFunction.java | 26 ++ 4 files changed, 331 insertions(+), 19 deletions(-) create mode 100644 src/main/java/aiyh/utils/action/SafeCusBaseAction.java create mode 100644 src/main/java/aiyh/utils/action/SafeCusBaseActionHandleFunction.java diff --git a/src/main/java/aiyh/utils/action/CusBaseAction.java b/src/main/java/aiyh/utils/action/CusBaseAction.java index 9b114a6..47ff1f2 100644 --- a/src/main/java/aiyh/utils/action/CusBaseAction.java +++ b/src/main/java/aiyh/utils/action/CusBaseAction.java @@ -19,6 +19,7 @@ import java.util.*; * * @author EBU7-dev-1 aiyh */ +@Deprecated public abstract class CusBaseAction implements Action { @@ -36,13 +37,13 @@ public abstract class CusBaseAction implements Action { *

初始化流程默认的处理方法

*/ private void initHandleMethod() { -// 提交 + // 提交 actionHandleMethod.put(ActionRunType.SUBMIT, this::doSubmit); -// 退回 + // 退回 actionHandleMethod.put(ActionRunType.REJECT, this::doReject); -// 撤回 + // 撤回 actionHandleMethod.put(ActionRunType.WITHDRAW, this::doWithdraw); -// 强制收回 + // 强制收回 actionHandleMethod.put(ActionRunType.DRAW_BACK, this::doDrawBack); } @@ -55,7 +56,7 @@ public abstract class CusBaseAction implements Action { String requestId = requestInfo.getRequestid(); User user = requestInfo.getRequestManager().getUser(); int workflowId = requestManager.getWorkflowid(); -// 操作类型 submit - 提交 reject - 退回 等 + // 操作类型 submit - 提交 reject - 退回 等 String src = requestManager.getSrc(); if ("".equals(billTable)) { WorkflowComInfo workflowComInfo = new WorkflowComInfo(); @@ -68,13 +69,13 @@ public abstract class CusBaseAction implements Action { if (StringUtils.isEmpty(src)) { src = "submit"; } -// 初始化默认的流程处理方法 + // 初始化默认的流程处理方法 initHandleMethod(); -// 提供自定义注册处理方法 + // 提供自定义注册处理方法 registerHandler(actionHandleMethod); -// 获取流程对应的处理方法 + // 获取流程对应的处理方法 CusBaseActionHandleFunction cusBaseActionHandleFunction = actionHandleMethod.get(src); -// 默认没有直接成功不做拦截 + // 默认没有直接成功不做拦截 if (null == cusBaseActionHandleFunction) { return Action.SUCCESS; } @@ -124,8 +125,7 @@ public abstract class CusBaseAction implements Action { /** *

action 提交流程业务处理方法

*

具体业务逻辑实现 - * 全局存在log成员变量,用于日志的输出 - * Util.actionFailException(requestManager,"error msg"); 用于提示action执行失败 + * 全局存在log成员变量,用于日志的输出 Util.actionFailException(requestManager,"error msg"); 用于提示action执行失败 *

* * @param requestId 流程请求ID @@ -142,8 +142,7 @@ public abstract class CusBaseAction implements Action { /** *

action 退回流程业务处理方法

*

具体业务逻辑实现 - * 全局存在log成员变量,用于日志的输出 - * Util.actionFailException(requestManager,"error msg"); 用于提示action执行失败 + * 全局存在log成员变量,用于日志的输出 Util.actionFailException(requestManager,"error msg"); 用于提示action执行失败 *

* * @param requestId 流程请求ID @@ -159,8 +158,7 @@ public abstract class CusBaseAction implements Action { /** *

action 撤回、撤回流程流程业务处理方法

*

具体业务逻辑实现 - * 全局存在log成员变量,用于日志的输出 - * Util.actionFailException(requestManager,"error msg"); 用于提示action执行失败 + * 全局存在log成员变量,用于日志的输出 Util.actionFailException(requestManager,"error msg"); 用于提示action执行失败 *

* * @param requestId 流程请求ID @@ -177,8 +175,7 @@ public abstract class CusBaseAction implements Action { /** *

action 强制收回流程业务处理方法

*

具体业务逻辑实现 - * 全局存在log成员变量,用于日志的输出 - * Util.actionFailException(requestManager,"error msg"); 用于提示action执行失败 + * 全局存在log成员变量,用于日志的输出 Util.actionFailException(requestManager,"error msg"); 用于提示action执行失败 *

* * @param requestId 流程请求ID @@ -199,7 +196,7 @@ public abstract class CusBaseAction implements Action { */ @Deprecated protected Map getMainTableValue() { -// 获取主表数据 + // 获取主表数据 Property[] propertyArr = globalRequestInfo.getMainTableInfo().getProperty(); return getStringMap(propertyArr); } @@ -210,7 +207,7 @@ public abstract class CusBaseAction implements Action { * @return 流程主表数据 */ protected Map getMainTableValue(RequestInfo requestInfo) { -// 获取主表数据 + // 获取主表数据 Property[] propertyArr = requestInfo.getMainTableInfo().getProperty(); return getStringMap(propertyArr); } diff --git a/src/main/java/aiyh/utils/action/CusBaseActionHandleFunction.java b/src/main/java/aiyh/utils/action/CusBaseActionHandleFunction.java index 1a8b86a..ac80efc 100644 --- a/src/main/java/aiyh/utils/action/CusBaseActionHandleFunction.java +++ b/src/main/java/aiyh/utils/action/CusBaseActionHandleFunction.java @@ -10,6 +10,7 @@ import weaver.workflow.request.RequestManager; *

create: 2022-07-23 18:05

*/ +@Deprecated @FunctionalInterface public interface CusBaseActionHandleFunction { /** diff --git a/src/main/java/aiyh/utils/action/SafeCusBaseAction.java b/src/main/java/aiyh/utils/action/SafeCusBaseAction.java new file mode 100644 index 0000000..c638269 --- /dev/null +++ b/src/main/java/aiyh/utils/action/SafeCusBaseAction.java @@ -0,0 +1,288 @@ +package aiyh.utils.action; + +import aiyh.utils.Util; +import aiyh.utils.excention.CustomerException; +import org.apache.commons.lang3.StringUtils; +import org.apache.log4j.Logger; +import org.jetbrains.annotations.NotNull; +import weaver.hrm.User; +import weaver.interfaces.workflow.action.Action; +import weaver.soa.workflow.request.*; +import weaver.workflow.request.RequestManager; +import weaver.workflow.workflow.WorkflowBillComInfo; +import weaver.workflow.workflow.WorkflowComInfo; + +import java.util.*; + +/** + *

基础的action,实现一些基础的参数

+ * + * @author EBU7-dev-1 aiyh + */ +public abstract class SafeCusBaseAction implements Action { + + + /** + * 全局日志对象 + */ + protected final Logger log = Util.getLogger(); + private final Map actionHandleMethod = new HashMap<>(); + + /** + *

初始化流程默认的处理方法

+ */ + private void initHandleMethod() { + // 提交 + actionHandleMethod.put(ActionRunType.SUBMIT, this::doSubmit); + // 退回 + actionHandleMethod.put(ActionRunType.REJECT, this::doReject); + // 撤回 + actionHandleMethod.put(ActionRunType.WITHDRAW, this::doWithdraw); + // 强制收回 + actionHandleMethod.put(ActionRunType.DRAW_BACK, this::doDrawBack); + } + + + @Override + public final String execute(RequestInfo requestInfo) { + RequestManager requestManager = requestInfo.getRequestManager(); + String billTable = requestManager.getBillTableName(); + String requestId = requestInfo.getRequestid(); + User user = requestInfo.getRequestManager().getUser(); + int workflowId = requestManager.getWorkflowid(); + // 操作类型 submit - 提交 reject - 退回 等 + String src = requestManager.getSrc(); + if ("".equals(billTable)) { + WorkflowComInfo workflowComInfo = new WorkflowComInfo(); + String formId = workflowComInfo.getFormId(String.valueOf(workflowId)); + WorkflowBillComInfo workflowBillComInfo = new WorkflowBillComInfo(); + billTable = workflowBillComInfo.getTablename(formId); + } + try { + Util.verifyRequiredField(this); + if (StringUtils.isEmpty(src)) { + src = "submit"; + } + // 初始化默认的流程处理方法 + initHandleMethod(); + // 提供自定义注册处理方法 + registerHandler(actionHandleMethod); + // 获取流程对应的处理方法 + SafeCusBaseActionHandleFunction cusBaseActionHandleFunction = actionHandleMethod.get(src); + // 默认没有直接成功不做拦截 + if (null == cusBaseActionHandleFunction) { + return Action.SUCCESS; + } + cusBaseActionHandleFunction.handle(requestId, billTable, workflowId, user, requestInfo); + } catch (CustomerException e) { + if (e.getCode() != null && e.getCode() == 500) { + Util.actionFail(requestManager, e.getMessage()); + return Action.FAILURE_AND_CONTINUE; + } + if (this.exceptionCallback(e, requestManager)) { + return Action.FAILURE_AND_CONTINUE; + } + } catch (Exception e) { + if (this.exceptionCallback(e, requestManager)) { + return Action.FAILURE_AND_CONTINUE; + } + } + return Action.SUCCESS; + } + + + /** + *

程序执行异常回调

+ * + * @param e 异常信息 + * @param requestManager requestManager对象 + * @return 是否阻止action往下提交,true- 阻止, false-放行 + */ + public boolean exceptionCallback(Exception e, RequestManager requestManager) { + e.printStackTrace(); + log.error(Util.logStr("getDataId action fail, exception message is [{}], error stack trace msg is: \n{}", + e.getMessage(), Util.getErrString(e))); + Util.actionFail(requestManager, e.getMessage()); + return true; + } + + + /** + *

流程其他流转类型处理方法注册

+ * + * @param actionHandleMethod 处理方法对应map + */ + public void registerHandler(Map actionHandleMethod) { + } + + + /** + *

action 提交流程业务处理方法

+ *

具体业务逻辑实现 + * 全局存在log成员变量,用于日志的输出 Util.actionFailException(requestManager,"error msg"); 用于提示action执行失败 + *

+ * + * @param requestId 流程请求ID + * @param billTable 流程对应主表名称 + * @param workflowId 流程对应流程ID + * @param user 当前节点操作者用户 + * @param requestInfo 请求管理对象 + */ + + public abstract void doSubmit(String requestId, String billTable, int workflowId, + User user, RequestInfo requestInfo); + + + /** + *

action 退回流程业务处理方法

+ *

具体业务逻辑实现 + * 全局存在log成员变量,用于日志的输出 Util.actionFailException(requestManager,"error msg"); 用于提示action执行失败 + *

+ * + * @param requestId 流程请求ID + * @param billTable 流程对应主表名称 + * @param workflowId 流程对应流程ID + * @param user 当前节点操作者用户 + * @param requestInfo 请求管理对象 + */ + public void doReject(String requestId, String billTable, int workflowId, + User user, RequestInfo requestInfo) { + } + + /** + *

action 撤回、撤回流程流程业务处理方法

+ *

具体业务逻辑实现 + * 全局存在log成员变量,用于日志的输出 Util.actionFailException(requestManager,"error msg"); 用于提示action执行失败 + *

+ * + * @param requestId 流程请求ID + * @param billTable 流程对应主表名称 + * @param workflowId 流程对应流程ID + * @param user 当前节点操作者用户 + * @param requestInfo 请求管理对象 + */ + public void doWithdraw(String requestId, String billTable, int workflowId, + User user, RequestInfo requestInfo) { + } + + + /** + *

action 强制收回流程业务处理方法

+ *

具体业务逻辑实现 + * 全局存在log成员变量,用于日志的输出 Util.actionFailException(requestManager,"error msg"); 用于提示action执行失败 + *

+ * + * @param requestId 流程请求ID + * @param billTable 流程对应主表名称 + * @param workflowId 流程对应流程ID + * @param user 当前节点操作者用户 + * @param requestInfo 请求管理对象 + */ + public void doDrawBack(String requestId, String billTable, int workflowId, + User user, RequestInfo requestInfo) { + } + + /** + *

获取流程主表数据

+ * + * @return 流程主表数据 + */ + protected Map getMainTableValue(RequestInfo requestInfo) { + // 获取主表数据 + Property[] propertyArr = requestInfo.getMainTableInfo().getProperty(); + return getStringMap(propertyArr); + } + + @NotNull + private Map getStringMap(Property[] propertyArr) { + if (null == propertyArr) { + return Collections.emptyMap(); + } + Map mainTable = new HashMap<>((int) Math.ceil(propertyArr.length * 1.4)); + for (Property property : propertyArr) { + String fieldName = property.getName(); + String value = property.getValue(); + mainTable.put(fieldName, value); + } + return mainTable; + } + + + /** + *

获取所有明细数据

+ * + * @return 以明细表需要为键,以明细表数据为值的键值对明细数据信息 + */ + protected Map>> getDetailTableValue(RequestInfo requestInfo) { + DetailTable[] detailTableArr = requestInfo.getDetailTableInfo().getDetailTable(); + return getListMap(detailTableArr); + } + + + @NotNull + private Map>> getListMap(DetailTable[] detailTableArr) { + Map>> detailDataList = new HashMap<>((int) Math.ceil(detailTableArr.length * 1.4)); + for (DetailTable detailTable : detailTableArr) { + List> detailData = getDetailValue(detailTable); + detailDataList.put(detailTable.getId(), detailData); + } + return detailDataList; + } + + + /** + *

获取指定明细表的表数据

+ * + * @param detailNo 明细表编号 + * @return 明细数据 + */ + protected List> getDetailTableValueByDetailNo(int detailNo, RequestInfo requestInfo) { + DetailTable detailTable = requestInfo.getDetailTableInfo().getDetailTable(detailNo); + return getDetailValue(detailTable); + } + + /** + *

根据明细表信息获取明细表数据

+ * + * @param detailTable 明细表对象 + * @return 明细表数据 + */ + @NotNull + private List> getDetailValue(DetailTable detailTable) { + Row[] rowArr = detailTable.getRow(); + List> detailData = new ArrayList<>(rowArr.length); + for (Row row : rowArr) { + Cell[] cellArr = row.getCell(); + Map rowData = new HashMap<>((int) Math.ceil(cellArr.length * (1 + 0.4))); + rowData.put("id", row.getId()); + for (Cell cell : cellArr) { + String fieldName = cell.getName(); + String value = cell.getValue(); + rowData.put(fieldName, value); + } + detailData.add(rowData); + } + return detailData; + } + + + public static final class ActionRunType { + /** + * 退回 + */ + public static final String REJECT = "reject"; + /** + * 撤回 + */ + public static final String WITHDRAW = "withdraw"; + /** + * 强制收回 + */ + public static final String DRAW_BACK = "drawBack"; + /** + * 提交 + */ + public static final String SUBMIT = "submit"; + } + +} diff --git a/src/main/java/aiyh/utils/action/SafeCusBaseActionHandleFunction.java b/src/main/java/aiyh/utils/action/SafeCusBaseActionHandleFunction.java new file mode 100644 index 0000000..4785ab1 --- /dev/null +++ b/src/main/java/aiyh/utils/action/SafeCusBaseActionHandleFunction.java @@ -0,0 +1,26 @@ +package aiyh.utils.action; + +import weaver.hrm.User; +import weaver.soa.workflow.request.RequestInfo; + +/** + *

流程类型处理方法

+ * + * @author EBU7-dev-1 aiyh + *

create: 2022-07-23 18:05

+ */ + +@FunctionalInterface +public interface SafeCusBaseActionHandleFunction { + /** + *

流程处理方法action

+ * + * @param requestId 流程请求ID + * @param billTable 流程对应主表名称 + * @param workflowId 流程对应流程ID + * @param user 当前节点操作者用户 + * @param requestInfo 请求管理对象 + */ + void handle(String requestId, String billTable, int workflowId, + User user, RequestInfo requestInfo); +} From 1654d4f765dfceeccde791647510df034d4b2d7c Mon Sep 17 00:00:00 2001 From: wangxuanran <3055088966@qq.com> Date: Tue, 13 Dec 2022 18:03:24 +0800 Subject: [PATCH 16/33] =?UTF-8?q?=E4=BC=98=E5=8C=96CusBaseAction=E4=BB=A5?= =?UTF-8?q?=E5=8F=8A=E6=96=BD=E7=BD=97=E5=BE=B7=E4=BB=A3=E7=A0=81=E5=AE=8C?= =?UTF-8?q?=E5=96=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/aiyh/utils/action/CusBaseAction.java | 8 + .../controller/CheckUserController.java | 59 +++++++ .../checkuser/service/CheckUserService.java | 149 ++++++++++++++++++ .../service/DownLoadFileService.java | 2 +- .../wang/common/util/CusInfoToOAUtil.java | 28 +++- .../schroeder/action/PushSealTaskAction.java | 40 ++++- .../PushSealTaskSealValue.java | 3 +- .../schroeder/mapper/SchroederMapper.java | 45 ++++++ .../service/SchroederQRCodeService.java | 58 ++++++- src/main/resources/META-INF/MANIFEST.MF | 3 + .../prop/prop2map/AmbofoADConfig.properties | 7 + .../wang/ambofo/checkuser/CheckUserTest.java | 27 ++++ .../download_file/DownLoadFileTest.java | 81 +++++++++- 13 files changed, 502 insertions(+), 8 deletions(-) create mode 100644 src/main/java/com/api/xuanran/wang/ambofo/checkuser/controller/CheckUserController.java create mode 100644 src/main/java/com/api/xuanran/wang/ambofo/checkuser/service/CheckUserService.java create mode 100644 src/main/java/weaver/xuanran/wang/schroeder/mapper/SchroederMapper.java create mode 100644 src/main/resources/META-INF/MANIFEST.MF create mode 100644 src/main/resources/WEB-INF/prop/prop2map/AmbofoADConfig.properties create mode 100644 src/test/java/xuanran/wang/ambofo/checkuser/CheckUserTest.java diff --git a/src/main/java/aiyh/utils/action/CusBaseAction.java b/src/main/java/aiyh/utils/action/CusBaseAction.java index 9b114a6..35827b6 100644 --- a/src/main/java/aiyh/utils/action/CusBaseAction.java +++ b/src/main/java/aiyh/utils/action/CusBaseAction.java @@ -31,6 +31,10 @@ public abstract class CusBaseAction implements Action { * 全局requestInfo对象 */ protected RequestInfo globalRequestInfo; + /** + *

线程局部变量

+ **/ + protected static ThreadLocal requestInfoThreadLocal = new ThreadLocal<>(); /** *

初始化流程默认的处理方法

@@ -49,6 +53,7 @@ public abstract class CusBaseAction implements Action { @Override public final String execute(RequestInfo requestInfo) { + requestInfoThreadLocal.set(requestInfo); this.globalRequestInfo = requestInfo; RequestManager requestManager = requestInfo.getRequestManager(); String billTable = requestManager.getBillTableName(); @@ -91,6 +96,9 @@ public abstract class CusBaseAction implements Action { if (this.exceptionCallback(e, requestManager)) { return Action.FAILURE_AND_CONTINUE; } + }finally { + // 无论成功还是失败 都将该线程的requestInfo进行移除 + requestInfoThreadLocal.remove(); } return Action.SUCCESS; } diff --git a/src/main/java/com/api/xuanran/wang/ambofo/checkuser/controller/CheckUserController.java b/src/main/java/com/api/xuanran/wang/ambofo/checkuser/controller/CheckUserController.java new file mode 100644 index 0000000..5adc100 --- /dev/null +++ b/src/main/java/com/api/xuanran/wang/ambofo/checkuser/controller/CheckUserController.java @@ -0,0 +1,59 @@ +package com.api.xuanran.wang.ambofo.checkuser.controller; + +import aiyh.utils.ApiResult; +import aiyh.utils.Util; +import com.api.xuanran.wang.ambofo.checkuser.service.CheckUserService; +import org.apache.log4j.Logger; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; + +/** + *

安波福从AD域中校验用户是否存在

+ * + * @Author xuanran.wang + * @Date 2022/12/12 14:24 + */ +@Path("/wxr/ambofo/") +public class CheckUserController { + + private final Logger log = Util.getLogger(); + + @Path("checkUser") + @POST + @Produces(MediaType.TEXT_PLAIN) + public String checkUser(@Context HttpServletRequest request, @Context HttpServletResponse response) { + String checkContent = request.getParameter("checkContent"); + try { + CheckUserService checkUserService = new CheckUserService(); + return ApiResult.success(checkUserService.checkADHasUser(checkContent),"ok"); + }catch (Exception e){ + String error = Util.logStr("AD查询接口发生异常:{}", e.getMessage()); + log.error(error); + log.error(Util.getErrString(e)); + return ApiResult.error(500, error); + } + } + + @Path("logUser") + @GET + @Produces(MediaType.TEXT_PLAIN) + public String logUser(@Context HttpServletRequest request, @Context HttpServletResponse response) { + try { + CheckUserService checkUserService = new CheckUserService(); + checkUserService.logAllUser(); + return ApiResult.successNoData(); + }catch (Exception e){ + String error = Util.logStr("AD查询接口发生异常:{}", e.getMessage()); + log.error(error); + log.error(Util.getErrString(e)); + return ApiResult.error(500, error); + } + } +} diff --git a/src/main/java/com/api/xuanran/wang/ambofo/checkuser/service/CheckUserService.java b/src/main/java/com/api/xuanran/wang/ambofo/checkuser/service/CheckUserService.java new file mode 100644 index 0000000..4a3c165 --- /dev/null +++ b/src/main/java/com/api/xuanran/wang/ambofo/checkuser/service/CheckUserService.java @@ -0,0 +1,149 @@ +package com.api.xuanran.wang.ambofo.checkuser.service; + + +import aiyh.utils.Util; +import aiyh.utils.excention.CustomerException; +import com.alibaba.fastjson.JSONObject; +import org.apache.commons.collections.MapUtils; +import org.apache.log4j.Logger; +import javax.naming.Context; +import javax.naming.NamingEnumeration; +import javax.naming.NamingException; +import javax.naming.directory.SearchControls; +import javax.naming.directory.SearchResult; +import javax.naming.ldap.InitialLdapContext; +import javax.naming.ldap.LdapContext; +import java.util.Hashtable; +import java.util.Map; + +/** + *

安波福从AD校验用户是否存在业务方法

+ * + * @Author xuanran.wang + * @Date 2022/12/12 14:29 + */ +public class CheckUserService { + + private Map ADConfig = null; + private final Logger log = Util.getLogger(); + /** + *

构造方法中初始化配置文件

+ * @author xuanran.wang + * @dateTime 2022/12/12 15:31 + **/ + public CheckUserService(){ + // AD配置文件 + ADConfig = Util.getProperties2Map("AmbofoADConfig"); + if(MapUtils.isEmpty(ADConfig)){ + throw new CustomerException("请检查/filesystem/prop/prop2map 文件夹下是否存在AmbofoADConfig.properties文件!"); + } + + log.info(Util.logStr("AD配置对象 : [{}]", JSONObject.toJSONString(ADConfig))); + } + + /** + *

校验AD是否存在指定用户

+ * @author xuanran.wang + * @dateTime 2022/12/12 15:22 + * @param checkInfo 校验内容 + * @return true/false 有/没有 + **/ + public boolean checkADHasUser(String checkInfo) { + //连接到AD + LdapContext ldapContext = login(); + try { + // 域节点 + String searchBase = Util.null2String(ADConfig.get("searchBase")); + // LDAP搜索过滤器类 cn=*name*模糊查询 cn=name 精确查询 String searchFilter = "(objectClass="+type+")"; + //查询域帐号 + String searchFilter = Util.null2String(ADConfig.get("queryField")) + "=" + checkInfo; + log.info("searchFilter : " + searchFilter); + // 创建搜索控制器 + SearchControls searchControl = new SearchControls(); + // 设置搜索范围 深度 + searchControl.setSearchScope(SearchControls.SUBTREE_SCOPE); + // 根据设置的域节点、过滤器类和搜索控制器搜索LDAP得到结果 + NamingEnumeration answer = ldapContext.search(searchBase, searchFilter, searchControl); + // 初始化搜索结果数为0 + return answer.hasMoreElements(); + } catch (NamingException e) { + throw new CustomerException(Util.logStr("从AD搜索用户异常:[{}]",e.getMessage())); + } finally { + close(ldapContext); + } + } + + public void logAllUser() { + //连接到AD + LdapContext ldapContext = login(); + try { + // 域节点 + String searchBase = Util.null2String(ADConfig.get("searchBase")); + // LDAP搜索过滤器类 cn=*name*模糊查询 cn=name 精确查询 String searchFilter = "(objectClass="+type+")"; + // 创建搜索控制器 + SearchControls searchControl = new SearchControls(); + // 设置搜索范围 深度 + searchControl.setSearchScope(SearchControls.SUBTREE_SCOPE); + // 根据设置的域节点、过滤器类和搜索控制器搜索LDAP得到结果 + NamingEnumeration answer = ldapContext.search(searchBase, "", searchControl); + //4. 获取查询的内容 + while (answer.hasMoreElements()) { + SearchResult sr = (SearchResult) answer.next(); + String dn = sr.getName(); + log.info("dn " + dn); + } + } catch (NamingException e) { + throw new CustomerException(Util.logStr("从AD搜索用户异常:[{}]",e.getMessage())); + } finally { + close(ldapContext); + } + } + + /** + *

创建LDAP连接

+ * @author xuanran.wang + * @dateTime 2022/12/12 15:21 + * @return LDAP连接对象 + **/ + private LdapContext login() { + String userName = Util.null2String(ADConfig.get("userName")); + String password = Util.null2String(ADConfig.get("password")); + String server = Util.null2String(ADConfig.get("server")); + String driver = Util.null2String(ADConfig.get("driver")); + String authentication = Util.null2String(ADConfig.get("authentication")); + try { + Hashtable env = new Hashtable<>(); + //用户名称,cn,ou,dc 分别:用户,组,域 + env.put(Context.SECURITY_PRINCIPAL, userName); + //用户密码 cn 的密码 + env.put(Context.SECURITY_CREDENTIALS, password); + //url 格式:协议://ip:端口/组,域 ,直接连接到域或者组上面 + env.put(Context.PROVIDER_URL, server); + //LDAP 工厂 + env.put(Context.INITIAL_CONTEXT_FACTORY, driver); + //验证的类型 "none", "simple", "strong" + env.put(Context.SECURITY_AUTHENTICATION, authentication); + return new InitialLdapContext(env, null); + } catch (NamingException e) { + throw new CustomerException(Util.logStr("连接AD失败! : {}", e.getMessage())); + } + } + + + /** + *

关闭连接

+ * @author xuanran.wang + * @dateTime 2022/12/12 15:30 + * @param lct AD连接对象 + **/ + private void close(LdapContext lct) { + try { + if (lct != null){ + //关闭连接 + lct.close(); + } + } catch (NamingException e) { + throw new CustomerException(Util.logStr("关闭AD连接失败! : {}", e.getMessage())); + } + } +} diff --git a/src/main/java/com/api/xuanran/wang/schroeder/download_file/service/DownLoadFileService.java b/src/main/java/com/api/xuanran/wang/schroeder/download_file/service/DownLoadFileService.java index b2dd097..49f5ef6 100644 --- a/src/main/java/com/api/xuanran/wang/schroeder/download_file/service/DownLoadFileService.java +++ b/src/main/java/com/api/xuanran/wang/schroeder/download_file/service/DownLoadFileService.java @@ -19,7 +19,7 @@ public class DownLoadFileService { /** *

文件记录表

**/ - private static final String DOC_LOG_TABLE_NAME = "doc_log"; + private static final String DOC_LOG_TABLE_NAME = "uf_doc_log"; /** *

查询文件记录sql

**/ diff --git a/src/main/java/weaver/xuanran/wang/common/util/CusInfoToOAUtil.java b/src/main/java/weaver/xuanran/wang/common/util/CusInfoToOAUtil.java index c5431e4..b02e57f 100644 --- a/src/main/java/weaver/xuanran/wang/common/util/CusInfoToOAUtil.java +++ b/src/main/java/weaver/xuanran/wang/common/util/CusInfoToOAUtil.java @@ -90,6 +90,29 @@ public class CusInfoToOAUtil { return executeBatch(modelId, params, "", Collections.emptyList(), true); } + /** + *

将自定义信息写入建模

+ * @author xuanran.wang + * @dateTime 2022/11/23 17:00 + * @param modelId 模块id + * @param params 需要插入的数据map + * @param whereSql 重复数据条件sql + * @param whereParams 重复数据参数集合 + * @return 建模数据id集合 + **/ + public static List executeBatch( int modelId, + List> params, + String whereSql, + List whereParams) { + if(modelId < 0){ + throw new RuntimeException("建模模块id不能小于0!"); + } + String tableName = commonMapper.getModelNameByModelId(String.valueOf(modelId)); + if(StringUtils.isBlank(tableName)){ + throw new CustomerException("模块id为 " + modelId + ", 在系统中暂没查询到对应表单!"); + } + return executeBatch(modelId, tableName, params, whereSql, whereParams, true); + } /** *

将自定义信息写入建模

* @author xuanran.wang @@ -148,10 +171,11 @@ public class CusInfoToOAUtil { if(StringUtils.isNotBlank(whereSql)){ whereSql = Util.sbc2dbcCase(whereSql); whereSql = whereSql.replaceAll(TABLE_NAME_PLACEHOLDER, tableName); - log.info("whereSql : " + whereSql); - log.info("参数 : " + whereParams); if (rs.executeQuery(whereSql, whereParams) && rs.next()) { mainId = Util.getIntValue(rs.getString(1),-1); + }else { + log.info("whereSql : " + whereSql); + log.info("参数 : " + whereParams); } } if(mainId < 0){ diff --git a/src/main/java/weaver/xuanran/wang/schroeder/action/PushSealTaskAction.java b/src/main/java/weaver/xuanran/wang/schroeder/action/PushSealTaskAction.java index 5e53045..4a43775 100644 --- a/src/main/java/weaver/xuanran/wang/schroeder/action/PushSealTaskAction.java +++ b/src/main/java/weaver/xuanran/wang/schroeder/action/PushSealTaskAction.java @@ -4,11 +4,19 @@ import aiyh.utils.Util; import aiyh.utils.action.CusBaseAction; // 基础的action,实现一些基础的参数 import aiyh.utils.annotation.RequiredMark; import aiyh.utils.excention.CustomerException; // 自定义异常类 create 2022/3/9 2:20 PM +import org.apache.commons.lang3.StringUtils; import weaver.conn.RecordSetTrans; import weaver.hrm.User; +import weaver.soa.workflow.request.RequestInfo; import weaver.workflow.request.RequestManager; +import weaver.xuanran.wang.common.util.CommonUtil; +import weaver.xuanran.wang.common.util.CusInfoToOAUtil; import weaver.xuanran.wang.schroeder.service.SchroederQRCodeService; +import java.util.*; +import java.util.function.Function; +import java.util.stream.Collectors; + /** *

施罗德创建二维码action

@@ -30,25 +38,53 @@ public class PushSealTaskAction extends CusBaseAction { // 基础的action, @RequiredMark private String QRCodeField; + /** + *

用印文件字段 会将这个字段所有的值存到用印文件记录表中

+ **/ + @RequiredMark + private String fileField; + + /** + *

文档记录表模块id

+ **/ + @RequiredMark + private String modelId; + private final SchroederQRCodeService schroederQRCodeService = new SchroederQRCodeService(); // 施罗德业务方法 施罗德业务方法 + + @Override // action 提交流程业务处理方法 具体业务逻辑实现 public void doSubmit(String requestId, String billTable, int workflowId, User user, RequestManager requestManager) { log.info("---------- PushSealTaskSealValue Begin " + requestId + "----------"); + RequestInfo requestInfo = requestInfoThreadLocal.get(); String scanNum = schroederQRCodeService.pushSealTask(onlyMark, billTable, requestId); // 推送数据创建任务 建模配置唯一标识 RecordSetTrans trans = requestManager.getRsTrans(); trans.setAutoCommit(false); String updateSql = "update " + billTable + " set " + QRCodeField + " = ? where requestid = ?"; // 二维码来源字段 try{ if(!trans.executeUpdate(updateSql, scanNum, requestId)){ - throw new CustomerException(Util.logStr("更新表单sql执行失败!sql : {}, 参数 scanNum : {}, requestId : {}", scanNum, requestId)); // 自定义异常类 create 2022/3/9 2:20 PM 构建日志字符串 + throw new CustomerException(Util.logStr("更新表单sql执行失败!sql : {}, 参数 scanNum : {}, requestId : {}", scanNum, requestId)); // 自定义异常类 create 2022/3/9 2:20 PM 构建日志字符串 } + // 获取明细表数据 + List> detailList = getDetailTableValueByDetailNo(1, requestInfo); + List docIds = detailList.stream() + .map(item -> Util.null2DefaultStr(item.get(fileField), "")) + .filter(StringUtils::isNotBlank).collect(Collectors.toList()); + ArrayList> list = new ArrayList<>(); + for (String docId : docIds) { + LinkedHashMap map = new LinkedHashMap<>(); + map.put("docId", docId); + map.put("enable", 0); + list.add(map); + } + // 将数据写入建模 + CusInfoToOAUtil.executeBatch(Util.getIntValue(modelId, -1), list, "select 1 from #{tableName} where docId = ?", docIds); }catch (Exception e){ trans.rollback(); throw new CustomerException(Util.logStr("执行提交方法异常:{}", e.getMessage())); // 自定义异常类 create 2022/3/9 2:20 PM 构建日志字符串 } trans.commit(); } - } diff --git a/src/main/java/weaver/xuanran/wang/schroeder/cus_field_value/PushSealTaskSealValue.java b/src/main/java/weaver/xuanran/wang/schroeder/cus_field_value/PushSealTaskSealValue.java index d4859d7..1b9dc5b 100644 --- a/src/main/java/weaver/xuanran/wang/schroeder/cus_field_value/PushSealTaskSealValue.java +++ b/src/main/java/weaver/xuanran/wang/schroeder/cus_field_value/PushSealTaskSealValue.java @@ -26,7 +26,8 @@ public class PushSealTaskSealValue implements CusInterfaceGetValue { // 自定 @Override // 获取参数值 public Object execute(Map mainMap, Map detailMap, String currentValue, Map pathParam) { - logger.info(Util.logStr("路径参数:[{}]", JSONObject.toJSONString(pathParam))); // 构建日志字符串 + logger.info(Util.logStr("路径参数:[{}]", JSONObject.toJSONString(pathParam))); + logger.info("路径参数(字符串拼接) : " + JSONObject.toJSONString(pathParam));// 构建日志字符串 // 接口字段 String sealSnField = pathParam.get("sealSnField"); String sealNumField = pathParam.get("sealNumField"); diff --git a/src/main/java/weaver/xuanran/wang/schroeder/mapper/SchroederMapper.java b/src/main/java/weaver/xuanran/wang/schroeder/mapper/SchroederMapper.java new file mode 100644 index 0000000..1812c4c --- /dev/null +++ b/src/main/java/weaver/xuanran/wang/schroeder/mapper/SchroederMapper.java @@ -0,0 +1,45 @@ +package weaver.xuanran.wang.schroeder.mapper; + +import aiyh.utils.annotation.recordset.ParamMapper; +import aiyh.utils.annotation.recordset.Select; +import aiyh.utils.annotation.recordset.SqlMapper; + +import java.util.List; +import java.util.Map; + +/** + *

施罗德查询方法

+ * + * @Author xuanran.wang + * @Date 2022/12/13 13:05 + */ +@SqlMapper +public interface SchroederMapper { + + /** + *

查询明细一数据集

+ * @author xuanran.wang + * @dateTime 2022/12/13 13:10 + * @param tableName 表名 + * @param mainId 主表id + * @return 明细表数据集合 + **/ + @Select("select yywj,qfzzl,qfzcs from $t{tableName} where mainid = #{mainId} and sfjgqfz = 0") + List> selectSealTaskInfoList(@ParamMapper("tableName") String tableName, + @ParamMapper("mainId") String mainId); + + /** + *

查询明细一用印文件docId/h1> + * @author xuanran.wang + * @dateTime 2022/12/13 13:10 + * @param fileField 用印文件字段 + * @param tableName 表名 + * @param mainId 主表id + * @return 明细表数据集合 + **/ + @Select("select $t{fileField} from $t{tableName} where mainid = #{mainId}") + List> selectSealFileList(@ParamMapper("fileField") String fileField, + @ParamMapper("tableName") String tableName, + @ParamMapper("mainId") String mainId); + +} diff --git a/src/main/java/weaver/xuanran/wang/schroeder/service/SchroederQRCodeService.java b/src/main/java/weaver/xuanran/wang/schroeder/service/SchroederQRCodeService.java index 6b28b52..ad6af3b 100644 --- a/src/main/java/weaver/xuanran/wang/schroeder/service/SchroederQRCodeService.java +++ b/src/main/java/weaver/xuanran/wang/schroeder/service/SchroederQRCodeService.java @@ -8,16 +8,27 @@ import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.fasterxml.jackson.core.JsonProcessingException; import com.google.zxing.qrcode.encoder.QRCode; +import com.icbc.api.internal.apache.http.M; +import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; +import org.junit.Test; +import org.springframework.beans.BeanUtils; import weaver.conn.RecordSet; import weaver.mobile.plugin.ecology.QRCodeComInfo; import weaver.xiao.commons.config.entity.RequestMappingConfig; import weaver.xiao.commons.config.service.DealWithMapping; +import weaver.xuanran.wang.schroeder.mapper.SchroederMapper; import javax.ws.rs.core.MediaType; +import java.io.File; import java.io.IOException; +import java.util.HashMap; +import java.util.List; import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; /** *

施罗德业务方法

@@ -49,6 +60,7 @@ public class SchroederQRCodeService { { httpUtils.getGlobalCache().header.put("Content-Type", MediaType.APPLICATION_JSON); // 全局请求头 } + private final SchroederMapper schroederMapper = Util.getMapper(SchroederMapper.class); /** *

推送数据创建任务

@@ -72,7 +84,10 @@ public class SchroederQRCodeService { recordSet.executeQuery(selectMainSql, requestId); if (recordSet.next()) { dealWithMapping.setMainTable(billTable); - Map requestParam = dealWithMapping.getRequestParam(recordSet, requestMappingConfig); // 解析请求参数配置树,转换成请求参数 + Map requestParam = dealWithMapping.getRequestParam(recordSet, requestMappingConfig); + // 如果明细数据存在骑缝章时候增加一行数据进去 + changeRequestMap(requestParam, billTable + "_dt1", recordSet.getString("id")); + // 解析请求参数配置树,转换成请求参数 log.info(Util.logStr("请求json : {}", JSONObject.toJSONString(requestParam))); // 构建日志字符串 String url = requestMappingConfig.getRequestUrl(); ResponeVo responeVo = null; @@ -111,6 +126,47 @@ public class SchroederQRCodeService { } return res; } + + /** + *

骑缝章修改请求参数

+ * @author xuanran.wang + * @dateTime 2022/12/13 14:15 + * @param requestParam 请求参数 + * @param billTable 表名 + * @param mainId 主表id + **/ + public void changeRequestMap(Map requestParam, String billTable, String mainId){ + List> files = (List>) requestParam.get("file"); + List> detail1List = schroederMapper.selectSealTaskInfoList(billTable, mainId); + if(CollectionUtils.isEmpty(detail1List) || CollectionUtils.isEmpty(files)){ + return; + } + // 遍历明细数据 + for (Map detailItem : detail1List) { + // 用印文件 + String sealFile = Util.null2String(detailItem.get("yywj")); + // 从生成的请求参数map中开始匹配 + List> filterFiles = files.stream() + .filter(item -> { + String filePath = Util.null2DefaultStr(item.get("filePath"), ""); + String docId = Util.null2DefaultStr(filePath.substring(filePath.lastIndexOf("=") + 1),""); + return sealFile.equals(docId); + }) + .collect(Collectors.toList()); + if(CollectionUtils.isNotEmpty(filterFiles)){ + // 只有一个能匹配 + Map o = filterFiles.get(0); + HashMap tempMap = o.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> a, HashMap::new)); + // 印章集合 + HashMap seal = new HashMap<>(); + seal.put("sealSn",Util.null2DefaultStr(detailItem.get("qfzzl"),"")); + seal.put("sealNum",Util.null2DefaultStr(detailItem.get("qfzcs"),"0")); + tempMap.put("seal", seal); + files.add(tempMap); + } + } + } + } diff --git a/src/main/resources/META-INF/MANIFEST.MF b/src/main/resources/META-INF/MANIFEST.MF new file mode 100644 index 0000000..a7cfc61 --- /dev/null +++ b/src/main/resources/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +Main-Class: aiyh.utils.Util + diff --git a/src/main/resources/WEB-INF/prop/prop2map/AmbofoADConfig.properties b/src/main/resources/WEB-INF/prop/prop2map/AmbofoADConfig.properties new file mode 100644 index 0000000..015bb4b --- /dev/null +++ b/src/main/resources/WEB-INF/prop/prop2map/AmbofoADConfig.properties @@ -0,0 +1,7 @@ +userName = SID_ECOLOGY +password = BDw5FzWQ@ +server = ldap://LDAP_ASIA.Aptiv.com:389 +driver = com.sun.jndi.ldap.LdapCtxFactory +authentication = simple +searchBase=CN=Users,DC=aptiv,DC=com +queryField=uid \ No newline at end of file diff --git a/src/test/java/xuanran/wang/ambofo/checkuser/CheckUserTest.java b/src/test/java/xuanran/wang/ambofo/checkuser/CheckUserTest.java new file mode 100644 index 0000000..ebc2770 --- /dev/null +++ b/src/test/java/xuanran/wang/ambofo/checkuser/CheckUserTest.java @@ -0,0 +1,27 @@ +package xuanran.wang.ambofo.checkuser; + +import aiyh.utils.Util; +import basetest.BaseTest; +import com.api.xuanran.wang.ambofo.checkuser.service.CheckUserService; +import org.junit.Test; + +/** + *

安波福校验用户测试类

+ * + * @Author xuanran.wang + * @Date 2022/12/12 15:35 + */ +public class CheckUserTest extends BaseTest { + + @Test + public void testProperties(){ + try{ + CheckUserService checkUserService = new CheckUserService(); + checkUserService.logAllUser(); + }catch (Exception e){ + String error = Util.logStr("AD查询接口发生异常:{}", e.getMessage()); + log.error(error); + log.error(Util.getErrString(e)); + } + } +} diff --git a/src/test/java/xuanran/wang/schroeder/download_file/DownLoadFileTest.java b/src/test/java/xuanran/wang/schroeder/download_file/DownLoadFileTest.java index 48ef944..cfd995b 100644 --- a/src/test/java/xuanran/wang/schroeder/download_file/DownLoadFileTest.java +++ b/src/test/java/xuanran/wang/schroeder/download_file/DownLoadFileTest.java @@ -5,8 +5,10 @@ import basetest.BaseTest; import com.alibaba.fastjson.JSONObject; import com.api.xuanran.wang.schroeder.download_file.mapper.DownLoadFileMapper; import com.icbc.api.internal.apache.http.impl.cookie.S; +import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.junit.Test; +import org.springframework.beans.BeanUtils; import weaver.file.ImageFileManager; import weaver.general.TimeUtil; import weaver.xuanran.wang.common.util.CommonUtil; @@ -56,7 +58,6 @@ public class DownLoadFileTest extends BaseTest { @Test public void testParseStr(){ - String str = ""; String pattern = "(?<=\\{).+(?=})"; Pattern compile = Pattern.compile(pattern); @@ -75,4 +76,82 @@ public class DownLoadFileTest extends BaseTest { } } } + + @Test + public void testAddItem(){ + String json = "{\"requestId\":\"189567\",\"super\":\"luchenghong\",\"orgNo\":\"junhe\",\"title\":\"鲁诚鸿\",\"sealPlace\":\"2\",\"useSealType\":\"1\",\"userPassword\":\"672518\",\"useSealEquipment\":\"2\",\"file\":[{\"fileName\":\"拜访函(景德镇).docx\",\"filePath\":\"http://oa.junheland.com/hyu/seal.download?docId=12\",\"waterAndSeal\":\"2\",\"crosssealType\":\"2\",\"printCount\":\"1\",\"printType\":\"0\",\"seal\":[{\"sealType\":\"124\",\"sealNum\":\"1\"}]},{\"fileName\":\"附件6-变更签证办理协议.pdf\",\"filePath\":\"http://erp.junheland.com:9070/view?docId=13\",\"waterAndSeal\":\"2\",\"crosssealType\":\"1\",\"printCount\":\"6\",\"printType\":\"1\",\"seal\":[{\"sealType\":\"164\",\"sealNum\":\"6\"}]}]}"; + Map requestParam = JSONObject.parseObject(json, Map.class); + log.info("requestParam " + requestParam); + ArrayList> detail1List = new ArrayList<>(); + HashMap map = new HashMap<>(); + // yywj,qfzzl,qfzcs + map.put("yywj","12"); + map.put("qfzzl","2"); + map.put("qfzcs","3"); + detail1List.add(map); + // 过滤出集合类型的参数 + List> files = (List>) requestParam.get("file"); + if(CollectionUtils.isNotEmpty(files)){ + // 加盖骑缝章的明细数据 + if(CollectionUtils.isNotEmpty(detail1List)){ + // 遍历明细数据 + for (Map detailItem : detail1List) { + // 用印文件 + String sealFile = Util.null2String(detailItem.get("yywj")); + log.info("sealFile : " + sealFile); + // 从生成的请求参数map中开始匹配 + List> filterFiles = files.stream() + .filter(item -> { + String filePath = Util.null2DefaultStr(item.get("filePath"), ""); + String docId = Util.null2DefaultStr(filePath.substring(filePath.lastIndexOf("=") + 1),""); + log.info("filePath : " + filePath + " , docId : " + docId); + return sealFile.equals(docId); + }) + .collect(Collectors.toList()); + log.info("filterFiles " + JSONObject.toJSONString(filterFiles)); + if(CollectionUtils.isNotEmpty(filterFiles)){ + // 只有一个能匹配 + Map o = filterFiles.get(0); + HashMap tempMap = o.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> a, HashMap::new)); + // 印章集合 + HashMap seal = new HashMap<>(); + seal.put("sealSn",Util.null2DefaultStr(detailItem.get("qfzzl"),"")); + seal.put("sealNum",Util.null2DefaultStr(detailItem.get("qfzcs"),"0")); + tempMap.put("seal", seal); + log.info("tempMap " + tempMap); + files.add(tempMap); + } + } + } + } + log.info("requestParam : " + JSONObject.toJSONString(requestParam) ); + } + + @Test + public void testParse(){ + String paramStr = "weaver.xuanran.wang.schroeder.cus_field_value.PushSealTaskSealValue?sealSnField=sealSn&sealNumField=sealNum&sealSnCusSql=`select\n" + + " ? from jkfdjsfk where id\n" + + " =1`&sealNumCusSql=`select case ? when 0 then htzyzcs when 1 then gzcs else frzcs end from formtable_main_22_dt1 where id = {?dt.id}`&hah=liuliu&cus=`select? * fr$%&#@!)(<>?/\\{}「」【【】[]~、asfom table where id = '' and teset = #{name}`&niua=卧槽"; + + String pattern = "&?(?([#.\\w\\u4E00-\\u9FA5]+))=" + + "(?((`([^`]*)`)|" + + "((#(\\{|sql\\{))?([():/\\-$#={ }.\\w\\u4E00-\\u9FA5?]+)?}?)))&?"; + Pattern compile = Pattern.compile(pattern); + Matcher matcher = compile.matcher(paramStr); + HashMap pathParamMap = new HashMap<>(); + while (matcher.find()) { + String key = matcher.group("key"); + String paramValue = matcher.group("value"); + if (paramValue != null && paramValue.startsWith("`") && paramValue.endsWith("`")) { + paramValue = paramValue.substring(1, paramValue.length() - 1); + } + pathParamMap.put(key, paramValue); + } + log.info("pathParamMap : " + JSONObject.toJSONString(pathParamMap)); + + String text ="123456"; + String replacement = "two$two"; + String resultString = text.replaceAll("2", replacement); + log.info("resultString " + resultString); + } } From 7caba0236ecd1bd15a81c96dbfea48647de4748b Mon Sep 17 00:00:00 2001 From: "youHong.ai" <774495953@qq.com> Date: Tue, 13 Dec 2022 18:13:44 +0800 Subject: [PATCH 17/33] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=89=8D=E7=AB=AFjs?= =?UTF-8?q?=E9=80=9A=E8=BF=87=E5=AD=97=E6=AE=B5=E5=90=8D=E8=8E=B7=E5=8F=96?= =?UTF-8?q?=E5=AD=97=E6=AE=B5=E5=80=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- javascript/common/Utils.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/javascript/common/Utils.js b/javascript/common/Utils.js index 75aa117..6c960d1 100644 --- a/javascript/common/Utils.js +++ b/javascript/common/Utils.js @@ -134,7 +134,7 @@ window.Utils = { * @returns {*} 字段值 */ getFiledValueByName: function (fieldName, rowIndex) { - return WfForm.getFieldValue(Utils.convertNameObjToId(fieldName) + rowIndex ? '_' + rowIndex : '') + return WfForm.getFieldValue(Utils.convertNameObjToId(fieldName) + (rowIndex ? '_' + rowIndex : '')) }, /** From d94aa8e9fa80396b7d169dd4eeaa32fde13b339d Mon Sep 17 00:00:00 2001 From: wangxuanran <3055088966@qq.com> Date: Tue, 13 Dec 2022 18:39:38 +0800 Subject: [PATCH 18/33] =?UTF-8?q?=E5=88=A0=E9=99=A4=E4=B8=B4=E6=97=B6?= =?UTF-8?q?=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../xuanran/wang/schroeder/action/PushSealTaskAction.java | 1 - src/main/resources/META-INF/MANIFEST.MF | 3 --- 2 files changed, 4 deletions(-) delete mode 100644 src/main/resources/META-INF/MANIFEST.MF diff --git a/src/main/java/weaver/xuanran/wang/schroeder/action/PushSealTaskAction.java b/src/main/java/weaver/xuanran/wang/schroeder/action/PushSealTaskAction.java index 4a43775..f88d2b3 100644 --- a/src/main/java/weaver/xuanran/wang/schroeder/action/PushSealTaskAction.java +++ b/src/main/java/weaver/xuanran/wang/schroeder/action/PushSealTaskAction.java @@ -9,7 +9,6 @@ import weaver.conn.RecordSetTrans; import weaver.hrm.User; import weaver.soa.workflow.request.RequestInfo; import weaver.workflow.request.RequestManager; -import weaver.xuanran.wang.common.util.CommonUtil; import weaver.xuanran.wang.common.util.CusInfoToOAUtil; import weaver.xuanran.wang.schroeder.service.SchroederQRCodeService; diff --git a/src/main/resources/META-INF/MANIFEST.MF b/src/main/resources/META-INF/MANIFEST.MF deleted file mode 100644 index a7cfc61..0000000 --- a/src/main/resources/META-INF/MANIFEST.MF +++ /dev/null @@ -1,3 +0,0 @@ -Manifest-Version: 1.0 -Main-Class: aiyh.utils.Util - From 8198c7e4eb3f03775a6dbf69979ff15c24793f9d Mon Sep 17 00:00:00 2001 From: "jiacheng.deng" Date: Fri, 16 Dec 2022 15:05:04 +0800 Subject: [PATCH 19/33] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 1 + ecology-9-dev.iml | 8 -------- sql/youhong.ai/common_view_sql/sqlserver.sql | 1 - src/main/java/aiyh/utils/action/CusBaseAction.java | 1 - src/test/java/youhong/ai/pcn/TestOrganization.java | 3 +++ 5 files changed, 4 insertions(+), 10 deletions(-) delete mode 100644 ecology-9-dev.iml diff --git a/.gitignore b/.gitignore index c5ff955..5621e6a 100644 --- a/.gitignore +++ b/.gitignore @@ -40,6 +40,7 @@ DirectoryV2.xml *.log src/main/resources/WEB-INF/sqllog/ java.io.tempdir/ +ecology-9-dev.iml diff --git a/ecology-9-dev.iml b/ecology-9-dev.iml deleted file mode 100644 index c545449..0000000 --- a/ecology-9-dev.iml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/sql/youhong.ai/common_view_sql/sqlserver.sql b/sql/youhong.ai/common_view_sql/sqlserver.sql index 98781cc..6f6ed89 100644 --- a/sql/youhong.ai/common_view_sql/sqlserver.sql +++ b/sql/youhong.ai/common_view_sql/sqlserver.sql @@ -26,7 +26,6 @@ select (bill.id + '-' + base.id) id, from workflow_billdetailtable bill join workflow_base base on base.formid = bill.billid; - create view workflow_field_table_view as select wb.id, wb.fieldname, diff --git a/src/main/java/aiyh/utils/action/CusBaseAction.java b/src/main/java/aiyh/utils/action/CusBaseAction.java index 9b114a6..a6c836e 100644 --- a/src/main/java/aiyh/utils/action/CusBaseAction.java +++ b/src/main/java/aiyh/utils/action/CusBaseAction.java @@ -21,7 +21,6 @@ import java.util.*; */ public abstract class CusBaseAction implements Action { - /** * 全局日志对象 */ diff --git a/src/test/java/youhong/ai/pcn/TestOrganization.java b/src/test/java/youhong/ai/pcn/TestOrganization.java index a275676..5bc34c6 100644 --- a/src/test/java/youhong/ai/pcn/TestOrganization.java +++ b/src/test/java/youhong/ai/pcn/TestOrganization.java @@ -200,4 +200,7 @@ public class TestOrganization extends BaseTest { List orgChartTree = orgChartService.getOrgChartTree(user); System.out.println(JSON.toJSONString(orgChartTree)); } + + + } From d0c7e50ec4ba862fddc7b8d9e9325a6fb611936c Mon Sep 17 00:00:00 2001 From: "jiacheng.deng" Date: Fri, 16 Dec 2022 15:13:09 +0800 Subject: [PATCH 20/33] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=B5=8B=E8=AF=95?= =?UTF-8?q?=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/youhong/ai/pcn/TestOrganization.java | 202 +----------------- 1 file changed, 7 insertions(+), 195 deletions(-) diff --git a/src/test/java/youhong/ai/pcn/TestOrganization.java b/src/test/java/youhong/ai/pcn/TestOrganization.java index c8b4da6..0c43783 100644 --- a/src/test/java/youhong/ai/pcn/TestOrganization.java +++ b/src/test/java/youhong/ai/pcn/TestOrganization.java @@ -5,14 +5,6 @@ import aiyh.utils.httpUtil.HttpMultipartFile; import aiyh.utils.httpUtil.ResponeVo; import aiyh.utils.httpUtil.util.HttpUtils; import basetest.BaseTest; -import com.alibaba.excel.EasyExcel; -import com.alibaba.excel.ExcelWriter; -import com.alibaba.excel.metadata.CellData; -import com.alibaba.excel.metadata.Head; -import com.alibaba.excel.write.handler.CellWriteHandler; -import com.alibaba.excel.write.metadata.WriteSheet; -import com.alibaba.excel.write.metadata.holder.WriteSheetHolder; -import com.alibaba.excel.write.metadata.holder.WriteTableHolder; import com.alibaba.fastjson.JSON; import com.api.youhong.ai.pcn.organization.orgchart.service.OrgChartService; import com.api.youhong.ai.pcn.organization.orgchart.vo.OrgChartNodeVo; @@ -24,6 +16,9 @@ import weaver.conn.RecordSet; import weaver.formmode.interfaces.action.WorkflowToMode; import weaver.general.GCONST; import weaver.hrm.User; +import weaver.soa.workflow.request.RequestInfo; +import weaver.soa.workflow.request.RequestService; +import weaver.workflow.request.RequestManager; import weaver.xiao.commons.config.entity.MultipartFile; import weaver.xiao.commons.config.entity.RequestMappingConfig; import weaver.xiao.commons.config.service.DealWithMapping; @@ -32,7 +27,10 @@ import weaver.youhong.ai.pcn.hrorganization.wesmat.model.Employee; import weaver.youhong.ai.pcn.hrorganization.wesmat.model.Position; import weaver.youhong.ai.pcn.hrorganization.wesmat.result.GetOrganizationResult; -import java.io.*; +import java.io.BufferedReader; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -267,191 +265,5 @@ public class TestOrganization extends BaseTest { System.out.println(execute); } - - @Test - public void testEasyExcel() throws FileNotFoundException { - String tempPath = "/Users/aoey.oct.22/company/Fan_wei/test_file/muban.xlsx"; - String filePath = "/Users/aoey.oct.22/company/Fan_wei/test_file/muban1.xlsx"; - FileOutputStream outputStream = new FileOutputStream(filePath); - int[] mergeColumeIndex = {0, 1}; - int mergeRowIndex = 1; - ExcelWriter excelWriter = EasyExcel.write(outputStream) - .withTemplate(tempPath) - .registerWriteHandler(new ExcelFillCellMergeStrategy(mergeRowIndex, mergeColumeIndex)) - .build(); - WriteSheet sheet = EasyExcel.writerSheet().build(); - excelWriter.fill(buildList(), sheet); - - excelWriter.finish(); - try { - outputStream.close(); - } catch (IOException e) { - } - } - - public List> buildList() { - List> list = new ArrayList<>(); - list.add(new HashMap() {{ - put("addr", "北京"); - put("kinds", "生活用品"); - put("price", 10); - put("num", 80); - }}); - list.add(new HashMap() {{ - put("addr", "北京"); - put("kinds", "生活用品"); - put("price", 10); - put("num", 80); - }}); - list.add(new HashMap() {{ - put("addr", "北京"); - put("kinds", "电子产品"); - put("price", 10); - put("num", 80); - }}); - list.add(new HashMap() {{ - put("addr", "北京"); - put("kinds", "电子产品"); - put("price", 10); - put("num", 80); - }}); - list.add(new HashMap() {{ - put("addr", "上海"); - put("kinds", "生活用品"); - put("price", 10); - put("num", 80); - }}); - list.add(new HashMap() {{ - put("addr", "上海"); - put("kinds", "生活用品"); - put("price", 10); - put("num", 80); - }}); - list.add(new HashMap() {{ - put("addr", "上海"); - put("kinds", "电子商品"); - put("price", 10); - put("num", 80); - }}); - list.add(new HashMap() {{ - put("addr", "云南"); - put("kinds", "生活用品"); - put("price", 10); - put("num", 80); - }}); - list.add(new HashMap() {{ - put("addr", "云南"); - put("kinds", "电子铲平"); - put("price", 10); - put("num", 80); - }}); - list.add(new HashMap() {{ - put("addr", "云南"); - put("kinds", "蘑菇"); - put("price", 10); - put("num", 80); - }}); - list.add(new HashMap() {{ - put("addr", "云南"); - put("kinds", "蘑菇"); - put("price", 10); - put("num", 80); - }}); - - return list; - } -} - -class ExcelFillCellMergeStrategy implements CellWriteHandler { - - /** 需要进行单元格合并的列数组 **/ - private int[] mergeColumnIndex; - /** 单元格合并从第几行开始 **/ - private int mergeRowIndex; - - public ExcelFillCellMergeStrategy() {} - - public ExcelFillCellMergeStrategy(int mergeRowIndex, int[] mergeColumnIndex) { - this.mergeRowIndex = mergeRowIndex; - this.mergeColumnIndex = mergeColumnIndex; - } - - - @Override - public void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Head head, Integer integer, Integer integer1, Boolean aBoolean) { - - } - - @Override - public void afterCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Cell cell, Head head, Integer integer, Boolean aBoolean) { - - } - - @Override - public void afterCellDataConverted(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, CellData cellData, Cell cell, Head head, Integer integer, Boolean aBoolean) { - - } - - @Override - public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, - List list, Cell cell, Head head, Integer integer, Boolean isHead) { - int curRowIndex = cell.getRowIndex(); - int curColIndex = cell.getColumnIndex(); - if (curRowIndex > mergeRowIndex) { - for (int i = 0; i < mergeColumnIndex.length; i++) { - if (curColIndex == mergeColumnIndex[i]) { - mergeWithPrevRow(writeSheetHolder, cell, curRowIndex, curColIndex); - break; - } - } - } - } - - /** - * 当前单元格向上合并 - * - * @param writeSheetHolder 表格数据写入处理对象 - * @param cell 当前单元格 - * @param curRowIndex 当前行 - * @param curColIndex 当前列 - */ - private void mergeWithPrevRow(WriteSheetHolder writeSheetHolder, Cell cell, int curRowIndex, int curColIndex) { - // 获取当前单元格的数据 - Object curData = - cell.getCellTypeEnum() == CellType.STRING ? cell.getStringCellValue() : cell.getNumericCellValue(); - // 获取当前shert表 - Sheet sheet1 = cell.getSheet(); - // 获取当前的行,有可能获取到空行 - Row row = sheet1.getRow(curRowIndex - 1); - if (row == null) { - row = sheet1.getRow(curRowIndex); - } - Cell preCell = row.getCell(curColIndex); - Object preData = - preCell.getCellTypeEnum() == CellType.STRING ? preCell.getStringCellValue() : preCell.getNumericCellValue(); - // 将当前单元格数据与上一个单元格数据比较 - Boolean dataBool = preData.equals(curData); - if (dataBool) { - Sheet sheet = writeSheetHolder.getSheet(); - List mergeRegions = sheet.getMergedRegions(); - boolean isMerged = false; - for (int i = 0; i < mergeRegions.size() && !isMerged; i++) { - CellRangeAddress cellRangeAddr = mergeRegions.get(i); - // 若上一个单元格已经被合并,则先移出原有的合并单元,再重新添加合并单元 - if (cellRangeAddr.isInRange(curRowIndex - 1, curColIndex)) { - sheet.removeMergedRegion(i); - cellRangeAddr.setLastRow(curRowIndex); - sheet.addMergedRegion(cellRangeAddr); - isMerged = true; - } - } - // 若上一个单元格未被合并,则新增合并单元 - if (!isMerged) { - CellRangeAddress cellRangeAddress = - new CellRangeAddress(curRowIndex - 1, curRowIndex, curColIndex, curColIndex); - sheet.addMergedRegion(cellRangeAddress); - } - } - } } From 88d6b40fb53f1cdb58f2e9534387fc3b228c30ca Mon Sep 17 00:00:00 2001 From: "jiacheng.deng" Date: Fri, 16 Dec 2022 15:16:40 +0800 Subject: [PATCH 21/33] =?UTF-8?q?fix=20filename=20bug=20fieldname=E4=B8=8D?= =?UTF-8?q?=E6=98=8E=E7=A1=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/weaver/xiao/commons/config/dao/ConfigMappingCMD.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/weaver/xiao/commons/config/dao/ConfigMappingCMD.java b/src/main/java/weaver/xiao/commons/config/dao/ConfigMappingCMD.java index cc32fb7..9feef2a 100644 --- a/src/main/java/weaver/xiao/commons/config/dao/ConfigMappingCMD.java +++ b/src/main/java/weaver/xiao/commons/config/dao/ConfigMappingCMD.java @@ -62,7 +62,7 @@ public class ConfigMappingCMD { " where mainid = ? "; break; case MODEL: - queryDetail1Sql = "select paramName,paramType,getValueType,dataSource,belongTo,workflowField,modelField,fieldName,valueContext, " + + queryDetail1Sql = "select paramName,paramType,getValueType,dataSource,belongTo,workflowField,modelField,fv.fieldName,valueContext, " + " fv.id fieldId,fv.fieldname,fv.tablename,fv.indexdesc " + " from " + configTableName + "_dt1 config " + " left join workflow_field_table_view fv on config.modelField = fv.id " + From e99562c417f9d7748281db382728470ca8542a85 Mon Sep 17 00:00:00 2001 From: "jiacheng.deng" Date: Fri, 16 Dec 2022 16:40:42 +0800 Subject: [PATCH 22/33] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E8=AF=B7=E6=B1=82?= =?UTF-8?q?=E6=97=A5=E5=BF=97=E8=BE=93=E5=87=BA=E6=89=80=E6=9C=89=E7=9B=B8?= =?UTF-8?q?=E5=BA=94=E6=95=B0=E6=8D=AE=E5=AF=BC=E8=87=B4=E6=97=A5=E5=BF=97?= =?UTF-8?q?=E5=A4=AA=E5=A4=A7=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/aiyh/utils/httpUtil/ResponeVo.java | 87 ++++++++++++------- .../httpUtil/util/HttpUtilParamInfo.java | 3 + .../aiyh/utils/httpUtil/util/HttpUtils.java | 30 ++++++- 3 files changed, 86 insertions(+), 34 deletions(-) diff --git a/src/main/java/aiyh/utils/httpUtil/ResponeVo.java b/src/main/java/aiyh/utils/httpUtil/ResponeVo.java index 6f07cbb..dcc34b3 100644 --- a/src/main/java/aiyh/utils/httpUtil/ResponeVo.java +++ b/src/main/java/aiyh/utils/httpUtil/ResponeVo.java @@ -27,6 +27,8 @@ public class ResponeVo implements HttpResponse { * 相应内容 */ private String entityString; + + private Map entityMap; /** * 相应头信息 */ @@ -39,7 +41,6 @@ public class ResponeVo implements HttpResponse { private Map requestData; - private HttpResponse response; public int getCode() { @@ -68,11 +69,15 @@ public class ResponeVo implements HttpResponse { * @return 资源皇后的map集合 * @throws JsonProcessingException JSON转换异常 */ + @Deprecated public Map getEntityMap() throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); return mapper.readValue(this.getEntityString(), Map.class); } + public Map getResponseMap(){ + return this.entityMap; + } /** * 根据相应结果,转化为实体类 * @@ -81,11 +86,21 @@ public class ResponeVo implements HttpResponse { * @return 转换后的实体类 * @throws JsonProcessingException JSON转换异常 */ + @Deprecated public T getEntity(Class clazz) throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); return mapper.readValue(this.getEntityString(), clazz); } + public T getResponseEntity(Class clazz) { + ObjectMapper mapper = new ObjectMapper(); + try { + return mapper.readValue(this.getEntityString(), clazz); + } catch (JsonProcessingException e) { + return null; + } + } + /** * 根据相应结果,转化为实体类 * @@ -98,6 +113,45 @@ public class ResponeVo implements HttpResponse { return mapper.readValue(this.getEntityString(), typeReference); } + public String getEntityString() { + return entityString; + } + + public void setEntityString(String entityString) { + this.entityString = entityString; + try{ + ObjectMapper mapper = new ObjectMapper(); + this.entityMap = mapper.readValue(this.getEntityString(), Map.class); + }catch (Exception ignore){ + + } + } + + public InputStream getContent() { + return content; + } + + public void setContent(InputStream content) { + this.content = content; + } + + public byte[] getContentByteArr() { + return contentByteArr; + } + + public void setContentByteArr(byte[] contentByteArr) { + this.contentByteArr = contentByteArr; + } + + @Override + public String toString() { + return "ResponeVo{" + + "code=" + code + + ", entityString='" + entityString + '\'' + + ", otherParam=" + requestData + + '}'; + } + /** * 根据相应结果转化为实体集合 * @@ -243,37 +297,6 @@ public class ResponeVo implements HttpResponse { } - public String getEntityString() { - return entityString; - } - public void setEntityString(String entityString) { - this.entityString = entityString; - } - - public InputStream getContent() { - return content; - } - - public void setContent(InputStream content) { - this.content = content; - } - - public byte[] getContentByteArr() { - return contentByteArr; - } - - public void setContentByteArr(byte[] contentByteArr) { - this.contentByteArr = contentByteArr; - } - - @Override - public String toString() { - return "ResponeVo{" + - "code=" + code + - ", entityString='" + entityString + '\'' + - ", otherParam=" + requestData + - '}'; - } } diff --git a/src/main/java/aiyh/utils/httpUtil/util/HttpUtilParamInfo.java b/src/main/java/aiyh/utils/httpUtil/util/HttpUtilParamInfo.java index 01790ed..7e32e34 100644 --- a/src/main/java/aiyh/utils/httpUtil/util/HttpUtilParamInfo.java +++ b/src/main/java/aiyh/utils/httpUtil/util/HttpUtilParamInfo.java @@ -5,6 +5,7 @@ import com.alibaba.fastjson.annotation.JSONField; import lombok.Data; import java.util.Date; +import java.util.Map; /** *

http请求信息

@@ -27,5 +28,7 @@ public class HttpUtilParamInfo { @JSONField(format = "yyyy-MM-dd HH:mm:ss") private Date responseDate; + private Map responseMap; + private String responseString; private ResponeVo response; } diff --git a/src/main/java/aiyh/utils/httpUtil/util/HttpUtils.java b/src/main/java/aiyh/utils/httpUtil/util/HttpUtils.java index 6ea581f..44665b8 100644 --- a/src/main/java/aiyh/utils/httpUtil/util/HttpUtils.java +++ b/src/main/java/aiyh/utils/httpUtil/util/HttpUtils.java @@ -8,9 +8,9 @@ import aiyh.utils.zwl.common.ToolUtil; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.serializer.SerializerFeature; +import com.alibaba.fastjson.support.spring.PropertyPreFilters; import com.google.common.base.Strings; import com.google.common.util.concurrent.ThreadFactoryBuilder; -import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.client.CredentialsProvider; @@ -57,6 +57,8 @@ public class HttpUtils { * basic 认证 */ private CredentialsProvider credentialsProvider = null; + private final PropertyPreFilters filters = new PropertyPreFilters(); + private final PropertyPreFilters.MySimplePropertyPreFilter excludefilter = filters.addFilter(); { // private final ExecutorService executorService = Executors.newFixedThreadPool(3); @@ -67,6 +69,8 @@ public class HttpUtils { new LinkedBlockingQueue<>(1024), threadFactory, new ThreadPoolExecutor.AbortPolicy()); + String[] excludeProperties = {"locale","contentByteArr","response"}; + excludefilter.addExcludes(excludeProperties); } public HttpUtils() { @@ -638,10 +642,16 @@ public class HttpUtils { httpUtilParamInfo = new HttpUtilParamInfo(); } httpUtilParamInfo.setResponse(apply); + if(apply.getResponseMap() == null){ + httpUtilParamInfo.setResponseString(apply.getEntityString()); + }else { + httpUtilParamInfo.setResponseMap(apply.getResponseMap()); + } httpUtilParamInfo.setResponseDate(new Date()); try { log.info(Util.logStr("url [{}] request info : [\n{}\n];", httpUtilParamInfo.getUrl(), JSONObject.toJSONString(httpUtilParamInfo, + excludefilter, SerializerFeature.PrettyFormat, SerializerFeature.WriteDateUseDateFormat))); } catch (Exception ignore) { @@ -669,11 +679,17 @@ public class HttpUtils { httpUtilParamInfo = new HttpUtilParamInfo(); } httpUtilParamInfo.setResponse(apply); + if(apply.getResponseMap() == null){ + httpUtilParamInfo.setResponseString(apply.getEntityString()); + }else { + httpUtilParamInfo.setResponseMap(apply.getResponseMap()); + } httpUtilParamInfo.setResponseDate(new Date()); HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.remove(); try { log.info(Util.logStr("url [{}] request info : [\n{}\n];", httpUtilParamInfo.getUrl(), JSONObject.toJSONString(httpUtilParamInfo, + excludefilter, SerializerFeature.PrettyFormat, SerializerFeature.WriteDateUseDateFormat))); } catch (Exception ignore) { @@ -696,17 +712,22 @@ public class HttpUtils { try { response = httpClient.execute(request); HttpEntity entity = response.getEntity(); - Header[] allHeaders = response.getAllHeaders(); Locale locale = response.getLocale(); responeVo.setLocale(locale); responeVo.setEntityString(EntityUtils.toString(entity, DEFAULT_ENCODING)); responeVo.setCode(response.getStatusLine().getStatusCode()); responeVo.setResponse(response); httpUtilParamInfo.setResponse(responeVo); + if(responeVo.getResponseMap() == null){ + httpUtilParamInfo.setResponseString(responeVo.getEntityString()); + }else { + httpUtilParamInfo.setResponseMap(responeVo.getResponseMap()); + } httpUtilParamInfo.setResponseDate(new Date()); try { log.info(Util.logStr("url [{}] request info : [\n{}\n];", httpUtilParamInfo.getUrl(), JSONObject.toJSONString(httpUtilParamInfo, + excludefilter, SerializerFeature.PrettyFormat, SerializerFeature.WriteDateUseDateFormat))); } catch (Exception ignore) { @@ -718,6 +739,7 @@ public class HttpUtils { httpUtilParamInfo.setResponseDate(new Date()); log.info(Util.logStr("url [{}] request info : [\n{}\n];", httpUtilParamInfo.getUrl(), JSONObject.toJSONString(httpUtilParamInfo, + excludefilter, SerializerFeature.PrettyFormat, SerializerFeature.WriteDateUseDateFormat))); } catch (Exception ignore) { @@ -1021,9 +1043,11 @@ public class HttpUtils { private HttpPost uploadFileByInputStream(String url, List multipartFileList, Map params, Map headers) { log.info(Util.logStr("start request : url is [{}],other param [\n{}\n],heard [\n{}\n]", url, JSONObject.toJSONString(params, + excludefilter, SerializerFeature.PrettyFormat, SerializerFeature.WriteDateUseDateFormat), JSONObject.toJSONString(headers, + excludefilter, SerializerFeature.PrettyFormat, SerializerFeature.WriteDateUseDateFormat))); HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo(); @@ -1074,9 +1098,11 @@ public class HttpUtils { private HttpPut uploadFileByInputStreamPut(String url, List multipartFileList, Map params, Map headers) { log.info(Util.logStr("start request : url is [{}],other param [\n{}\n],heard [\n{}\n]", url, JSONObject.toJSONString(params, + excludefilter, SerializerFeature.PrettyFormat, SerializerFeature.WriteDateUseDateFormat), JSONObject.toJSONString(headers, + excludefilter, SerializerFeature.PrettyFormat, SerializerFeature.WriteDateUseDateFormat))); HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo(); From 242080e58118580f9bbed23c0966e6a0cdd7c20d Mon Sep 17 00:00:00 2001 From: "youHong.ai" <774495953@qq.com> Date: Mon, 19 Dec 2022 19:49:02 +0800 Subject: [PATCH 23/33] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=96=B9=E6=B3=95?= =?UTF-8?q?=E9=87=8D=E8=BD=BD=E4=B8=ADdocid=E6=B2=A1=E8=AE=BE=E7=BD=AE?= =?UTF-8?q?=E7=9A=84bug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../youhong.ai/pcn/workflow_code_block.js | 19 +- .../aiyh/utils/httpUtil/util/HttpUtils.java | 34 +-- .../aiyh/utils/recordset/RecordsetUtil.java | 14 +- .../controller/OrgChartController.java | 27 +- .../orgchart/mapper/OrgChartMapper.java | 8 +- .../orgchart/service/OrgChartService.java | 247 ++++++++++++------ .../config/service/DealWithMapping.java | 2 + .../java/youhong/ai/pcn/TestOrganization.java | 26 +- .../java/youhong/ai/pcn/WorkflowTest.java | 139 +++++++++- 9 files changed, 394 insertions(+), 122 deletions(-) diff --git a/javascript/youhong.ai/pcn/workflow_code_block.js b/javascript/youhong.ai/pcn/workflow_code_block.js index 290ce16..74e8d70 100644 --- a/javascript/youhong.ai/pcn/workflow_code_block.js +++ b/javascript/youhong.ai/pcn/workflow_code_block.js @@ -208,6 +208,9 @@ window.workflowCus = Object.assign(window.workflowCus ? window.workflowCus : {}, getLevelByScore: async function (config) { let scoreFiled = config.scoreFiled let score = Utils.getFiledValueByName(scoreFiled); + if(score == 0 || score == ''){ + return + } let result = await Utils.api({ url: "/api/ayh/workflow/apa/level", data: { @@ -225,10 +228,20 @@ window.workflowCus = Object.assign(window.workflowCus ? window.workflowCus : {}, /* ******************* apa流程通过apa分数字段带出level字段 ******************* */ $(() => { let config = { - scoreFiled: "", - levelField: "" + scoreFiled: "apafsptyg", + levelField: "level1" + } + try { + setTimeout(()=>{ + WfForm.bindFieldChangeEvent(Utils.convertNameObjToId(config.scoreFiled),()=>{ + console.log("asdfasdfasdfsadfasdf") + window.workflowCus.getLevelByScore(config) + }) + window.workflowCus.getLevelByScore(config) + },100) + }catch (err){ + console.log(err) } - window.workflowCus.getLevelByScore(config) }) /* ******************* apa流程通过apa分数字段带出level字段eng ******************* */ diff --git a/src/main/java/aiyh/utils/httpUtil/util/HttpUtils.java b/src/main/java/aiyh/utils/httpUtil/util/HttpUtils.java index 44665b8..bf4d92b 100644 --- a/src/main/java/aiyh/utils/httpUtil/util/HttpUtils.java +++ b/src/main/java/aiyh/utils/httpUtil/util/HttpUtils.java @@ -51,14 +51,14 @@ public class HttpUtils { private final GlobalCache globalCache = new GlobalCache(); // 线程池 private final ThreadPoolExecutor executorService; + private final PropertyPreFilters filters = new PropertyPreFilters(); + private final PropertyPreFilters.MySimplePropertyPreFilter excludefilter = filters.addFilter(); // 默认编码 private String DEFAULT_ENCODING = "UTF-8"; /** * basic 认证 */ private CredentialsProvider credentialsProvider = null; - private final PropertyPreFilters filters = new PropertyPreFilters(); - private final PropertyPreFilters.MySimplePropertyPreFilter excludefilter = filters.addFilter(); { // private final ExecutorService executorService = Executors.newFixedThreadPool(3); @@ -69,7 +69,7 @@ public class HttpUtils { new LinkedBlockingQueue<>(1024), threadFactory, new ThreadPoolExecutor.AbortPolicy()); - String[] excludeProperties = {"locale","contentByteArr","response"}; + String[] excludeProperties = {"locale", "contentByteArr", "response"}; excludefilter.addExcludes(excludeProperties); } @@ -642,9 +642,9 @@ public class HttpUtils { httpUtilParamInfo = new HttpUtilParamInfo(); } httpUtilParamInfo.setResponse(apply); - if(apply.getResponseMap() == null){ + if (apply.getResponseMap() == null) { httpUtilParamInfo.setResponseString(apply.getEntityString()); - }else { + } else { httpUtilParamInfo.setResponseMap(apply.getResponseMap()); } httpUtilParamInfo.setResponseDate(new Date()); @@ -679,9 +679,9 @@ public class HttpUtils { httpUtilParamInfo = new HttpUtilParamInfo(); } httpUtilParamInfo.setResponse(apply); - if(apply.getResponseMap() == null){ + if (apply.getResponseMap() == null) { httpUtilParamInfo.setResponseString(apply.getEntityString()); - }else { + } else { httpUtilParamInfo.setResponseMap(apply.getResponseMap()); } httpUtilParamInfo.setResponseDate(new Date()); @@ -718,9 +718,9 @@ public class HttpUtils { responeVo.setCode(response.getStatusLine().getStatusCode()); responeVo.setResponse(response); httpUtilParamInfo.setResponse(responeVo); - if(responeVo.getResponseMap() == null){ + if (responeVo.getResponseMap() == null) { httpUtilParamInfo.setResponseString(responeVo.getEntityString()); - }else { + } else { httpUtilParamInfo.setResponseMap(responeVo.getResponseMap()); } httpUtilParamInfo.setResponseDate(new Date()); @@ -1042,14 +1042,14 @@ public class HttpUtils { */ private HttpPost uploadFileByInputStream(String url, List multipartFileList, Map params, Map headers) { - log.info(Util.logStr("start request : url is [{}],other param [\n{}\n],heard [\n{}\n]", url, JSONObject.toJSONString(params, - excludefilter, - SerializerFeature.PrettyFormat, - SerializerFeature.WriteDateUseDateFormat), - JSONObject.toJSONString(headers, - excludefilter, - SerializerFeature.PrettyFormat, - SerializerFeature.WriteDateUseDateFormat))); + //log.info(Util.logStr("start request : url is [{}],other param [\n{}\n],heard [\n{}\n]", url, JSONObject.toJSONString(params, + // excludefilter, + // SerializerFeature.PrettyFormat, + // SerializerFeature.WriteDateUseDateFormat), + // JSONObject.toJSONString(headers, + // excludefilter, + // SerializerFeature.PrettyFormat, + // SerializerFeature.WriteDateUseDateFormat))); HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo(); httpUtilParamInfo.setParams(params); httpUtilParamInfo.setUrl(url); diff --git a/src/main/java/aiyh/utils/recordset/RecordsetUtil.java b/src/main/java/aiyh/utils/recordset/RecordsetUtil.java index a7b5370..9b2c5f5 100644 --- a/src/main/java/aiyh/utils/recordset/RecordsetUtil.java +++ b/src/main/java/aiyh/utils/recordset/RecordsetUtil.java @@ -13,8 +13,7 @@ import java.lang.reflect.Method; import java.lang.reflect.Proxy; /** - * @author EBU7-dev1-ayh - * create 2021/12/19 0019 14:39 + * @author EBU7-dev1-ayh create 2021/12/19 0019 14:39 */ @@ -22,6 +21,8 @@ public class RecordsetUtil implements InvocationHandler { private final RecordSet recordSet = new RecordSet(); + private final RecordSet rs = new RecordSet(); + public T getMapper(Class tClass) { if (tClass == null) { throw new BindingException("class is null!"); @@ -40,8 +41,7 @@ public class RecordsetUtil implements InvocationHandler { ResultMapper resultMapper = new ResultMapper(); Select select = method.getAnnotation(Select.class); if (select != null) { -// 查询 - RecordSet rs = new RecordSet(); + // 查询 String sql = select.value(); boolean custom = select.custom(); PrepSqlResultImpl handler = sqlHandler.handler(sql, custom, method, args); @@ -59,7 +59,7 @@ public class RecordsetUtil implements InvocationHandler { Update update = method.getAnnotation(Update.class); if (update != null) { -// 查询 + // 查询 String sql = update.value(); boolean custom = update.custom(); PrepSqlResultImpl handler = sqlHandler.handler(sql, custom, method, args); @@ -90,7 +90,7 @@ public class RecordsetUtil implements InvocationHandler { } Insert insert = method.getAnnotation(Insert.class); if (insert != null) { -// 查询 + // 查询 String sql = insert.value(); boolean custom = insert.custom(); PrepSqlResultImpl handler = sqlHandler.handler(sql, custom, method, args); @@ -114,7 +114,7 @@ public class RecordsetUtil implements InvocationHandler { } Delete delete = method.getAnnotation(Delete.class); if (delete != null) { -// 查询 + // 查询 String sql = delete.value(); boolean custom = delete.custom(); PrepSqlResultImpl handler = sqlHandler.handler(sql, custom, method, args); diff --git a/src/main/java/com/api/youhong/ai/pcn/organization/orgchart/controller/OrgChartController.java b/src/main/java/com/api/youhong/ai/pcn/organization/orgchart/controller/OrgChartController.java index f07666b..1f4ba06 100644 --- a/src/main/java/com/api/youhong/ai/pcn/organization/orgchart/controller/OrgChartController.java +++ b/src/main/java/com/api/youhong/ai/pcn/organization/orgchart/controller/OrgChartController.java @@ -1,6 +1,7 @@ package com.api.youhong.ai.pcn.organization.orgchart.controller; import aiyh.utils.ApiResult; +import aiyh.utils.Util; import com.api.youhong.ai.pcn.organization.orgchart.service.OrgChartService; import com.api.youhong.ai.pcn.organization.orgchart.vo.OrgChartNodeVo; import weaver.hrm.HrmUserVarify; @@ -35,8 +36,28 @@ public class OrgChartController { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public String getOrgChartTree(@Context HttpServletRequest request, @Context HttpServletResponse response) { - User logInUser = HrmUserVarify.getUser(request, response); - List treeList = service.getOrgChartTree(logInUser); - return ApiResult.success(treeList); + try { + User logInUser = HrmUserVarify.getUser(request, response); + List treeList = service.getOrgChartTree(logInUser); + return ApiResult.success(treeList); + } catch (Exception e) { + Util.getLogger().error("get chart tree error ! \n" + Util.getErrString(e)); + return ApiResult.error("get chart tree error!" + e.getMessage()); + } + } + + @Path("get-all") + @GET + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public String getOrgChartTreeAll(@Context HttpServletRequest request, @Context HttpServletResponse response) { + try { + User logInUser = HrmUserVarify.getUser(request, response); + List treeList = service.getOrgChartTreeAll(logInUser); + return ApiResult.success(treeList); + } catch (Exception e) { + Util.getLogger().error("get all chart tree error ! \n" + Util.getErrString(e)); + return ApiResult.error("get all chart tree error!" + e.getMessage()); + } } } diff --git a/src/main/java/com/api/youhong/ai/pcn/organization/orgchart/mapper/OrgChartMapper.java b/src/main/java/com/api/youhong/ai/pcn/organization/orgchart/mapper/OrgChartMapper.java index 742c417..864fb93 100644 --- a/src/main/java/com/api/youhong/ai/pcn/organization/orgchart/mapper/OrgChartMapper.java +++ b/src/main/java/com/api/youhong/ai/pcn/organization/orgchart/mapper/OrgChartMapper.java @@ -40,7 +40,7 @@ public interface OrgChartMapper { " hrm.departmentid department_id, " + " dept.DEPARTMENTNAME department_name, " + " job.JOBTITLENAME job_title_name, " + - " cus1.$t{typeOfEmploymentFiled} type_of_employment " + + " uftb.$t{parentField} type_of_employment " + "from hrmresource hrm " + " inner join hrmjobtitles job on hrm.JOBTITLE = job.id " + " inner join cus_fielddata cus on cus.ID = hrm.ID " + @@ -50,9 +50,13 @@ public interface OrgChartMapper { " and cus1.scope = 'HrmCustomFieldByInfoType' " + " and cus1.scopeid = -1" + " inner join hrmdepartment dept on dept.id = hrm.DEPARTMENTID " + + " inner join $t{typeOfEmploymentTable} uftb on uftb.$t{typeOfEmploymentIdField} = cus1.$t{typeOfEmploymentFiled} " + "where hrm.status in (0, 1)") List selectAll(@ParamMapper("typeOfEmploymentFiled") String typeOfEmploymentField, - @ParamMapper("lastNameEnField") String lastNameEnField); + @ParamMapper("lastNameEnField") String lastNameEnField, + @ParamMapper("typeOfEmploymentTable") String typeOfEmploymentTable, + @ParamMapper("parentField") String parentField, + @ParamMapper("typeOfEmploymentIdField") String typeOfEmploymentIdField); /** diff --git a/src/main/java/com/api/youhong/ai/pcn/organization/orgchart/service/OrgChartService.java b/src/main/java/com/api/youhong/ai/pcn/organization/orgchart/service/OrgChartService.java index cd235e6..8fdbd6f 100644 --- a/src/main/java/com/api/youhong/ai/pcn/organization/orgchart/service/OrgChartService.java +++ b/src/main/java/com/api/youhong/ai/pcn/organization/orgchart/service/OrgChartService.java @@ -41,84 +41,13 @@ public class OrgChartService { */ public List getOrgChartTree(User logInUser) { int userId = logInUser.getUID(); - String typeOfEmploymentField = Util.getCusConfigValue("typeOfEmploymentField"); - Assert.notBlank(typeOfEmploymentField, "config [typeOfEmploymentField] is null or blank!"); - String lastNameEnField = Util.getCusConfigValue("lastNameEnField"); - Assert.notBlank(lastNameEnField, "config [lastNameEnField] is null or blank!"); - List hrmResourceList = mapper.selectAll(typeOfEmploymentField, lastNameEnField); - if (Objects.isNull(hrmResourceList) || hrmResourceList.isEmpty()) { - throw new CustomerException("查询不到相关人员!"); - } - //List hrmResourceDtoList = new ArrayList(); AtomicReference currentUser = new AtomicReference<>(); - /* ******************* 将pojo转换为Dto对象,对节点属性默认值赋值,找出当前用户并设置显示 ******************* */ - List hrmResourceDtoList = hrmResourceList.stream() - .map(struct::hrmResourceToDto) - .peek(item -> Builder.startSet(item) - .with(HrmResourceDto::setShow, 0) - .with(HrmResourceDto::setShowBrother, 0) - .with(HrmResourceDto::setShowChildren, 0) - .endSet()) - .collect(Collectors.toList()); - hrmResourceDtoList.stream() - .peek(item -> { - if (item.getManagerId() == userId) { - item.setShow(1); - } - }) - .filter(item -> item.getId() == userId) - .forEach(item -> { - Builder.startSet(item) - .with(HrmResourceDto::setShow, 1) - .with(HrmResourceDto::setShowBrother, 1) - .with(HrmResourceDto::setShowChildren, 1) - .with(HrmResourceDto::setCurrent, true) - .endSet(); - currentUser.set(item); - }); + List hrmResourceDtoList = getHrmResourceDtoList(userId, currentUser); /* ******************* 系统管理员默认全部展开哦 ******************* */ if (userId == 1) { - List collect = hrmResourceDtoList.stream() - .map(struct::hrmResourceDtoToVo) - .peek(item -> Builder.startSet(item) - .with(OrgChartNodeVo::setShow, 1) - .with(OrgChartNodeVo::setShowBrother, 1) - .with(OrgChartNodeVo::setShowChildren, 1) - .with(OrgChartNodeVo::setCurrent, true) - .endSet()) - .collect(Collectors.toList()); - return Util.listToTree(collect, OrgChartNodeVo::getId, OrgChartNodeVo::getManagerId, - OrgChartNodeVo::getChildren, OrgChartNodeVo::setChildren, - parentId -> parentId == null || parentId <= 0) - .stream().peek(item -> Builder.startSet(item) - .with(OrgChartNodeVo::setIsRoot, true) - .with(OrgChartNodeVo::setCurrent, true) - .endSet()) - .peek(item -> recursionChildrenNums(item, 0)) - .collect(Collectors.toList()); + return systemAdminTree(hrmResourceDtoList); } - Assert.notNull(currentUser.get(), "not find current login user info!"); - /* ******************* 根据当前登陆人的分部来过滤 ******************* */ - hrmResourceDtoList = hrmResourceDtoList.stream() - .filter(item -> logInUser.getUserSubCompany1() == item.getSubCompanyId()) - .collect(Collectors.toList()); - /* ******************* 查找当前登陆人员的所有上级 ******************* */ - String currentUserManagerStr = currentUser.get().getManagerStr(); - if (Objects.isNull(currentUserManagerStr)) { - currentUserManagerStr = ""; - } - currentUserManagerStr = Util.removeSeparator(currentUserManagerStr, ","); - List currentUserManagerList = Arrays.stream(currentUserManagerStr.split(",")) - .map(Integer::parseInt) - .collect(Collectors.toList()); - /* ******************* 对当前用户的所有直接上级设置标识 ******************* */ - hrmResourceDtoList.stream() - .filter(item -> currentUserManagerList.contains(item.getId())) - .forEach(item -> Builder.startSet(item) - .with(HrmResourceDto::setShowChildren, 1) - .with(HrmResourceDto::setCurrentParent, true) - .endSet()); - + filterCurrentSubCom(hrmResourceDtoList, currentUser, logInUser); /* ******************* 查询当前用户的是否全部展示或显示小红点的配置信息 ******************* */ ShowPointOrAll showPointOrAll = mapper.selectShowPointOrAll(userId); List orgChartNodeVoList = null; @@ -157,6 +86,176 @@ public class OrgChartService { } + /** + *

getOrgChartTreeAll 获取所有的数据并默认展开

+ * 2022/12/16 17:21 + * ************************************************************ + * + * @param logInUser 当前登陆id + * @return List 最终树 + * @author youHong.ai ****************************************** + */ + public List getOrgChartTreeAll(User logInUser) { + int userId = logInUser.getUID(); + AtomicReference currentUser = new AtomicReference<>(); + List hrmResourceDtoList = getHrmResourceDtoList(userId, currentUser); + /* ******************* 系统管理员默认全部展开哦 ******************* */ + if (userId == 1) { + return systemAdminTree(hrmResourceDtoList); + } + filterCurrentSubCom(hrmResourceDtoList, currentUser, logInUser); + List orgChartNodeVoList = null; + /* ******************* 转换dto为Vo并且设置根节点标识 ******************* */ + orgChartNodeVoList = hrmResourceDtoList.stream() + .map(struct::hrmResourceDtoToVo) + .peek(item -> + Builder.startSet(item) + .with(OrgChartNodeVo::setShow, 1) + .with(OrgChartNodeVo::setShowBrother, 1) + .with(OrgChartNodeVo::setShowChildren, 1) + .endSet() + ).collect(Collectors.toList()); + + return Util.listToTree(orgChartNodeVoList, OrgChartNodeVo::getId, + OrgChartNodeVo::getManagerId, OrgChartNodeVo::getChildren, + OrgChartNodeVo::setChildren, + parentId -> parentId == null || parentId <= 0) + .stream() + .peek(item -> item.setIsRoot(true)) + .peek(item -> recursionChildrenNums(item, 0)) + .collect(Collectors.toList()); + } + + + /** + *

filterCurrentSubCom 过滤当前分部的人员,并且设置用户上级标识

+ * 2022/12/16 17:16 + * ************************************************************ + * + * @param hrmResourceDtoList 人力资源dtolist + * @param currentUser 当前用户 + * @param logInUser 当前登陆用户 + * @author youHong.ai ****************************************** + */ + private void filterCurrentSubCom(List hrmResourceDtoList, + AtomicReference currentUser, + User logInUser) { + Assert.notNull(currentUser.get(), "not find current login user info!"); + /* ******************* 根据当前登陆人的分部来过滤 ******************* */ + hrmResourceDtoList = hrmResourceDtoList.stream() + .filter(item -> logInUser.getUserSubCompany1() == item.getSubCompanyId()) + .collect(Collectors.toList()); + /* ******************* 查找当前登陆人员的所有上级 ******************* */ + String currentUserManagerStr = currentUser.get().getManagerStr(); + if (Objects.isNull(currentUserManagerStr) || "".equals(currentUserManagerStr)) { + currentUserManagerStr = "0"; + } + currentUserManagerStr = Util.removeSeparator(currentUserManagerStr, ","); + List currentUserManagerList = Arrays.stream(currentUserManagerStr.split(",")) + .map(Integer::parseInt) + .collect(Collectors.toList()); + /* ******************* 对当前用户的所有直接上级设置标识 ******************* */ + hrmResourceDtoList.stream() + .filter(item -> currentUserManagerList.contains(item.getId())) + .forEach(item -> Builder.startSet(item) + .with(HrmResourceDto::setShowChildren, 1) + .with(HrmResourceDto::setCurrentParent, true) + .endSet()); + + } + + + /** + *

systemAdminTree 系统管理员返回全部展开的数据

+ * 2022/12/16 17:15 + * ************************************************************ + * + * @param hrmResourceDtoList 人力资源dtolist + * @return List 树型list + * @author youHong.ai ****************************************** + */ + private List systemAdminTree(List hrmResourceDtoList) { + List collect = hrmResourceDtoList.stream() + .map(struct::hrmResourceDtoToVo) + .peek(item -> Builder.startSet(item) + .with(OrgChartNodeVo::setShow, 1) + .with(OrgChartNodeVo::setShowBrother, 1) + .with(OrgChartNodeVo::setShowChildren, 1) + .with(OrgChartNodeVo::setCurrent, true) + .endSet()) + .collect(Collectors.toList()); + return Util.listToTree(collect, OrgChartNodeVo::getId, OrgChartNodeVo::getManagerId, + OrgChartNodeVo::getChildren, OrgChartNodeVo::setChildren, + parentId -> parentId == null || parentId <= 0) + .stream().peek(item -> Builder.startSet(item) + .with(OrgChartNodeVo::setIsRoot, true) + .with(OrgChartNodeVo::setCurrent, true) + .endSet()) + .peek(item -> recursionChildrenNums(item, 0)) + .collect(Collectors.toList()); + } + + /** + *

getHrmResourceDtoList 获取人力资源dto对象list

+ * 2022/12/16 17:09 + * ************************************************************ + * + * @param userId 当前登陆用户ID + * @param currentUser 当前登陆用户对象 + * @return List 人力资源dto对象list + * @author youHong.ai ****************************************** + */ + private List getHrmResourceDtoList(Integer userId, AtomicReference currentUser) { + // 人员类型自定义字段 + String typeOfEmploymentField = Util.getCusConfigValue("typeOfEmploymentField"); + Assert.notBlank(typeOfEmploymentField, "config [typeOfEmploymentField] is null or blank!"); + // 英文自定义名称字段 + String lastNameEnField = Util.getCusConfigValue("lastNameEnField"); + Assert.notBlank(lastNameEnField, "config [lastNameEnField] is null or blank!"); + // 人员类型id字段 建模表 + String typeOfEmploymentIdField = Util.getCusConfigValue("typeOfEmploymentIdField"); + Assert.notBlank(typeOfEmploymentIdField, "config [typeOfEmploymentIdField] is null or blank!"); + // 人员类型父级字段 建模表 + String parentField = Util.getCusConfigValue("parentField"); + Assert.notBlank(parentField, "config [parentField] is null or blank!"); + // 人员类型建模表表名 + String typeOfEmploymentTable = Util.getCusConfigValue("typeOfEmploymentTable"); + Assert.notBlank(typeOfEmploymentTable, "config [typeOfEmploymentTable] is null or blank!"); + // 查询所有人员信息 + List hrmResourceList = mapper.selectAll(typeOfEmploymentField, lastNameEnField, + typeOfEmploymentTable, parentField, typeOfEmploymentIdField); + if (Objects.isNull(hrmResourceList) || hrmResourceList.isEmpty()) { + throw new CustomerException("查询不到相关人员!"); + } + //List hrmResourceDtoList = new ArrayList(); + /* ******************* 将pojo转换为Dto对象,对节点属性默认值赋值,找出当前用户并设置显示 ******************* */ + List hrmResourceDtoList = hrmResourceList.stream() + .map(struct::hrmResourceToDto) + .peek(item -> Builder.startSet(item) + .with(HrmResourceDto::setShow, 0) + .with(HrmResourceDto::setShowBrother, 0) + .with(HrmResourceDto::setShowChildren, 0) + .endSet()) + .collect(Collectors.toList()); + hrmResourceDtoList.stream() + .peek(item -> { + if (Objects.equals(item.getManagerId(), userId)) { + item.setShow(1); + } + }) + .filter(item -> Objects.equals(item.getId(), userId)) + .forEach(item -> { + Builder.startSet(item) + .with(HrmResourceDto::setShow, 1) + .with(HrmResourceDto::setShowBrother, 1) + .with(HrmResourceDto::setShowChildren, 1) + .with(HrmResourceDto::setCurrent, true) + .endSet(); + currentUser.set(item); + }); + return hrmResourceDtoList; + } + /** *

计算节点所有子节点的数量

* 2022/12/3 17:55 diff --git a/src/main/java/weaver/xiao/commons/config/service/DealWithMapping.java b/src/main/java/weaver/xiao/commons/config/service/DealWithMapping.java index ebc7b22..458f9f8 100644 --- a/src/main/java/weaver/xiao/commons/config/service/DealWithMapping.java +++ b/src/main/java/weaver/xiao/commons/config/service/DealWithMapping.java @@ -649,6 +649,8 @@ public class DealWithMapping extends ToolUtil { for (DocImageFile docImageFile : docImageFiles) { MultipartFile multipartFile = new MultipartFile(); InputStream fileInputStream = ImageFileManager.getInputStreamById(docImageFile.getImageFileId()); + multipartFile.setDocId(docImageFile.getDocId()); + multipartFile.setImageFileId(docImageFile.getImageFileId()); multipartFile.setFileKey(paramName); multipartFile.setStream(fileInputStream); multipartFile.setFileName(docImageFile.getImageFileName()); diff --git a/src/test/java/youhong/ai/pcn/TestOrganization.java b/src/test/java/youhong/ai/pcn/TestOrganization.java index 0c43783..b541e09 100644 --- a/src/test/java/youhong/ai/pcn/TestOrganization.java +++ b/src/test/java/youhong/ai/pcn/TestOrganization.java @@ -170,16 +170,16 @@ public class TestOrganization extends BaseTest { @Test public void testReadCsv() { String srcPath = GCONST.getSysFilePath() + "HRIS_PositionExport20221120" + ".csv"; -// String charset = "utf-8"; -// try (CSVReader csvReader = new CSVReaderBuilder(new BufferedReader(new InputStreamReader(new FileInputStream(new File(srcPath)), charset))).build()) { -// Iterator iterator = csvReader.iterator(); -// while (iterator.hasNext()) { -// Arrays.stream(iterator.next()).forEach(System.out::print); -// System.out.println(); -// } -// } catch (Exception e) { -// e.printStackTrace(); -// } + // String charset = "utf-8"; + // try (CSVReader csvReader = new CSVReaderBuilder(new BufferedReader(new InputStreamReader(new FileInputStream(new File(srcPath)), charset))).build()) { + // Iterator iterator = csvReader.iterator(); + // while (iterator.hasNext()) { + // Arrays.stream(iterator.next()).forEach(System.out::print); + // System.out.println(); + // } + // } catch (Exception e) { + // e.printStackTrace(); + // } BufferedReader reader = null; String line = null; @@ -192,8 +192,8 @@ public class TestOrganization extends BaseTest { String[] fieldsArr = null; int lineNum = 0; int insertResult = 0; -// TableInfo tableInfo = new TableInfo(); -// tableInfo.setTableName(tableName); + // TableInfo tableInfo = new TableInfo(); + // tableInfo.setTableName(tableName); try { List> listField = new ArrayList<>(); while ((line = reader.readLine()) != null) { @@ -233,7 +233,7 @@ public class TestOrganization extends BaseTest { @Test public void testOrgChart() { - User user = new User(1); + User user = new User(35); OrgChartService orgChartService = new OrgChartService(); List orgChartTree = orgChartService.getOrgChartTree(user); System.out.println(JSON.toJSONString(orgChartTree)); diff --git a/src/test/java/youhong/ai/pcn/WorkflowTest.java b/src/test/java/youhong/ai/pcn/WorkflowTest.java index 71f6738..70caf2a 100644 --- a/src/test/java/youhong/ai/pcn/WorkflowTest.java +++ b/src/test/java/youhong/ai/pcn/WorkflowTest.java @@ -1,12 +1,22 @@ package youhong.ai.pcn; import aiyh.utils.Util; +import aiyh.utils.httpUtil.util.HttpUtils; import basetest.BaseTest; +import com.itextpdf.text.pdf.BaseFont; +import org.jsoup.Jsoup; +import org.jsoup.nodes.Document; import org.junit.Test; +import org.springframework.core.io.ClassPathResource; +import org.xhtmlrenderer.pdf.ITextFontResolver; +import org.xhtmlrenderer.pdf.ITextRenderer; +import weaver.email.EmailWorkRunnable; +import weaver.general.GCONST; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; +import java.io.File; +import java.io.FileOutputStream; +import java.io.OutputStream; +import java.util.*; /** *

流程相关测试

@@ -28,4 +38,127 @@ public class WorkflowTest extends BaseTest { .reduce(0, Integer::sum); System.out.println(sum); } + + + @Test + public void testEmail() { + String content = "

各位大佬:

\n" + + "

先前注册的gitea私有云仓库账号,域名备案已完成,现登陆仓库时请使用域名登陆!

\n" + + "
\n" + + "

私有仓库登陆地址:gitea私有仓库login

\n" + + "
\n" + + "

登陆账号为先前注册的账号:#{zhanghao},默认密码为用户名!

\n" + + "

如已绑定仓库,需要重新设置仓库远程地址,方法如下:

\n" + + "
\n" + + " 执行命令:
\n" + + " git remote -v\n" + + "
比如:\n" + + "

\n" + + " origin http://1.****.82/ecology/ebu_ecology_dev1.git (fetch)
\n" + + " origin http://1.****.82/ecology/ebu_ecology_dev1.git (push)\n" + + "

\n" + + "

查看到remote的名称,一般默认为 origin

\n" + + "
\n" + + " 执行命令:
\n" + + " git remote set-url origin https://gitea.yeyaguitu.cn/ecology/ebu_ecology_dev1.git\n" + + "

其中 origin 为查询到的remote的名称

"; + List> list = new ArrayList<>(); + list.add(new HashMap() {{ + put("name", "bokang.xiao"); + put("email", "ic_excellent@qq.com"); + }}); + list.add(new HashMap() {{ + put("name", "chaoyang.he"); + put("email", "chaoyang.he@weaver.com.cn"); + }}); + list.add(new HashMap() {{ + put("name", "jiacheng.deng"); + put("email", "jiacheng.deng@weaver.com.cn"); + }}); + list.add(new HashMap() {{ + put("name", "jiayong.cao"); + put("email", "jiayong.cao@weaver.com.cn"); + }}); + list.add(new HashMap() {{ + put("name", "jingwei.tao"); + put("email", "jingwei.tao@weaver.com.cn"); + }}); + list.add(new HashMap() {{ + put("name", "weilin.zhu"); + put("email", "bleach_725@163.com"); + }}); + list.add(new HashMap() {{ + put("name", "xuanran.wang"); + put("email", "xuanran.wang@weaver.com.cn"); + }}); + list.add(new HashMap() {{ + put("name", "xvqiang.ren"); + put("email", "1215877336@qq.com"); + }}); + list.add(new HashMap() {{ + put("name", "youhong.ai"); + put("email", "youhong.ai@weaver.com.cn"); + }}); + for (Map map : list) { + EmailWorkRunnable.threadModeReminder(map.get("email"), "域名变更提醒补充", content.replace("#{zhanghao}", map.get("name"))); + } + } + + + @Test + public void testPdfFromWorkflow() throws Exception { + // 创建和初始化URL + //URL oracleURL = new URL("https://ecology.yeyaguitu.cn/spa/workflow/static4form/index.html#/main/workflow/req?requestid=50051&ismode=2&ismonitor=0&f_weaver_belongto_usertype=0&f_weaver_belongto_userid=1&urger=0&modeid=34&isprint=1"); + // 获取网页作为输入流 + //InputStream is = oracleURL.openStream(); + //ITextRenderer renderer = new ITextRenderer(); + //renderer.setDocument(); + //OutputStream os = new FileOutputStream(GCONST.getSysFilePath() + "testpdf.pdf"); + //renderer.layout(); + //renderer.createPDF(os); + //os.close(); + // 初始化HTML加载选项 + //HtmlLoadOptions htmloptions = new HtmlLoadOptions(); + // 将流加载到Document对象中 + //Document pdfDocument = new Document(is, htmloptions); + // 将输出另存为PDF格式 + //pdfDocument.save(GCONST.getSysFilePath() + "HTML-to-PDF.pdf"); + HttpUtils httpUtils = new HttpUtils(); + String htmlUrl = "https://ecology.yeyaguitu.cn/spa/workflow/static4form/index.html#/main/workflow/req?requestid=50051&ismode=2&ismonitor=0&f_weaver_belongto_usertype=0&f_weaver_belongto_userid=1&urger=0&modeid=34&isprint=1"; + log.info(Util.logStr("页面路径:{}", htmlUrl)); + String html = httpUtils.apiGet(htmlUrl).getEntityString(); + //String htmlContent = html.replace("", "") + // .replace("", "") + // .replace("", ""); + //log.info(Util.logStr("html内容:\n{}", htmlContent)); + File pdf = new File(GCONST.getSysFilePath() + "test.pdf"); + Document document = Jsoup.parse(html); + String html1 = document.html(); + HtmPdfUtil.html2pdf(html1, pdf); + + } } + +class HtmPdfUtil { + + /** + * 将HTML转成PDF格式的文件。html文件的格式比较严格 + * + * @param htmlContent + * @param pdfFile + * @throws Exception + */ + public static void html2pdf(String htmlContent, File pdfFile) throws Exception { + OutputStream os = new FileOutputStream(pdfFile); + ITextRenderer renderer = new ITextRenderer(); + renderer.setDocumentFromString(htmlContent); + // 中文 + ITextFontResolver fontResolver = renderer.getFontResolver(); + ClassPathResource resource = new ClassPathResource("font/simsun.ttc"); + fontResolver.addFont(resource.getURL().toString(), BaseFont.IDENTITY_H, BaseFont.EMBEDDED); + renderer.layout(); + renderer.createPDF(os); + os.close(); + } +} + From 958a9d702901f3b6352a20e5b1f36b0fd04c3a94 Mon Sep 17 00:00:00 2001 From: "youHong.ai" <774495953@qq.com> Date: Wed, 21 Dec 2022 23:02:27 +0800 Subject: [PATCH 24/33] =?UTF-8?q?=E6=B7=BB=E5=8A=A0maper=E4=BA=8B=E5=8A=A1?= =?UTF-8?q?=E6=94=AF=E6=8C=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 1 + src/main/java/aiyh/utils/Util.java | 37 +++ .../utils/recordset/BooleanTypeHandler.java | 20 +- .../aiyh/utils/recordset/DataTypeHandler.java | 42 ++- .../utils/recordset/FloatTypeHandler.java | 17 +- .../utils/recordset/IntegerTypeHandler.java | 38 ++- .../aiyh/utils/recordset/RecordsetUtil.java | 310 ++++++++++++++++-- .../aiyh/utils/recordset/ResultMapper.java | 233 ++++++++++++- .../utils/recordset/RsThreadLocalManager.java | 209 ++++++++++++ .../utils/recordset/StringTypeHandler.java | 18 +- .../aiyh/utils/recordset/TypeHandler.java | 11 +- .../renamefile/action/RenameDocFile.java | 27 ++ .../mapper/RenameDocFileMapper.java | 15 + src/test/java/youhong/ai/pcn/UtilTest.java | 33 ++ .../ai/pcn/mapper/TransTestMapper.java | 20 ++ .../java/youhong/ai/pcn/pojo/Student.java | 21 ++ 16 files changed, 998 insertions(+), 54 deletions(-) create mode 100644 src/main/java/aiyh/utils/recordset/RsThreadLocalManager.java create mode 100644 src/main/java/weaver/youhong/ai/fentian/renamefile/action/RenameDocFile.java create mode 100644 src/main/java/weaver/youhong/ai/fentian/renamefile/mapper/RenameDocFileMapper.java create mode 100644 src/test/java/youhong/ai/pcn/UtilTest.java create mode 100644 src/test/java/youhong/ai/pcn/mapper/TransTestMapper.java create mode 100644 src/test/java/youhong/ai/pcn/pojo/Student.java diff --git a/.gitignore b/.gitignore index 530ce3c..a85a048 100644 --- a/.gitignore +++ b/.gitignore @@ -43,6 +43,7 @@ DirectoryV2.xml src/main/resources/WEB-INF/sqllog/ java.io.tempdir/ ecology-9-dev.iml +src/test/resources/font diff --git a/src/main/java/aiyh/utils/Util.java b/src/main/java/aiyh/utils/Util.java index 9e9a5dc..1696df5 100644 --- a/src/main/java/aiyh/utils/Util.java +++ b/src/main/java/aiyh/utils/Util.java @@ -1976,6 +1976,43 @@ public class Util extends weaver.general.Util { return recordsetUtil.getMapper(t); } + /** + *

getTransMapper 获取事务对象mapper

+ * 2022/12/21 22:45 + * ************************************************************ + * + * @param t 类 + * @param 代理类 + * @return T + * @author youHong.ai ****************************************** + */ + public static T getTransMapper(Class t) { + return recordsetUtil.getMapper(t, false); + } + + /** + *

commitTransMapper 提交事务mapper的事务

+ * 2022/12/21 22:46 + * ************************************************************ + * + * @return boolean 是否提交成功 + * @author youHong.ai ****************************************** + */ + public static boolean commitTransMapper() { + return recordsetUtil.getRsManager().commit(); + } + + /** + *

rollbackTransMapper 回滚事务mapper 的事务

+ * 2022/12/21 22:46 + * ************************************************************ + * + * @return boolean 是否回滚成功 + * @author youHong.ai ****************************************** + */ + public static boolean rollbackTransMapper() { + return recordsetUtil.getRsManager().rollback(); + } /** * join方法 diff --git a/src/main/java/aiyh/utils/recordset/BooleanTypeHandler.java b/src/main/java/aiyh/utils/recordset/BooleanTypeHandler.java index 2a1bae5..76fcc92 100644 --- a/src/main/java/aiyh/utils/recordset/BooleanTypeHandler.java +++ b/src/main/java/aiyh/utils/recordset/BooleanTypeHandler.java @@ -6,23 +6,33 @@ import aiyh.utils.excention.CustomerException; import com.google.common.base.Strings; import org.jetbrains.annotations.NotNull; import weaver.conn.RecordSet; +import weaver.conn.RecordSetTrans; import java.lang.reflect.Field; /** - * @author EBU7-dev1-ayh - * create 2021/12/21 0021 13:34 + * @author EBU7-dev1-ayh create 2021/12/21 0021 13:34 */ -public class BooleanTypeHandler implements TypeHandler{ +public class BooleanTypeHandler implements TypeHandler { @Override public Object getValue(RecordSet rs, String fieldName, Field declaredField) { return getBoolean(declaredField, rs.getString(fieldName)); } @Override - public Object getValue(RecordSet rs, int index,Field declaredField) { + public Object getValue(RecordSet rs, int index, Field declaredField) { + return getBoolean(declaredField, rs.getString(index)); + } + + @Override + public Object getValue(RecordSetTrans rs, String fieldName, Field declaredField) { + return getBoolean(declaredField, rs.getString(fieldName)); + } + + @Override + public Object getValue(RecordSetTrans rs, int index, Field declaredField) { return getBoolean(declaredField, rs.getString(index)); } @@ -58,7 +68,7 @@ public class BooleanTypeHandler implements TypeHandler{ } else { return defaultValue; } - }else { + } else { return defaultValue; } } catch (Exception e) { diff --git a/src/main/java/aiyh/utils/recordset/DataTypeHandler.java b/src/main/java/aiyh/utils/recordset/DataTypeHandler.java index dfb18e8..2e6fa85 100644 --- a/src/main/java/aiyh/utils/recordset/DataTypeHandler.java +++ b/src/main/java/aiyh/utils/recordset/DataTypeHandler.java @@ -4,14 +4,14 @@ import aiyh.utils.annotation.DateFormatAn; import aiyh.utils.excention.TypeNonsupportException; import com.ibm.icu.text.SimpleDateFormat; import weaver.conn.RecordSet; +import weaver.conn.RecordSetTrans; import java.lang.reflect.Field; import java.text.ParseException; import java.util.Date; /** - * @author EBU7-dev1-ayh - * create 2021/12/21 0021 13:35 + * @author EBU7-dev1-ayh create 2021/12/21 0021 13:35 */ @@ -53,4 +53,42 @@ public class DataTypeHandler implements TypeHandler { } return date; } + + @Override + public Object getValue(RecordSetTrans rs, String fieldName, Field declaredField) { + if (declaredField == null) { + throw new TypeNonsupportException("An error occurred while trying to convert the query result field to type Date!"); + } + DateFormatAn annotation = declaredField.getAnnotation(DateFormatAn.class); + Date date = null; + if (annotation != null) { + String value = annotation.value(); + try { + date = new SimpleDateFormat(value).parse(rs.getString(fieldName)); + } catch (ParseException e) { + e.printStackTrace(); + throw new TypeNonsupportException("Failed to convert [" + rs.getString(fieldName) + "] to a Date object as [" + value + "]!!"); + } + } + return date; + } + + @Override + public Object getValue(RecordSetTrans rs, int index, Field declaredField) { + if (declaredField == null) { + throw new TypeNonsupportException("An error occurred while trying to convert the query result field to type Date!"); + } + DateFormatAn annotation = declaredField.getAnnotation(DateFormatAn.class); + Date date = null; + if (annotation != null) { + String value = annotation.value(); + try { + date = new SimpleDateFormat(value).parse(rs.getString(index)); + } catch (ParseException e) { + e.printStackTrace(); + throw new TypeNonsupportException("Failed to convert [" + rs.getString(index) + "] to a Date object as [" + value + "]!!"); + } + } + return date; + } } diff --git a/src/main/java/aiyh/utils/recordset/FloatTypeHandler.java b/src/main/java/aiyh/utils/recordset/FloatTypeHandler.java index 474895f..7eda059 100644 --- a/src/main/java/aiyh/utils/recordset/FloatTypeHandler.java +++ b/src/main/java/aiyh/utils/recordset/FloatTypeHandler.java @@ -2,6 +2,7 @@ package aiyh.utils.recordset; import aiyh.utils.Util; import weaver.conn.RecordSet; +import weaver.conn.RecordSetTrans; import java.lang.reflect.Field; @@ -15,13 +16,25 @@ import java.lang.reflect.Field; public class FloatTypeHandler implements TypeHandler { @Override public Object getValue(RecordSet rs, String fieldName, Field declaredField) { - String string = Util.null2DefaultStr(rs.getString(fieldName),"0.0"); + String string = Util.null2DefaultStr(rs.getString(fieldName), "0.0"); return Float.parseFloat(string); } @Override public Object getValue(RecordSet rs, int index, Field declaredField) { - String string = Util.null2DefaultStr(rs.getString(index),"0.0"); + String string = Util.null2DefaultStr(rs.getString(index), "0.0"); + return Float.parseFloat(string); + } + + @Override + public Object getValue(RecordSetTrans rs, String fieldName, Field declaredField) { + String string = Util.null2DefaultStr(rs.getString(fieldName), "0.0"); + return Float.parseFloat(string); + } + + @Override + public Object getValue(RecordSetTrans rs, int index, Field declaredField) { + String string = Util.null2DefaultStr(rs.getString(index), "0.0"); return Float.parseFloat(string); } } diff --git a/src/main/java/aiyh/utils/recordset/IntegerTypeHandler.java b/src/main/java/aiyh/utils/recordset/IntegerTypeHandler.java index 2eceae7..48c3b5c 100644 --- a/src/main/java/aiyh/utils/recordset/IntegerTypeHandler.java +++ b/src/main/java/aiyh/utils/recordset/IntegerTypeHandler.java @@ -2,30 +2,48 @@ package aiyh.utils.recordset; import aiyh.utils.Util; import weaver.conn.RecordSet; +import weaver.conn.RecordSetTrans; import java.lang.reflect.Field; /** - * @author EBU7-dev1-ayh - * create 2021/12/21 0021 13:10 + * @author EBU7-dev1-ayh create 2021/12/21 0021 13:10 */ -public class IntegerTypeHandler implements TypeHandler{ +public class IntegerTypeHandler implements TypeHandler { @Override public Object getValue(RecordSet rs, String fieldName, Field declaredField) { - String string = Util.null2DefaultStr(rs.getString(fieldName),"-1"); - if(string.contains(".")){ - string = string.substring(0,string.indexOf(".")); + String string = Util.null2DefaultStr(rs.getString(fieldName), "-1"); + if (string.contains(".")) { + string = string.substring(0, string.indexOf(".")); } return Integer.parseInt(string); } @Override - public Object getValue(RecordSet rs, int index,Field declaredField) { - String string = Util.null2DefaultStr(rs.getString(index),"-1"); - if(string.contains(".")){ - string = string.substring(0,string.indexOf(".")); + public Object getValue(RecordSet rs, int index, Field declaredField) { + String string = Util.null2DefaultStr(rs.getString(index), "-1"); + if (string.contains(".")) { + string = string.substring(0, string.indexOf(".")); + } + return Integer.parseInt(string); + } + + @Override + public Object getValue(RecordSetTrans rs, String fieldName, Field declaredField) { + String string = Util.null2DefaultStr(rs.getString(fieldName), "-1"); + if (string.contains(".")) { + string = string.substring(0, string.indexOf(".")); + } + return Integer.parseInt(string); + } + + @Override + public Object getValue(RecordSetTrans rs, int index, Field declaredField) { + String string = Util.null2DefaultStr(rs.getString(index), "-1"); + if (string.contains(".")) { + string = string.substring(0, string.indexOf(".")); } return Integer.parseInt(string); } diff --git a/src/main/java/aiyh/utils/recordset/RecordsetUtil.java b/src/main/java/aiyh/utils/recordset/RecordsetUtil.java index 9b2c5f5..e82a60f 100644 --- a/src/main/java/aiyh/utils/recordset/RecordsetUtil.java +++ b/src/main/java/aiyh/utils/recordset/RecordsetUtil.java @@ -7,10 +7,13 @@ import aiyh.utils.excention.CustomerException; import aiyh.utils.sqlUtil.sqlResult.impl.BatchSqlResultImpl; import aiyh.utils.sqlUtil.sqlResult.impl.PrepSqlResultImpl; import weaver.conn.RecordSet; +import weaver.conn.RecordSetTrans; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; +import java.util.ArrayList; +import java.util.List; /** * @author EBU7-dev1-ayh create 2021/12/19 0019 14:39 @@ -19,24 +22,43 @@ import java.lang.reflect.Proxy; public class RecordsetUtil implements InvocationHandler { - private final RecordSet recordSet = new RecordSet(); - private final RecordSet rs = new RecordSet(); + public static final String SQL_LOG = "sql_log"; + private final RsThreadLocalManager rsManager = new RsThreadLocalManager(); + + private boolean autoCommit = true; public T getMapper(Class tClass) { + return getMapper(tClass, true); + } + + public T getMapper(Class tClass, boolean autoCommit) { if (tClass == null) { throw new BindingException("class is null!"); } if (tClass.getAnnotation(SqlMapper.class) == null) { throw new BindingException("can not find SqlMapper annotation!"); } + this.autoCommit = autoCommit; return (T) Proxy.newProxyInstance(tClass.getClassLoader(), new Class[]{tClass}, this); } @Override public Object invoke(Object proxy, Method method, Object[] args) { + if (autoCommit) { + return invokeRs(proxy, method, args); + } + return invokeRsTrans(proxy, method, args); + } + + private Object invokeRs(Object proxy, Method method, Object[] args) { + RecordSet rs = rsManager.getRs(); + if (rs == null) { + rsManager.setRecordSet(); + rs = rsManager.getRs(); + } SqlHandler sqlHandler = new SqlHandler(); ResultMapper resultMapper = new ResultMapper(); Select select = method.getAnnotation(Select.class); @@ -48,7 +70,7 @@ public class RecordsetUtil implements InvocationHandler { if (!handler.getSqlStr().trim().toLowerCase().startsWith("select ")) { throw new CustomerException("The sql statement does not match, the @Select annotation can only getDataId the select statement, please check whether the sql statement matches!"); } - Util.getLogger("sql_log").info("解析sql===>" + handler); + Util.getLogger(SQL_LOG).info("解析sql===>" + handler); if (handler.getArgs().isEmpty()) { rs.executeQuery(handler.getSqlStr()); } else { @@ -57,7 +79,6 @@ public class RecordsetUtil implements InvocationHandler { return resultMapper.mapperResult(rs, method, method.getReturnType()); } Update update = method.getAnnotation(Update.class); - if (update != null) { // 查询 String sql = update.value(); @@ -66,13 +87,13 @@ public class RecordsetUtil implements InvocationHandler { if (!handler.getSqlStr().trim().toLowerCase().startsWith("update ")) { throw new CustomerException("The sql statement does not match, the @Update annotation can only getDataId the update statement, please check whether the sql statement matches!"); } - Util.getLogger("sql_log").info(handler.toString()); + Util.getLogger(SQL_LOG).info(handler.toString()); Class returnType = method.getReturnType(); boolean b; if (handler.getArgs().isEmpty()) { - b = recordSet.executeUpdate(handler.getSqlStr()); + b = rs.executeUpdate(handler.getSqlStr()); } else { - b = recordSet.executeUpdate(handler.getSqlStr(), handler.getArgs()); + b = rs.executeUpdate(handler.getSqlStr(), handler.getArgs()); } if (returnType.equals(void.class)) { return null; @@ -97,13 +118,13 @@ public class RecordsetUtil implements InvocationHandler { if (!handler.getSqlStr().trim().toLowerCase().startsWith("insert ")) { throw new CustomerException("The sql statement does not match, the @Insert annotation can only getDataId the insert statement, please check whether the sql statement matches!"); } - Util.getLogger("sql_log").info(handler.toString()); + Util.getLogger(SQL_LOG).info(handler.toString()); Class returnType = method.getReturnType(); boolean b; if (handler.getArgs().isEmpty()) { - b = recordSet.executeUpdate(handler.getSqlStr()); + b = rs.executeUpdate(handler.getSqlStr()); } else { - b = recordSet.executeUpdate(handler.getSqlStr(), handler.getArgs()); + b = rs.executeUpdate(handler.getSqlStr(), handler.getArgs()); } if (returnType.equals(void.class)) { return null; @@ -121,13 +142,13 @@ public class RecordsetUtil implements InvocationHandler { if (!handler.getSqlStr().trim().toLowerCase().startsWith("delete ")) { throw new CustomerException("The sql statement does not match, the @Delete annotation can only getDataId the delete statement, please check whether the sql statement matches!"); } - Util.getLogger("sql_log").info(handler.toString()); + Util.getLogger(SQL_LOG).info(handler.toString()); Class returnType = method.getReturnType(); boolean b; if (handler.getArgs().isEmpty()) { - b = recordSet.executeUpdate(handler.getSqlStr()); + b = rs.executeUpdate(handler.getSqlStr()); } else { - b = recordSet.executeUpdate(handler.getSqlStr(), handler.getArgs()); + b = rs.executeUpdate(handler.getSqlStr(), handler.getArgs()); } if (returnType.equals(void.class)) { return null; @@ -143,14 +164,14 @@ public class RecordsetUtil implements InvocationHandler { Class returnType = method.getReturnType(); boolean custom = batchInsert.custom(); BatchSqlResultImpl batchSqlResult = sqlHandler.handlerBatch(sql, custom, method, args); - Util.getLogger("sql_log").info(batchSqlResult.toString()); + Util.getLogger(SQL_LOG).info(batchSqlResult.toString()); if (batchSqlResult.getBatchList().isEmpty()) { throw new CustomerException("getDataId batch sql error , batch sql args is empty!"); } if (!batchSqlResult.getSqlStr().trim().toLowerCase().startsWith("insert ")) { throw new CustomerException("The sql statement does not match, the @Insert annotation can only getDataId the insert statement, please check whether the sql statement matches!"); } - boolean b = recordSet.executeBatchSql(batchSqlResult.getSqlStr(), batchSqlResult.getBatchList()); + boolean b = rs.executeBatchSql(batchSqlResult.getSqlStr(), batchSqlResult.getBatchList()); if (returnType.equals(void.class)) { return null; } @@ -166,14 +187,14 @@ public class RecordsetUtil implements InvocationHandler { Class returnType = method.getReturnType(); boolean custom = batchUpdate.custom(); BatchSqlResultImpl batchSqlResult = sqlHandler.handlerBatch(sql, custom, method, args); - Util.getLogger("sql_log").info(batchSqlResult.toString()); + Util.getLogger(SQL_LOG).info(batchSqlResult.toString()); if (batchSqlResult.getBatchList().isEmpty()) { throw new CustomerException("getDataId batch sql error , batch sql args is empty!"); } if (!batchSqlResult.getSqlStr().trim().toLowerCase().startsWith("update ")) { throw new CustomerException("The sql statement does not match, the @Update annotation can only getDataId the update statement, please check whether the sql statement matches!"); } - boolean b = recordSet.executeBatchSql(batchSqlResult.getSqlStr(), batchSqlResult.getBatchList()); + boolean b = rs.executeBatchSql(batchSqlResult.getSqlStr(), batchSqlResult.getBatchList()); if (returnType.equals(void.class)) { return null; } @@ -189,14 +210,14 @@ public class RecordsetUtil implements InvocationHandler { Class returnType = method.getReturnType(); boolean custom = batchDelete.custom(); BatchSqlResultImpl batchSqlResult = sqlHandler.handlerBatch(sql, custom, method, args); - Util.getLogger("sql_log").info(batchSqlResult.toString()); + Util.getLogger(SQL_LOG).info(batchSqlResult.toString()); if (batchSqlResult.getBatchList().isEmpty()) { throw new CustomerException("getDataId batch sql error , batch sql args is empty!"); } if (!batchSqlResult.getSqlStr().trim().toLowerCase().startsWith("delete ")) { throw new CustomerException("The sql statement does not match, the @Delete annotation can only getDataId the delete statement, please check whether the sql statement matches!"); } - boolean b = recordSet.executeBatchSql(batchSqlResult.getSqlStr(), batchSqlResult.getBatchList()); + boolean b = rs.executeBatchSql(batchSqlResult.getSqlStr(), batchSqlResult.getBatchList()); if (returnType.equals(void.class)) { return null; } @@ -208,4 +229,255 @@ public class RecordsetUtil implements InvocationHandler { throw new CustomerException("该方法没有添加注解!请检查是否正确添加注解!@Select、@Update、@Insert、@Delete、@BatchUpdate、@BatchInsert、@BatchDelete"); } + private Object invokeRsTrans(Object proxy, Method method, Object[] args) { + RecordSetTrans rs = rsManager.getTrans(); + if (rs == null) { + rsManager.setRecordSetTrans(); + rs = rsManager.getTrans(); + } + SqlHandler sqlHandler = new SqlHandler(); + ResultMapper resultMapper = new ResultMapper(); + Select select = method.getAnnotation(Select.class); + if (select != null) { + // 查询 + String sql = select.value(); + boolean custom = select.custom(); + PrepSqlResultImpl handler = sqlHandler.handler(sql, custom, method, args); + if (!handler.getSqlStr().trim().toLowerCase().startsWith("select ")) { + throw new CustomerException("The sql statement does not match, the @Select annotation can only getDataId the select statement, please check whether the sql statement matches!"); + } + Util.getLogger(SQL_LOG).info("解析sql===>" + handler); + try { + if (handler.getArgs().isEmpty()) { + rs.executeQuery(handler.getSqlStr()); + } else { + rs.executeQuery(handler.getSqlStr(), handler.getArgs()); + } + } catch (Exception e) { + Util.getLogger(SQL_LOG).error("execute sql error! " + Util.getErrString(e)); + throw new CustomerException("execute sql error!" + e.getMessage()); + } + return resultMapper.mapperResult(rs, method, method.getReturnType()); + } + + Update update = method.getAnnotation(Update.class); + if (update != null) { + // 查询 + String sql = update.value(); + boolean custom = update.custom(); + PrepSqlResultImpl handler = sqlHandler.handler(sql, custom, method, args); + if (!handler.getSqlStr().trim().toLowerCase().startsWith("update ")) { + throw new CustomerException("The sql statement does not match, the @Update annotation can only getDataId the update statement, please check whether the sql statement matches!"); + } + Util.getLogger(SQL_LOG).info(handler.toString()); + Class returnType = method.getReturnType(); + boolean b; + try { + if (handler.getArgs().isEmpty()) { + b = rs.executeUpdate(handler.getSqlStr()); + } else { + b = rs.executeUpdate(handler.getSqlStr(), handler.getArgs()); + } + } catch (Exception e) { + Util.getLogger(SQL_LOG).error("execute sql error! " + Util.getErrString(e)); + throw new CustomerException("execute sql error!" + e.getMessage()); + } + if (returnType.equals(void.class)) { + return null; + } + if (returnType.equals(int.class) || returnType.equals(Integer.class)) { + if (b) { + return 1; + } else { + return 0; + } + } + if (returnType.equals(boolean.class) || returnType.equals(Boolean.class)) { + return b; + } + } + Insert insert = method.getAnnotation(Insert.class); + if (insert != null) { + // 查询 + String sql = insert.value(); + boolean custom = insert.custom(); + PrepSqlResultImpl handler = sqlHandler.handler(sql, custom, method, args); + if (!handler.getSqlStr().trim().toLowerCase().startsWith("insert ")) { + throw new CustomerException("The sql statement does not match, the @Insert annotation can only getDataId the insert statement, please check whether the sql statement matches!"); + } + Util.getLogger(SQL_LOG).info(handler.toString()); + Class returnType = method.getReturnType(); + boolean b; + try { + if (handler.getArgs().isEmpty()) { + b = rs.executeUpdate(handler.getSqlStr()); + } else { + b = rs.executeUpdate(handler.getSqlStr(), handler.getArgs()); + } + } catch (Exception e) { + Util.getLogger(SQL_LOG).error("execute sql error! " + Util.getErrString(e)); + throw new CustomerException("execute sql error!" + e.getMessage()); + } + if (returnType.equals(void.class)) { + return null; + } + if (returnType.equals(boolean.class) || returnType.equals(Boolean.class)) { + return b; + } + } + Delete delete = method.getAnnotation(Delete.class); + if (delete != null) { + // 查询 + String sql = delete.value(); + boolean custom = delete.custom(); + PrepSqlResultImpl handler = sqlHandler.handler(sql, custom, method, args); + if (!handler.getSqlStr().trim().toLowerCase().startsWith("delete ")) { + throw new CustomerException("The sql statement does not match, the @Delete annotation can only getDataId the delete statement, please check whether the sql statement matches!"); + } + Util.getLogger(SQL_LOG).info(handler.toString()); + Class returnType = method.getReturnType(); + boolean b; + try { + if (handler.getArgs().isEmpty()) { + b = rs.executeUpdate(handler.getSqlStr()); + } else { + b = rs.executeUpdate(handler.getSqlStr(), handler.getArgs()); + } + } catch (Exception e) { + Util.getLogger(SQL_LOG).error("execute sql error! " + Util.getErrString(e)); + throw new CustomerException("execute sql error!" + e.getMessage()); + } + if (returnType.equals(void.class)) { + return null; + } + if (returnType.equals(boolean.class) || returnType.equals(Boolean.class)) { + return b; + } + } + boolean hasBatchInsert = method.isAnnotationPresent(BatchInsert.class); + if (hasBatchInsert) { + BatchInsert batchInsert = method.getAnnotation(BatchInsert.class); + String sql = batchInsert.value(); + Class returnType = method.getReturnType(); + boolean custom = batchInsert.custom(); + BatchSqlResultImpl batchSqlResult = sqlHandler.handlerBatch(sql, custom, method, args); + Util.getLogger(SQL_LOG).info(batchSqlResult.toString()); + List batchList = batchSqlResult.getBatchList(); + if (batchList.isEmpty()) { + throw new CustomerException("getDataId batch sql error , batch sql args is empty!"); + } + List> batchListTrans = new ArrayList<>(); + for (List list : batchList) { + List listItem = new ArrayList<>(); + for (Object o : list) { + listItem.add(o); + } + batchListTrans.add(listItem); + } + + if (!batchSqlResult.getSqlStr().trim().toLowerCase().startsWith("insert ")) { + throw new CustomerException("The sql statement does not match, the @Insert annotation can only getDataId the insert statement, please check whether the sql statement matches!"); + } + boolean b = true; + try { + rs.executeBatchSql(batchSqlResult.getSqlStr(), batchListTrans); + } catch (Exception e) { + Util.getLogger(SQL_LOG).error("execute sql error! " + Util.getErrString(e)); + throw new CustomerException("execute sql error!" + e.getMessage()); + } + if (returnType.equals(void.class)) { + return null; + } + if (returnType.equals(boolean.class) || returnType.equals(Boolean.class)) { + return b; + } + + } + boolean hasBatchUpdate = method.isAnnotationPresent(BatchUpdate.class); + if (hasBatchUpdate) { + BatchUpdate batchUpdate = method.getAnnotation(BatchUpdate.class); + String sql = batchUpdate.value(); + Class returnType = method.getReturnType(); + boolean custom = batchUpdate.custom(); + BatchSqlResultImpl batchSqlResult = sqlHandler.handlerBatch(sql, custom, method, args); + Util.getLogger(SQL_LOG).info(batchSqlResult.toString()); + if (batchSqlResult.getBatchList().isEmpty()) { + throw new CustomerException("getDataId batch sql error , batch sql args is empty!"); + } + if (!batchSqlResult.getSqlStr().trim().toLowerCase().startsWith("update ")) { + throw new CustomerException("The sql statement does not match, the @Update annotation can only getDataId the update statement, please check whether the sql statement matches!"); + } + + List batchList = batchSqlResult.getBatchList(); + if (batchList.isEmpty()) { + throw new CustomerException("getDataId batch sql error , batch sql args is empty!"); + } + List> batchListTrans = new ArrayList<>(); + for (List list : batchList) { + List listItem = new ArrayList<>(); + for (Object o : list) { + listItem.add(o); + } + batchListTrans.add(listItem); + } + try { + rs.executeBatchSql(batchSqlResult.getSqlStr(), batchListTrans); + } catch (Exception e) { + Util.getLogger(SQL_LOG).error("execute sql error! " + Util.getErrString(e)); + throw new CustomerException("execute sql error!" + e.getMessage()); + } + if (returnType.equals(void.class)) { + return null; + } + if (returnType.equals(boolean.class) || returnType.equals(Boolean.class)) { + return true; + } + + } + boolean hasBatchDelete = method.isAnnotationPresent(BatchDelete.class); + if (hasBatchDelete) { + BatchDelete batchDelete = method.getAnnotation(BatchDelete.class); + String sql = batchDelete.value(); + Class returnType = method.getReturnType(); + boolean custom = batchDelete.custom(); + BatchSqlResultImpl batchSqlResult = sqlHandler.handlerBatch(sql, custom, method, args); + Util.getLogger(SQL_LOG).info(batchSqlResult.toString()); + if (batchSqlResult.getBatchList().isEmpty()) { + throw new CustomerException("getDataId batch sql error , batch sql args is empty!"); + } + if (!batchSqlResult.getSqlStr().trim().toLowerCase().startsWith("delete ")) { + throw new CustomerException("The sql statement does not match, the @Delete annotation can only getDataId the delete statement, please check whether the sql statement matches!"); + } + List batchList = batchSqlResult.getBatchList(); + if (batchList.isEmpty()) { + throw new CustomerException("getDataId batch sql error , batch sql args is empty!"); + } + List> batchListTrans = new ArrayList<>(); + for (List list : batchList) { + List listItem = new ArrayList<>(); + for (Object o : list) { + listItem.add(o); + } + batchListTrans.add(listItem); + } + try { + rs.executeBatchSql(batchSqlResult.getSqlStr(), batchListTrans); + } catch (Exception e) { + Util.getLogger(SQL_LOG).error("execute sql error! " + Util.getErrString(e)); + throw new CustomerException("execute sql error!" + e.getMessage()); + } + if (returnType.equals(void.class)) { + return null; + } + if (returnType.equals(boolean.class) || returnType.equals(Boolean.class)) { + return true; + } + + } + throw new CustomerException("该方法没有添加注解!请检查是否正确添加注解!@Select、@Update、@Insert、@Delete、@BatchUpdate、@BatchInsert、@BatchDelete"); + } + + public RsThreadLocalManager getRsManager() { + return rsManager; + } } diff --git a/src/main/java/aiyh/utils/recordset/ResultMapper.java b/src/main/java/aiyh/utils/recordset/ResultMapper.java index 23b28d7..083abee 100644 --- a/src/main/java/aiyh/utils/recordset/ResultMapper.java +++ b/src/main/java/aiyh/utils/recordset/ResultMapper.java @@ -15,8 +15,7 @@ import java.lang.reflect.*; import java.util.*; /** - * @author EBU7-dev1-ayh - * create 2021/12/21 0021 11:03 + * @author EBU7-dev1-ayh create 2021/12/21 0021 11:03 */ @@ -60,7 +59,7 @@ public class ResultMapper { } T t = tClass.newInstance(); if (t instanceof Collection) { -// 集合求出泛型 + // 集合求出泛型 //获取返回值的类型 Type genericReturnType = method.getGenericReturnType(); Type actualTypeArgument = ((ParameterizedType) genericReturnType).getActualTypeArguments()[0]; @@ -93,7 +92,7 @@ public class ResultMapper { return t; } if (t instanceof Map) { -// map + // map Type genericReturnType = method.getGenericReturnType(); Type actualTypeArgument = ((ParameterizedType) genericReturnType).getActualTypeArguments()[0]; Class rawType = this.getRawType(actualTypeArgument); @@ -103,7 +102,7 @@ public class ResultMapper { if (rawType.equals(Map.class)) { rawType = HashMap.class; } -// Object o = rawType.newInstance(); + // Object o = rawType.newInstance(); Object o = null; try { Constructor constructor = rawType.getConstructor(); @@ -143,6 +142,222 @@ public class ResultMapper { return null; } + public T mapperResult(RecordSetTrans rs, Method method, Class tClass) { + if (tClass.equals(void.class)) { + return null; + } + if (tClass.equals(RecordSet.class) || tClass.equals(RecordSetTrans.class)) { + return (T) rs; + } + try { + if (tClass.equals(List.class)) { + tClass = (Class) ArrayList.class; + } + if (tClass.equals(Map.class)) { + tClass = (Class) HashMap.class; + } + if (ResultMapper.typeHandler.containsKey(tClass)) { + rs.next(); + return (T) ResultMapper.typeHandler.get(tClass).getValue(rs, 1, null); + } + T t = tClass.newInstance(); + if (t instanceof Collection) { + // 集合求出泛型 + //获取返回值的类型 + Type genericReturnType = method.getGenericReturnType(); + Type actualTypeArgument = ((ParameterizedType) genericReturnType).getActualTypeArguments()[0]; + Class rawType = this.getRawType(actualTypeArgument); + if (rawType.equals(Map.class)) { + rawType = HashMap.class; + } + while (rs.next()) { + Object o = null; + try { + Constructor constructor = rawType.getConstructor(); + o = constructor.newInstance(); + } catch (NoSuchMethodException | InvocationTargetException ignored) { + if (Number.class.isAssignableFrom(rawType)) { + Constructor constructor; + try { + constructor = rawType.getConstructor(String.class); + o = constructor.newInstance("-1"); + } catch (NoSuchMethodException | InvocationTargetException e) { + throw new CustomerException("can not Initialization " + t.getClass() + " [" + rawType + "]", e); + } + } + } + if (o == null) { + throw new CustomerException("can not Initialization " + t.getClass() + " [" + rawType + "]"); + } + Object object = getObjectTrans(rs, o, method); + ((Collection) t).add(object); + } + return t; + } + if (t instanceof Map) { + // map + Type genericReturnType = method.getGenericReturnType(); + Type actualTypeArgument = ((ParameterizedType) genericReturnType).getActualTypeArguments()[0]; + Class rawType = this.getRawType(actualTypeArgument); + if (rawType.equals(List.class)) { + rawType = (Class) ArrayList.class; + } + if (rawType.equals(Map.class)) { + rawType = HashMap.class; + } + // Object o = rawType.newInstance(); + Object o = null; + try { + Constructor constructor = rawType.getConstructor(); + o = constructor.newInstance(); + } catch (NoSuchMethodException | InvocationTargetException ignored) { + if (Number.class.isAssignableFrom(rawType)) { + Constructor constructor; + try { + constructor = rawType.getConstructor(String.class); + o = constructor.newInstance("-1"); + } catch (NoSuchMethodException | InvocationTargetException e) { + throw new CustomerException("can not Initialization " + t.getClass() + " [" + rawType + "]", e); + } + } + } + if (o == null) { + throw new CustomerException("can not Initialization " + t.getClass() + " [" + rawType + "]"); + } + if (o instanceof Map || o instanceof Collection) { + throw new TypeNonsupportException("An unsupported return type!"); + } + if (rs.next()) { + return (T) getObjectTrans(rs, t, method); + } + return null; + } + if (t.getClass().isArray()) { + throw new TypeNonsupportException("An unsupported return type!"); + } + if (rs.next()) { + return (T) getObjectTrans(rs, t, method); + } + return null; + } catch (InstantiationException | IllegalAccessException e) { + e.printStackTrace(); + } + return null; + } + + public Object getObjectTrans(RecordSetTrans rs, Object o, Method method) { + CaseConversion annotation = method.getAnnotation(CaseConversion.class); + boolean enable = annotation == null ? true : annotation.value(); + String[] columnName = rs.getColumnName(); + String[] columnTypeName = rs.getColumnTypeName(); + int[] columnTypes = rs.getColumnType(); + if (columnTypeName == null) { + columnTypeName = new String[columnTypes.length]; + for (int i = 0; i < columnTypes.length; i++) { + int type = columnTypes[i]; + switch (type) { + case -1: + columnTypeName[i] = "TEXT"; + break; + case 4: + columnTypeName[i] = "INT"; + break; + case 12: + columnTypeName[i] = "VARCHAR"; + break; + default: + columnTypeName[i] = "VARCHAR"; + } + } + } + + try { + if (o instanceof Map) { + for (int i = 0; i < columnName.length; i++) { + String columnType = columnTypeName[i]; + if ("int".equalsIgnoreCase(columnType) || "long".equalsIgnoreCase(columnType) || "number".equalsIgnoreCase(columnType) || "MEDIUMINT".equalsIgnoreCase(columnType) || "TINYINT".equalsIgnoreCase(columnType) || "SMALLINT".equalsIgnoreCase(columnType) || "BIGINT".equalsIgnoreCase(columnType) || "INTEGER".equalsIgnoreCase(columnType)) { + if (enable) { + ((Map) o).put(Util.toCamelCase(columnName[i]), rs.getInt(i + 1)); + continue; + } + ((Map) o).put(columnName[i], rs.getInt(i + 1)); + continue; + } + if ("FLOAT".equalsIgnoreCase(columnType) || "DOUBLE".equalsIgnoreCase(columnType) || "DECIMAL".equalsIgnoreCase(columnType)) { + if (enable) { + ((Map) o).put(Util.toCamelCase(columnName[i]), rs.getFloat(i + 1)); + continue; + } + ((Map) o).put(columnName[i], rs.getFloat(i + 1)); + continue; + } + if (enable) { + ((Map) o).put(Util.toCamelCase(columnName[i]), rs.getString(i + 1)); + continue; + } + ((Map) o).put(columnName[i], rs.getString(i + 1)); + continue; + } + return o; + } + if (o instanceof Collection) { + throw new TypeNonsupportException("An unsupported return type!"); + } + if (o instanceof Number) { + for (int i = 0; i < columnName.length; i++) { + String columnType = columnTypeName[i]; + if ("int".equalsIgnoreCase(columnType) || "long".equalsIgnoreCase(columnType) || "number".equalsIgnoreCase(columnType) || "MEDIUMINT".equalsIgnoreCase(columnType) || "TINYINT".equalsIgnoreCase(columnType) || "SMALLINT".equalsIgnoreCase(columnType) || "BIGINT".equalsIgnoreCase(columnType) || "INTEGER".equalsIgnoreCase(columnType)) { + return rs.getInt(i + 1); + } + if ("FLOAT".equalsIgnoreCase(columnType) || "DOUBLE".equalsIgnoreCase(columnType) || "DECIMAL".equalsIgnoreCase(columnType)) { + return rs.getFloat(i + 1); + } + } + return o; + } + if (o instanceof String) { + for (int i = 0; i < columnName.length; i++) { + return rs.getString(i + 1); + } + return o; + } + if (o instanceof Boolean) { + for (int i = 0; i < columnName.length; i++) { + return rs.getBoolean(i + 1); + } + return o; + } + + // Util.getLogger().info("获取对象:" + o.toString()); + BeanInfo beanInfo = Introspector.getBeanInfo(o.getClass(), Object.class); + PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); + for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { + Class propertyType = propertyDescriptor.getPropertyType(); + Object value = null; + String fieldName = propertyDescriptor.getName(); + + if (Strings.isNullOrEmpty(fieldName)) { + fieldName = propertyDescriptor.getDisplayName(); + } + // Util.getLogger().info("获取类字段:" + fieldName); + // Util.getLogger().info("获取类字段1:" + propertyDescriptor.getDisplayName()); + // Util.getLogger().info("获取的数据库数据:" + rs.getString(fieldName)); + Field declaredField = o.getClass().getDeclaredField(fieldName); + if (enable) { + value = ResultMapper.typeHandler.get(propertyType) == null ? null : ResultMapper.typeHandler.get(propertyType).getValue(rs, Util.toUnderlineCase(fieldName), declaredField); + } else { + value = ResultMapper.typeHandler.get(propertyType) == null ? null : ResultMapper.typeHandler.get(propertyType).getValue(rs, fieldName, declaredField); + } + propertyDescriptor.getWriteMethod().invoke(o, value); + } + + } catch (Exception e) { + e.printStackTrace(); + Util.getLogger().error("报错了,写入数据到实体类报错!\n" + Util.getErrString(e)); + } + return o; + } + public Object getObject(RecordSet rs, Object o, Method method) { CaseConversion annotation = method.getAnnotation(CaseConversion.class); boolean enable = annotation == null ? true : annotation.value(); @@ -226,7 +441,7 @@ public class ResultMapper { return o; } -// Util.getLogger().info("获取对象:" + o.toString()); + // Util.getLogger().info("获取对象:" + o.toString()); BeanInfo beanInfo = Introspector.getBeanInfo(o.getClass(), Object.class); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { @@ -237,9 +452,9 @@ public class ResultMapper { if (Strings.isNullOrEmpty(fieldName)) { fieldName = propertyDescriptor.getDisplayName(); } -// Util.getLogger().info("获取类字段:" + fieldName); -// Util.getLogger().info("获取类字段1:" + propertyDescriptor.getDisplayName()); -// Util.getLogger().info("获取的数据库数据:" + rs.getString(fieldName)); + // Util.getLogger().info("获取类字段:" + fieldName); + // Util.getLogger().info("获取类字段1:" + propertyDescriptor.getDisplayName()); + // Util.getLogger().info("获取的数据库数据:" + rs.getString(fieldName)); Field declaredField = o.getClass().getDeclaredField(fieldName); if (enable) { value = ResultMapper.typeHandler.get(propertyType) == null ? null : ResultMapper.typeHandler.get(propertyType).getValue(rs, Util.toUnderlineCase(fieldName), declaredField); diff --git a/src/main/java/aiyh/utils/recordset/RsThreadLocalManager.java b/src/main/java/aiyh/utils/recordset/RsThreadLocalManager.java new file mode 100644 index 0000000..deacc1b --- /dev/null +++ b/src/main/java/aiyh/utils/recordset/RsThreadLocalManager.java @@ -0,0 +1,209 @@ +package aiyh.utils.recordset; + +import aiyh.utils.excention.CustomerException; +import weaver.conn.RecordSet; +import weaver.conn.RecordSetTrans; + +import java.util.Iterator; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +/** + *

ThreadLocal管理类

+ * + *

create: 2022-12-21 21:31

+ * + * @author youHong.ai + */ + +public class RsThreadLocalManager { + + private final ConcurrentHashMap rsMap = new ConcurrentHashMap<>(); + + private final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); + + public RsThreadLocalManager() { + startMonitor(); + } + + /** + *

定时清除过期的rs对象

+ * 2022/12/21 22:02 + * ************************************************************ + * + * @author youHong.ai ****************************************** + */ + private void startMonitor() { + executor.scheduleAtFixedRate(this::checkExpireRs, 0, 2, TimeUnit.MINUTES); + } + + /** + *

checkExpireRs 检查清除过期的rs对象

+ * 2022/12/21 22:02 + * ************************************************************ + * + * @author youHong.ai ****************************************** + */ + private void checkExpireRs() { + Iterator> iterator = rsMap.entrySet().iterator(); + while (iterator.hasNext()) { + Map.Entry entity = iterator.next(); + RsThreadLocalMap value = entity.getValue(); + if (System.currentTimeMillis() >= value.getExpireTime() || value.getExpireTime() != -1) { + iterator.remove(); + } + } + } + + /** + *

setRecordSet 设置当前线程的rs对象

+ * 2022/12/21 22:03 + * ************************************************************ + * + * @author youHong.ai ****************************************** + */ + public void setRecordSet() { + RsThreadLocalMap rsThreadLocalMap = new RsThreadLocalMap(new RecordSet(), getExpireTime()); + rsMap.put(Thread.currentThread().getId(), rsThreadLocalMap); + } + + /** + *

setRecordSet 设置当前线程的事务对象

+ * 2022/12/21 22:03 + * ************************************************************ + * + * @author youHong.ai ****************************************** + */ + public void setRecordSetTrans() { + RecordSetTrans recordSetTrans = new RecordSetTrans(); + recordSetTrans.setAutoCommit(false); + RsThreadLocalMap rsThreadLocalMap = new RsThreadLocalMap(recordSetTrans, -1L); + rsMap.put(Thread.currentThread().getId(), rsThreadLocalMap); + } + + /** + *

getExpireTime 获取过期时间

+ * 2022/12/21 22:06 + * ************************************************************ + * + * @return Long + * @author youHong.ai ****************************************** + */ + public Long getExpireTime() { + return System.currentTimeMillis() + 1000L * 60 * 3; + } + + + /** + *

getRs 获取当前线程的rs对象

+ * 2022/12/21 22:04 + * ************************************************************ + * + * @return RecordSet + * @author youHong.ai ****************************************** + */ + public RecordSet getRs() { + RsThreadLocalMap rsThreadLocalMap = rsMap.get(Thread.currentThread().getId()); + if (Objects.isNull(rsThreadLocalMap)) { + return null; + } + rsThreadLocalMap.setExpireTime(getExpireTime()); + return rsThreadLocalMap.getRecordSet(); + } + + /** + *

getTrans 获取当前线程的事务rs

+ * 2022/12/21 22:04 + * ************************************************************ + * + * @return RecordSetTrans 事务rs + * @author youHong.ai ****************************************** + */ + public RecordSetTrans getTrans() { + RsThreadLocalMap rsThreadLocalMap = rsMap.get(Thread.currentThread().getId()); + if (Objects.isNull(rsThreadLocalMap)) { + return null; + } + rsThreadLocalMap.setExpireTime(-1L); + return rsThreadLocalMap.getRecordSetTrans(); + } + + public boolean commit() { + RsThreadLocalMap rsThreadLocalMap = rsMap.get(Thread.currentThread().getId()); + if (Objects.isNull(rsThreadLocalMap)) { + throw new CustomerException("can not find RecordSetTrans instance! please Contact the developer of RecordsetUtil.java!"); + } + rsThreadLocalMap.setExpireTime(getExpireTime()); + RecordSetTrans recordSetTrans = rsThreadLocalMap.getRecordSetTrans(); + return recordSetTrans.commit(); + } + + + public boolean rollback() { + RsThreadLocalMap rsThreadLocalMap = rsMap.get(Thread.currentThread().getId()); + if (Objects.isNull(rsThreadLocalMap)) { + throw new CustomerException("can not find RecordSetTrans instance! please Contact the developer of RecordsetUtil.java!"); + } + rsThreadLocalMap.setExpireTime(getExpireTime()); + RecordSetTrans recordSetTrans = rsThreadLocalMap.getRecordSetTrans(); + return recordSetTrans.rollback(); + } + + + /** + *

remove 删除当前线程的rs对象

+ * 2022/12/21 22:05 + * ************************************************************ + * + * @author youHong.ai ****************************************** + */ + public void remove() { + rsMap.remove(Thread.currentThread().getId()); + } + + + static class RsThreadLocalMap { + private RecordSet recordSet; + + private RecordSetTrans recordSetTrans; + private Long expireTime; + + public RsThreadLocalMap(RecordSet recordSet, Long expireTime) { + this.recordSet = recordSet; + this.expireTime = expireTime; + } + + public RsThreadLocalMap(RecordSetTrans recordSetTrans, Long expireTime) { + this.recordSetTrans = recordSetTrans; + this.expireTime = expireTime; + } + + public RecordSetTrans getRecordSetTrans() { + return recordSetTrans; + } + + public void setRecordSetTrans(RecordSetTrans recordSetTrans) { + this.recordSetTrans = recordSetTrans; + } + + public RecordSet getRecordSet() { + return recordSet; + } + + public void setRecordSet(RecordSet recordSet) { + this.recordSet = recordSet; + } + + public Long getExpireTime() { + return expireTime; + } + + public void setExpireTime(Long expireTime) { + this.expireTime = expireTime; + } + } +} diff --git a/src/main/java/aiyh/utils/recordset/StringTypeHandler.java b/src/main/java/aiyh/utils/recordset/StringTypeHandler.java index 17fdf7a..042d5da 100644 --- a/src/main/java/aiyh/utils/recordset/StringTypeHandler.java +++ b/src/main/java/aiyh/utils/recordset/StringTypeHandler.java @@ -1,23 +1,33 @@ package aiyh.utils.recordset; import weaver.conn.RecordSet; +import weaver.conn.RecordSetTrans; import java.lang.reflect.Field; /** - * @author EBU7-dev1-ayh - * create 2021/12/21 0021 13:06 + * @author EBU7-dev1-ayh create 2021/12/21 0021 13:06 */ -public class StringTypeHandler implements TypeHandler{ +public class StringTypeHandler implements TypeHandler { @Override public Object getValue(RecordSet rs, String fieldName, Field declaredField) { return rs.getString(fieldName); } @Override - public Object getValue(RecordSet rs, int index,Field declaredField) { + public Object getValue(RecordSet rs, int index, Field declaredField) { + return rs.getString(index); + } + + @Override + public Object getValue(RecordSetTrans rs, String fieldName, Field declaredField) { + return rs.getString(fieldName); + } + + @Override + public Object getValue(RecordSetTrans rs, int index, Field declaredField) { return rs.getString(index); } } diff --git a/src/main/java/aiyh/utils/recordset/TypeHandler.java b/src/main/java/aiyh/utils/recordset/TypeHandler.java index 42df5a7..a85defa 100644 --- a/src/main/java/aiyh/utils/recordset/TypeHandler.java +++ b/src/main/java/aiyh/utils/recordset/TypeHandler.java @@ -1,15 +1,20 @@ package aiyh.utils.recordset; import weaver.conn.RecordSet; +import weaver.conn.RecordSetTrans; import java.lang.reflect.Field; /** - * @author @author EBU7-dev1-ay - * create 2021/12/21 0021 13:05 + * @author @author EBU7-dev1-ay create 2021/12/21 0021 13:05 */ public interface TypeHandler { Object getValue(RecordSet rs, String fieldName, Field declaredField); - Object getValue(RecordSet rs,int index,Field declaredField); + + Object getValue(RecordSet rs, int index, Field declaredField); + + Object getValue(RecordSetTrans rs, String fieldName, Field declaredField); + + Object getValue(RecordSetTrans rs, int index, Field declaredField); } diff --git a/src/main/java/weaver/youhong/ai/fentian/renamefile/action/RenameDocFile.java b/src/main/java/weaver/youhong/ai/fentian/renamefile/action/RenameDocFile.java new file mode 100644 index 0000000..9fa9779 --- /dev/null +++ b/src/main/java/weaver/youhong/ai/fentian/renamefile/action/RenameDocFile.java @@ -0,0 +1,27 @@ +package weaver.youhong.ai.fentian.renamefile.action; + +import aiyh.utils.Util; +import aiyh.utils.action.SafeCusBaseAction; +import aiyh.utils.annotation.ActionDesc; +import lombok.Setter; +import weaver.hrm.User; +import weaver.soa.workflow.request.RequestInfo; +import weaver.youhong.ai.fentian.renamefile.mapper.RenameDocFileMapper; + +/** + *

重命名流程字段中的附件字段

+ * + *

create: 2022-12-15 11:38

+ * + * @author youHong.ai + */ + +@ActionDesc(value = "重命名流程字段中的附件字段的附件名称",author = "youhong.ai") +@Setter +public class RenameDocFile extends SafeCusBaseAction { + private final RenameDocFileMapper mapper = Util.getMapper(RenameDocFileMapper.class); + @Override + public void doSubmit(String requestId, String billTable, int workflowId, User user, RequestInfo requestInfo) { + + } +} diff --git a/src/main/java/weaver/youhong/ai/fentian/renamefile/mapper/RenameDocFileMapper.java b/src/main/java/weaver/youhong/ai/fentian/renamefile/mapper/RenameDocFileMapper.java new file mode 100644 index 0000000..540867d --- /dev/null +++ b/src/main/java/weaver/youhong/ai/fentian/renamefile/mapper/RenameDocFileMapper.java @@ -0,0 +1,15 @@ +package weaver.youhong.ai.fentian.renamefile.mapper; + +import aiyh.utils.annotation.recordset.SqlMapper; + +/** + *

+ * + *

create: 2022-12-15 11:40

+ * + * @author youHong.ai + */ + +@SqlMapper +public interface RenameDocFileMapper { +} diff --git a/src/test/java/youhong/ai/pcn/UtilTest.java b/src/test/java/youhong/ai/pcn/UtilTest.java new file mode 100644 index 0000000..6ee36c1 --- /dev/null +++ b/src/test/java/youhong/ai/pcn/UtilTest.java @@ -0,0 +1,33 @@ +package youhong.ai.pcn; + +import aiyh.utils.Util; +import basetest.BaseTest; +import ebu7common.youhong.ai.bean.Builder; +import org.junit.Test; +import youhong.ai.pcn.mapper.TransTestMapper; +import youhong.ai.pcn.pojo.Student; + +/** + *

测试

+ * + *

create: 2022-12-21 21:22

+ * + * @author youHong.ai + */ + +public class UtilTest extends BaseTest { + + @Test + public void test() { + + TransTestMapper transMapper = Util.getTransMapper(TransTestMapper.class); + Student student = Builder.builder(Student::new) + .with(Student::setName, "王小明") + .with(Student::setAge, 10) + .with(Student::setSex, 1).build(); + boolean b = transMapper.insertStudent(student); + System.out.println(b); + System.out.println(Util.commitTransMapper()); + + } +} diff --git a/src/test/java/youhong/ai/pcn/mapper/TransTestMapper.java b/src/test/java/youhong/ai/pcn/mapper/TransTestMapper.java new file mode 100644 index 0000000..c82e239 --- /dev/null +++ b/src/test/java/youhong/ai/pcn/mapper/TransTestMapper.java @@ -0,0 +1,20 @@ +package youhong.ai.pcn.mapper; + +import aiyh.utils.annotation.recordset.Insert; +import aiyh.utils.annotation.recordset.SqlMapper; +import youhong.ai.pcn.pojo.Student; + +/** + *

+ * + *

create: 2022-12-21 22:54

+ * + * @author youHong.ai + */ + +@SqlMapper +public interface TransTestMapper { + + @Insert("insert into test_trans (name,age,sex) values (#{name},#{age},#{sex})") + boolean insertStudent(Student student); +} diff --git a/src/test/java/youhong/ai/pcn/pojo/Student.java b/src/test/java/youhong/ai/pcn/pojo/Student.java new file mode 100644 index 0000000..0174767 --- /dev/null +++ b/src/test/java/youhong/ai/pcn/pojo/Student.java @@ -0,0 +1,21 @@ +package youhong.ai.pcn.pojo; + +import lombok.Getter; +import lombok.Setter; + +/** + *

+ * + *

create: 2022-12-21 22:55

+ * + * @author youHong.ai + */ + +@Getter +@Setter +public class Student { + private int id; + private String name; + private int age; + private int sex; +} From 8e6720335da2a40ec10aaad4232ce1026c926aad Mon Sep 17 00:00:00 2001 From: "youHong.ai" <774495953@qq.com> Date: Wed, 21 Dec 2022 23:22:58 +0800 Subject: [PATCH 25/33] fix dealwithmapping lowecase bug --- .../config/service/DealWithMapping.java | 72 ++++++++++++++----- 1 file changed, 56 insertions(+), 16 deletions(-) diff --git a/src/main/java/weaver/xiao/commons/config/service/DealWithMapping.java b/src/main/java/weaver/xiao/commons/config/service/DealWithMapping.java index 458f9f8..44b939b 100644 --- a/src/main/java/weaver/xiao/commons/config/service/DealWithMapping.java +++ b/src/main/java/weaver/xiao/commons/config/service/DealWithMapping.java @@ -557,11 +557,18 @@ public class DealWithMapping extends ToolUtil { // 流程字段 case WORKFLOW_FIELD: { FieldMessage fieldMassage = mappingDetail.getFieldMassage(); - String fieldName = fieldMassage.getFieldName().toLowerCase(); + String fieldName = fieldMassage.getFieldName(); + String fieldNameLower = fieldName.toLowerCase(); if ("1".equals(childSource)) { - value = Util.null2String(detailMap.get(fieldName)); + value = Util.null2String(detailMap.get(fieldNameLower)); + if ("".equals(value)) { + value = Util.null2String(detailMap.get(fieldName)); + } } else { - value = Util.null2String(mainMap.get(fieldName)); + value = Util.null2String(mainMap.get(fieldNameLower)); + if ("".equals(value)) { + value = Util.null2String(mainMap.get(fieldName)); + } } } break; @@ -570,11 +577,18 @@ public class DealWithMapping extends ToolUtil { FieldMessage fieldMassage = mappingDetail.getFieldMassage(); String workFlowVal = ""; if (fieldMassage != null) { - String fieldName = fieldMassage.getFieldName().toLowerCase(); + String fieldName = fieldMassage.getFieldName(); + String fieldNameLowe = fieldName.toLowerCase(); if ("1".equals(childSource)) { - workFlowVal = Util.null2String(detailMap.get(fieldName)); + workFlowVal = Util.null2String(detailMap.get(fieldNameLowe)); + if ("".equals(workFlowVal)) { + workFlowVal = Util.null2String(detailMap.get(fieldName)); + } } else if ("0".equals(childSource)) { - workFlowVal = Util.null2String(mainMap.get(fieldName)); + workFlowVal = Util.null2String(mainMap.get(fieldNameLowe)); + if ("".equals(workFlowVal)) { + workFlowVal = Util.null2String(mainMap.get(fieldName)); + } } } value = Util.null2String(valueContext) @@ -819,18 +833,31 @@ public class DealWithMapping extends ToolUtil { // 流程字段 case WORKFLOW_FIELD: { FieldMessage fieldMassage = mappingDetail.getFieldMassage(); - String fieldName = fieldMassage.getFieldName().toLowerCase(); + String fieldName = fieldMassage.getFieldName(); + String fieldNameLower = fieldName.toLowerCase(); this.writeDebuggerLog("fieldName:" + fieldName); if ("1".equals(childSource)) { - value = Util.null2String(detailMap.get(fieldName)); + value = Util.null2String(detailMap.get(fieldNameLower)); + if ("".equals(value)) { + value = Util.null2String(detailMap.get(fieldName)); + } } else if ("0".equals(childSource)) { - value = Util.null2String(mainMap.get(fieldName)); + value = Util.null2String(mainMap.get(fieldNameLower)); + if ("".equals(value)) { + value = Util.null2String(mainMap.get(fieldName)); + } } else { - value = Util.null2String(relationRs.getString(fieldName)); + value = Util.null2String(relationRs.getString(fieldNameLower)); + if ("".equals(value)) { + value = Util.null2String(relationRs.getString(fieldName)); + } } if ("rootNode".equals(mappingDetail.getBelongTo()) && "2".equals(childSource)) { writeDebuggerLog("主表取关联流程字段 => " + paramName); - value = Util.null2String(tempRs.getString(fieldName)); + value = Util.null2String(tempRs.getString(fieldNameLower)); + if ("".equals(value)) { + value = Util.null2String(tempRs.getString(fieldName)); + } } } break; @@ -839,16 +866,29 @@ public class DealWithMapping extends ToolUtil { FieldMessage fieldMassage = mappingDetail.getFieldMassage(); String workFlowVal = ""; if (fieldMassage != null) { - String fieldName = fieldMassage.getFieldName().toLowerCase(); + String fieldName = fieldMassage.getFieldName(); + String fieldNameLower = fieldName.toLowerCase(); if ("1".equals(childSource)) { - workFlowVal = Util.null2String(detailMap.get(fieldName)); + workFlowVal = Util.null2String(detailMap.get(fieldNameLower)); + if ("".equals(workFlowVal)) { + workFlowVal = Util.null2String(detailMap.get(fieldName)); + } } else if ("0".equals(childSource)) { - workFlowVal = Util.null2String(mainMap.get(fieldName)); + workFlowVal = Util.null2String(mainMap.get(fieldNameLower)); + if ("".equals(workFlowVal)) { + workFlowVal = Util.null2String(mainMap.get(fieldName)); + } } else { - workFlowVal = Util.null2String(relationRs.getString(fieldName)); + workFlowVal = Util.null2String(relationRs.getString(fieldNameLower)); + if ("".equals(workFlowVal)) { + workFlowVal = Util.null2String(relationRs.getString(fieldName)); + } } if ("rootNode".equals(mappingDetail.getBelongTo()) && "2".equals(childSource)) { - workFlowVal = Util.null2String(tempRs.getString(fieldName)); + workFlowVal = Util.null2String(tempRs.getString(fieldNameLower)); + if ("".equals(workFlowVal)) { + workFlowVal = Util.null2String(tempRs.getString(fieldName)); + } } } value = Util.null2String(valueContext) From f2b3189e4ff77d70d2fd639d01b893453e9a51e2 Mon Sep 17 00:00:00 2001 From: "youHong.ai" <774495953@qq.com> Date: Wed, 21 Dec 2022 23:58:45 +0800 Subject: [PATCH 26/33] =?UTF-8?q?=E5=90=8C=E4=B8=80=E4=B8=AA=E7=BA=BF?= =?UTF-8?q?=E7=A8=8B=E6=94=AF=E6=8C=81=E5=A4=9A=E4=B8=AA=E4=BA=8B=E5=8A=A1?= =?UTF-8?q?mapper?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/aiyh/utils/Util.java | 22 +++++- .../aiyh/utils/recordset/RecordsetUtil.java | 12 +-- .../utils/recordset/RsThreadLocalManager.java | 75 +++++++++++++------ src/test/java/youhong/ai/pcn/UtilTest.java | 5 +- 4 files changed, 79 insertions(+), 35 deletions(-) diff --git a/src/main/java/aiyh/utils/Util.java b/src/main/java/aiyh/utils/Util.java index 1696df5..ed2e2e6 100644 --- a/src/main/java/aiyh/utils/Util.java +++ b/src/main/java/aiyh/utils/Util.java @@ -2,7 +2,9 @@ package aiyh.utils; import aiyh.utils.action.CusBaseAction; import aiyh.utils.annotation.*; +import aiyh.utils.annotation.recordset.SqlMapper; import aiyh.utils.entity.*; +import aiyh.utils.excention.BindingException; import aiyh.utils.excention.CustomerException; import aiyh.utils.fileUtil.ProperUtil; import aiyh.utils.mapUtil.UtilHashMap; @@ -1998,8 +2000,14 @@ public class Util extends weaver.general.Util { * @return boolean 是否提交成功 * @author youHong.ai ****************************************** */ - public static boolean commitTransMapper() { - return recordsetUtil.getRsManager().commit(); + public static boolean commitTransMapper(Class t) { + if (t == null) { + throw new NullPointerException("can not commit trans for null mapper proxy!"); + } + if (t.getAnnotation(SqlMapper.class) == null) { + throw new BindingException("can not find SqlMapper annotation!"); + } + return recordsetUtil.getRsManager().commit(t.getName()); } /** @@ -2010,8 +2018,14 @@ public class Util extends weaver.general.Util { * @return boolean 是否回滚成功 * @author youHong.ai ****************************************** */ - public static boolean rollbackTransMapper() { - return recordsetUtil.getRsManager().rollback(); + public static boolean rollbackTransMapper(Class t) { + if (t == null) { + throw new NullPointerException("can not commit trans for null mapper proxy!"); + } + if (t.getAnnotation(SqlMapper.class) == null) { + throw new BindingException("can not find SqlMapper annotation!"); + } + return recordsetUtil.getRsManager().rollback(t.getName()); } /** diff --git a/src/main/java/aiyh/utils/recordset/RecordsetUtil.java b/src/main/java/aiyh/utils/recordset/RecordsetUtil.java index e82a60f..29145e3 100644 --- a/src/main/java/aiyh/utils/recordset/RecordsetUtil.java +++ b/src/main/java/aiyh/utils/recordset/RecordsetUtil.java @@ -54,10 +54,10 @@ public class RecordsetUtil implements InvocationHandler { private Object invokeRs(Object proxy, Method method, Object[] args) { - RecordSet rs = rsManager.getRs(); + RecordSet rs = rsManager.getRs(method.getDeclaringClass().getName()); if (rs == null) { - rsManager.setRecordSet(); - rs = rsManager.getRs(); + rsManager.setRecordSet(method.getDeclaringClass().getName()); + rs = rsManager.getRs(method.getDeclaringClass().getName()); } SqlHandler sqlHandler = new SqlHandler(); ResultMapper resultMapper = new ResultMapper(); @@ -230,10 +230,10 @@ public class RecordsetUtil implements InvocationHandler { } private Object invokeRsTrans(Object proxy, Method method, Object[] args) { - RecordSetTrans rs = rsManager.getTrans(); + RecordSetTrans rs = rsManager.getTrans(method.getDeclaringClass().getName()); if (rs == null) { - rsManager.setRecordSetTrans(); - rs = rsManager.getTrans(); + rsManager.setRecordSetTrans(method.getDeclaringClass().getName()); + rs = rsManager.getTrans(method.getDeclaringClass().getName()); } SqlHandler sqlHandler = new SqlHandler(); ResultMapper resultMapper = new ResultMapper(); diff --git a/src/main/java/aiyh/utils/recordset/RsThreadLocalManager.java b/src/main/java/aiyh/utils/recordset/RsThreadLocalManager.java index deacc1b..5950668 100644 --- a/src/main/java/aiyh/utils/recordset/RsThreadLocalManager.java +++ b/src/main/java/aiyh/utils/recordset/RsThreadLocalManager.java @@ -22,7 +22,7 @@ import java.util.concurrent.TimeUnit; public class RsThreadLocalManager { - private final ConcurrentHashMap rsMap = new ConcurrentHashMap<>(); + private final ConcurrentHashMap> rsMap = new ConcurrentHashMap<>(); private final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); @@ -49,11 +49,19 @@ public class RsThreadLocalManager { * @author youHong.ai ****************************************** */ private void checkExpireRs() { - Iterator> iterator = rsMap.entrySet().iterator(); + Iterator>> iterator = rsMap.entrySet().iterator(); while (iterator.hasNext()) { - Map.Entry entity = iterator.next(); - RsThreadLocalMap value = entity.getValue(); - if (System.currentTimeMillis() >= value.getExpireTime() || value.getExpireTime() != -1) { + Map.Entry> entity = iterator.next(); + Map map = entity.getValue(); + Iterator> mapIterator = map.entrySet().iterator(); + while (mapIterator.hasNext()) { + Map.Entry mapEntity = mapIterator.next(); + RsThreadLocalMap value = mapEntity.getValue(); + if (System.currentTimeMillis() >= value.getExpireTime() || value.getExpireTime() != -1) { + mapIterator.remove(); + } + } + if (map.isEmpty()) { iterator.remove(); } } @@ -66,9 +74,18 @@ public class RsThreadLocalManager { * * @author youHong.ai ****************************************** */ - public void setRecordSet() { + public void setRecordSet(String className) { RsThreadLocalMap rsThreadLocalMap = new RsThreadLocalMap(new RecordSet(), getExpireTime()); - rsMap.put(Thread.currentThread().getId(), rsThreadLocalMap); + setRecordSetOrTrans(className, rsThreadLocalMap); + } + + private void setRecordSetOrTrans(String className, RsThreadLocalMap rsThreadLocalMap) { + Map map = rsMap.get(Thread.currentThread().getId()); + if (Objects.isNull(map)) { + map = new ConcurrentHashMap<>(); + } + map.put(className, rsThreadLocalMap); + rsMap.put(Thread.currentThread().getId(), map); } /** @@ -78,11 +95,11 @@ public class RsThreadLocalManager { * * @author youHong.ai ****************************************** */ - public void setRecordSetTrans() { + public void setRecordSetTrans(String className) { RecordSetTrans recordSetTrans = new RecordSetTrans(); recordSetTrans.setAutoCommit(false); RsThreadLocalMap rsThreadLocalMap = new RsThreadLocalMap(recordSetTrans, -1L); - rsMap.put(Thread.currentThread().getId(), rsThreadLocalMap); + setRecordSetOrTrans(className, rsThreadLocalMap); } /** @@ -106,8 +123,12 @@ public class RsThreadLocalManager { * @return RecordSet * @author youHong.ai ****************************************** */ - public RecordSet getRs() { - RsThreadLocalMap rsThreadLocalMap = rsMap.get(Thread.currentThread().getId()); + public RecordSet getRs(String className) { + Map map = rsMap.get(Thread.currentThread().getId()); + if (Objects.isNull(map)) { + return null; + } + RsThreadLocalMap rsThreadLocalMap = map.get(className); if (Objects.isNull(rsThreadLocalMap)) { return null; } @@ -123,8 +144,12 @@ public class RsThreadLocalManager { * @return RecordSetTrans 事务rs * @author youHong.ai ****************************************** */ - public RecordSetTrans getTrans() { - RsThreadLocalMap rsThreadLocalMap = rsMap.get(Thread.currentThread().getId()); + public RecordSetTrans getTrans(String className) { + Map map = rsMap.get(Thread.currentThread().getId()); + if (Objects.isNull(map)) { + return null; + } + RsThreadLocalMap rsThreadLocalMap = map.get(className); if (Objects.isNull(rsThreadLocalMap)) { return null; } @@ -132,24 +157,28 @@ public class RsThreadLocalManager { return rsThreadLocalMap.getRecordSetTrans(); } - public boolean commit() { - RsThreadLocalMap rsThreadLocalMap = rsMap.get(Thread.currentThread().getId()); - if (Objects.isNull(rsThreadLocalMap)) { - throw new CustomerException("can not find RecordSetTrans instance! please Contact the developer of RecordsetUtil.java!"); - } - rsThreadLocalMap.setExpireTime(getExpireTime()); - RecordSetTrans recordSetTrans = rsThreadLocalMap.getRecordSetTrans(); + public boolean commit(String className) { + RecordSetTrans recordSetTrans = getRecordSetTrans(className); return recordSetTrans.commit(); } - - public boolean rollback() { - RsThreadLocalMap rsThreadLocalMap = rsMap.get(Thread.currentThread().getId()); + private RecordSetTrans getRecordSetTrans(String className) { + Map map = rsMap.get(Thread.currentThread().getId()); + if (Objects.isNull(map)) { + throw new CustomerException("can not find RecordSetTrans instance! please Contact the developer of RecordsetUtil.java!"); + } + RsThreadLocalMap rsThreadLocalMap = map.get(className); if (Objects.isNull(rsThreadLocalMap)) { throw new CustomerException("can not find RecordSetTrans instance! please Contact the developer of RecordsetUtil.java!"); } rsThreadLocalMap.setExpireTime(getExpireTime()); RecordSetTrans recordSetTrans = rsThreadLocalMap.getRecordSetTrans(); + return recordSetTrans; + } + + + public boolean rollback(String className) { + RecordSetTrans recordSetTrans = getRecordSetTrans(className); return recordSetTrans.rollback(); } diff --git a/src/test/java/youhong/ai/pcn/UtilTest.java b/src/test/java/youhong/ai/pcn/UtilTest.java index 6ee36c1..516502e 100644 --- a/src/test/java/youhong/ai/pcn/UtilTest.java +++ b/src/test/java/youhong/ai/pcn/UtilTest.java @@ -22,12 +22,13 @@ public class UtilTest extends BaseTest { TransTestMapper transMapper = Util.getTransMapper(TransTestMapper.class); Student student = Builder.builder(Student::new) - .with(Student::setName, "王小明") + .with(Student::setName, "王小明2") .with(Student::setAge, 10) .with(Student::setSex, 1).build(); boolean b = transMapper.insertStudent(student); System.out.println(b); - System.out.println(Util.commitTransMapper()); + //boolean b1 = Util.rollbackTransMapper(TransTestMapper.class); + System.out.println(Util.commitTransMapper(TransTestMapper.class)); } } From 50789e184b1c9f2176355b06b296e3d4bd89b987 Mon Sep 17 00:00:00 2001 From: wangxuanran <3055088966@qq.com> Date: Fri, 23 Dec 2022 16:07:57 +0800 Subject: [PATCH 27/33] =?UTF-8?q?=E4=B8=8A=E6=B1=BD=E5=87=BA=E8=A1=8C?= =?UTF-8?q?=E4=BB=A5=E5=8F=8A=E6=96=BD=E7=BD=97=E5=BE=B7=E4=BB=A3=E7=A0=81?= =?UTF-8?q?=E6=B5=8B=E8=AF=95=E5=AE=8C=E6=88=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../xuanran.wang/bme/js/BuildContractApply.js | 54 ++++ javascript/xuanran.wang/bme/js/Common.js | 154 ++++++++++++ .../bme/js/PurchaseContractApply.js | 58 +++++ .../xuanran.wang/bme/js/SaleContractApply.js | 61 +++++ javascript/xuanran.wang/schroeder/js/Seal.js | 151 +++++++++++ .../checkuser/service/CheckUserService.java | 10 +- .../CusCreateWorkFlowController.java | 91 +++++-- .../service/CreateWorkFlowService.java | 233 +++++++++++++++++ .../action/ContractApplyComDateAction.java | 91 +++++++ .../bme/action/CusCreateWaterNoAction.java | 111 +++++++++ .../wang/common/mapper/CommonMapper.java | 7 + .../xuanran/wang/common/util/CommonUtil.java | 70 ++++++ .../wang/common/util/CusInfoToOAUtil.java | 138 +++++++--- .../datapush/eneity/DetailRequestConfig.java | 21 ++ .../datapush/eneity/MainRequestConfig.java | 25 ++ .../config/eneity/DataAsyncDetail.java | 14 +- .../config/eneity/DataAsyncMain.java | 1 + .../constant/DataAsyncConstant.java | 8 + .../job/CusDataToModelAsync.java | 2 + .../mapper/DataAsyncMapper.java | 2 - .../service/DataAsyncConfigService.java | 120 +++++++-- .../schroeder/action/PushSealTaskAction.java | 175 +++++++++++-- .../action/SalesforceEndpointAction.java | 45 ++++ .../before/PushSealTaskBeforeProcessor.java | 62 +++++ .../interfaces/CusActionBeforeProcessor.java | 23 ++ .../PushSealTaskSealValue.java | 2 - .../schroeder/mapper/SchroederMapper.java | 16 ++ .../service/SchroederQRCodeService.java | 235 ++++++++++++------ .../service/WacoDataPushOAService.java | 3 + .../model_data_async/AsyncTest.java | 84 +++++-- .../download_file/DownLoadFileTest.java | 46 ++++ .../waco_first/WacoFirstTest.java | 2 +- 32 files changed, 1918 insertions(+), 197 deletions(-) create mode 100644 javascript/xuanran.wang/bme/js/BuildContractApply.js create mode 100644 javascript/xuanran.wang/bme/js/Common.js create mode 100644 javascript/xuanran.wang/bme/js/PurchaseContractApply.js create mode 100644 javascript/xuanran.wang/bme/js/SaleContractApply.js create mode 100644 javascript/xuanran.wang/schroeder/js/Seal.js create mode 100644 src/main/java/com/api/xuanran/wang/saic_travel/model_create_workflow/service/CreateWorkFlowService.java create mode 100644 src/main/java/weaver/xuanran/wang/bme/action/ContractApplyComDateAction.java create mode 100644 src/main/java/weaver/xuanran/wang/bme/action/CusCreateWaterNoAction.java create mode 100644 src/main/java/weaver/xuanran/wang/epdi/datapush/eneity/DetailRequestConfig.java create mode 100644 src/main/java/weaver/xuanran/wang/epdi/datapush/eneity/MainRequestConfig.java create mode 100644 src/main/java/weaver/xuanran/wang/schroeder/action/SalesforceEndpointAction.java create mode 100644 src/main/java/weaver/xuanran/wang/schroeder/before/PushSealTaskBeforeProcessor.java create mode 100644 src/main/java/weaver/xuanran/wang/schroeder/before/interfaces/CusActionBeforeProcessor.java diff --git a/javascript/xuanran.wang/bme/js/BuildContractApply.js b/javascript/xuanran.wang/bme/js/BuildContractApply.js new file mode 100644 index 0000000..a58d098 --- /dev/null +++ b/javascript/xuanran.wang/bme/js/BuildContractApply.js @@ -0,0 +1,54 @@ +/** + * 柏美 施工合同申请js + * 明细表自动添加5行 不允许增删 并校验付款比例是否等于100% 自动计算付款日期 + * @author xuanran.wang + */ +// 明细表 +const detailTable = "detail_2"; +// 主表合同签订日期 +const contractSignDateId = WfForm.convertFieldNameToId("htqdrq"); +// 明细2付款比例字段 +const detail2PayProportionId = WfForm.convertFieldNameToId("fkbl",detailTable); +// 明细2款项类型 +const detail2PaymentTypeId = WfForm.convertFieldNameToId("kxlx",detailTable); +// 明细2前后字段 +const detail2AroundId = WfForm.convertFieldNameToId("qh",detailTable); +// 明细2天数字段 +const detail2DayId = WfForm.convertFieldNameToId("ts",detailTable); +// 明细2预计付款日期 +const detail2ComPayDateId = WfForm.convertFieldNameToId("yjfkrq",detailTable); +// 对应日期 +const detail2TempDateField = WfForm.convertFieldNameToId("dyrq", detailTable); +// 需要计算的款项类型集合 +const computeDatePayType = ['0']; +// 款项类型预计对应日期取值 +const paymentTypeGetValue = { + 0: (index)=>{ + WfForm.changeFieldValue(`${detail2TempDateField}_${index}`,{value : WfForm.getFieldValue(contractSignDateId)}); + } +} +jQuery().ready(function(){ + let configObj = { + 'detailPaymentTypeId':detail2PaymentTypeId, + 'detailTempDateId': detail2TempDateField, + 'around': detail2AroundId, + 'detailComPayDateId': detail2ComPayDateId, + 'dayId': detail2DayId, + 'computeDatePayType': computeDatePayType, + 'paymentTypeGetValue': paymentTypeGetValue + } + // 默认增加5条 + for (let i = 0; i < 5; i++) { + WfForm.addDetailRow(detailTable,{ [detail2PaymentTypeId]: {value: i}}); + } + + // 主表字段发生变化 + mainFieldChangeDetailCom(contractSignDateId, detailTable, configObj); + + // 明细的款项类型字段变化绑定 + detailFieldChangeDetailCom(`${detail2AroundId},${detail2DayId}`, configObj); + + submitCallback(detailTable, detail2PayProportionId); + +}); + diff --git a/javascript/xuanran.wang/bme/js/Common.js b/javascript/xuanran.wang/bme/js/Common.js new file mode 100644 index 0000000..230e7f0 --- /dev/null +++ b/javascript/xuanran.wang/bme/js/Common.js @@ -0,0 +1,154 @@ +const ADD = '1'; +const DEL = '0'; +const READ_ONLY = '1'; +const EDIT = '2'; +/** + * 计算日期 + * @param date 计算日期 + * @param around 前/后 前是0 后是1 + * @param day + */ +function computeDate(date, around, day){ + let dateTime = new Date(date).getTime(); + let mill = 0; + switch (around){ + case ADD:{ + mill = day * 1; + console.log('add :', mill); + break; + } + case DEL:{ + mill = day * -1; + console.log('del :', mill); + break; + } + } + // 转成毫秒数 + mill *= (24 * 60 * 60 * 1000); + dateTime += mill; + return getDate(dateTime); +} + +/** + * 时间戳转 yyyy-MM-dd + * @param time + * @returns {string} + */ +function getDate(time) { + let date = new Date(time); + y = date.getFullYear(); + m = date.getMonth() + 1; + d = date.getDate(); + return y + "-" + (m < 10 ? "0" + m : m) + "-" + (d < 10 ? "0" + d : d); +} + +/** + * 校验比例是否等于100 + * @param detailTable 明细表 + * @param detail2PayProportionId 比例字段 + */ +function submitCallback(detailTable, detail2PayProportionId){ + WfForm.registerCheckEvent(WfForm.OPER_SUBMIT,function(callback){ + let rowArr = WfForm.getDetailAllRowIndexStr(detailTable).split(","); + let sum = 0; + for(let i=0; i < rowArr.length; i++){ + let rowIndex = rowArr[i]; + if(rowIndex !== ""){ + let field = `${detail2PayProportionId}_${rowIndex}`; + sum += parseFloat(WfForm.getFieldValue(field));//遍历明细行字段 + } + } + sum === 100.00 ? callback() : WfForm.showMessage("明细付款比例总和不等于100,请修改后提交!"); + }); +} + +/** + * 明细表字段发生变化进行日期计算 + * @param bindField + * @param configObj + */ +function detailFieldChangeDetailCom(bindField, configObj){ + WfForm.bindDetailFieldChangeEvent(bindField,function(id,index,value){ + configObj.index = index; + changeDetailPayDate(configObj); + }); +} + +/** + * 主表字段发生变化进行日期计算 + * @param mainField + * @param detailTable + * @param configObj + */ +function mainFieldChangeDetailCom(mainField, detailTable, configObj){ + // 主表项目字段变化绑定 + WfForm.bindFieldChangeEvent(mainField, function(obj,id,value){ + let rowArr = WfForm.getDetailAllRowIndexStr(detailTable).split(","); + for(let i=0; i < rowArr.length; i++){ + let index = rowArr[i]; + if(index !== ""){ + configObj.index = index; + changeDetailPayDate(configObj); + } + } + }); +} + +/** + * 先进行主表的dml查询日期字段赋值到明细 然后在计算日期 + * @param obj 配置对象 + */ +function changeDetailPayDate(obj){ + console.log('---- changeDetailPayDate obj ----', obj); + // 明细表的款项类型 + let detailPaymentTypeId = obj['detailPaymentTypeId']; + // 明细下标 + let index = obj['index']; + // 明细表的对应日期 + let detailTempDateId = obj['detailTempDateId']; + // 明细表的前/后 + let aroundId = obj['around']; + // 明细表的预计付款日期 + let detailComPayDateId = obj['detailComPayDateId']; + // 明细表的天数 + let dayId = obj['dayId']; + // 需要计算的款项数组 + let computeDatePayType = obj['computeDatePayType']; + // 获取主表的字符值转换函数 + let paymentTypeGetValue = obj['paymentTypeGetValue']; + // 款项类型 + let paymentType = WfForm.getFieldValue(`${detailPaymentTypeId}_${index}`); + // 先进行赋值 + if(computeDatePayType.includes(paymentType)){ + WfForm.changeFieldAttr(`${detailComPayDateId}_${index}`, READ_ONLY); + // 存在字段联动延时处理 + setTimeout(()=>{ + if(paymentTypeGetValue){ + paymentTypeGetValue[paymentType](index); + } + // 获取对应日期 + let tempDate = WfForm.getFieldValue(`${detailTempDateId}_${index}`); + if(tempDate){ + // 前/后 + let around = WfForm.getFieldValue(`${aroundId}_${index}`); + // 天数 + let day = WfForm.getFieldValue(`${dayId}_${index}`); + // 如果明细表三个字段的值都不为空 那么就去计算日期 + if(tempDate && around && day){ + let comDate = computeDate(tempDate, around, day); + WfForm.changeFieldValue(`${detailComPayDateId}_${index}`,{ + value: comDate + }); + } + }else { + // 如果对应日期为空就给预计付款赋空值 + WfForm.changeFieldValue(`${detailComPayDateId}_${index}`,{ + value: '' + }); + } + },100); + }else{ + // 如果款项类型不需要计算就把预计付款日期属性改成可编辑 + WfForm.changeFieldAttr(`${detailComPayDateId}_${index}`, EDIT); + } +} diff --git a/javascript/xuanran.wang/bme/js/PurchaseContractApply.js b/javascript/xuanran.wang/bme/js/PurchaseContractApply.js new file mode 100644 index 0000000..f4b95b1 --- /dev/null +++ b/javascript/xuanran.wang/bme/js/PurchaseContractApply.js @@ -0,0 +1,58 @@ +/** + * 柏美 采购合同申请js + * @author xuanran.wang + */ +// 明细表 +const detailTable = "detail_3"; +// 主表项目字段 +const mainProjectId = WfForm.convertFieldNameToId("xmmc"); +// 主表合同签订日期 +const contractSignDateId = WfForm.convertFieldNameToId("htqdrq"); +// 明细2付款比例字段 +const detailPayProportionId = WfForm.convertFieldNameToId("fkbl",detailTable); +// 明细2款项类型 +const detailPaymentTypeId = WfForm.convertFieldNameToId("kxlx",detailTable); +// 明细2前后字段 +const detailAroundId = WfForm.convertFieldNameToId("qh",detailTable); +// 明细2天数字段 +const detailDayId = WfForm.convertFieldNameToId("ts",detailTable); +// 明细2预计付款日期 +const detailComPayDateId = WfForm.convertFieldNameToId("yjfkrq",detailTable); +// 对应日期 +const detailTempDateField = WfForm.convertFieldNameToId("dyrq", detailTable); +// 需要计算的款项类型集合 +const computeDatePayType = ['0','2','4']; +// 款项类型预计对应日期取值 +const paymentTypeGetValue = { + 0: (index)=>{ + WfForm.changeFieldValue(`${detailTempDateField}_${index}`,{value : WfForm.getFieldValue(contractSignDateId)}); + }, + 2: (index)=>{ + WfForm.changeFieldValue(`${detailTempDateField}_${index}`,{value : WfForm.getFieldValue(mainActualCheckId)}); + }, + 4: (index)=>{ + WfForm.changeFieldValue(`${detailTempDateField}_${index}`,{value : WfForm.getFieldValue(mainActualCheckId)}); + } +} +$(()=>{ + init(); +}); + +function init(){ + + let obj = { + 'detailPaymentTypeId':detailPaymentTypeId, + 'detailTempDateId': detailTempDateField, + 'around': detailAroundId, + 'detailComPayDateId': detailComPayDateId, + 'dayId': detailDayId, + 'computeDatePayType': computeDatePayType, + 'paymentTypeGetValue': paymentTypeGetValue + } + + // 主表字段发生变化 + mainFieldChangeDetailCom(`${mainProjectId},${contractSignDateId}`, detailTable, obj); + // 明细的款项类型字段变化绑定 + detailFieldChangeDetailCom(`${detailPaymentTypeId},${detailAroundId},${detailDayId}`, obj); + submitCallback(detailTable, detailPayProportionId); +} diff --git a/javascript/xuanran.wang/bme/js/SaleContractApply.js b/javascript/xuanran.wang/bme/js/SaleContractApply.js new file mode 100644 index 0000000..87cb38d --- /dev/null +++ b/javascript/xuanran.wang/bme/js/SaleContractApply.js @@ -0,0 +1,61 @@ +/** + * 柏美 销售合同申请js + * @author xuanran.wang + */ +// 明细表 +const detailTable = "detail_2"; +// 主表项目字段 +const mainProjectId = WfForm.convertFieldNameToId("xmmc"); +// 主表流程归档日期 +const mainWorkFlowEndId = WfForm.convertFieldNameToId("fhdgdrq"); +// 主表实际验收 +const mainActualCheckId = WfForm.convertFieldNameToId("sjysrq"); +// 明细2付款比例字段 +const detail2PayProportionId = WfForm.convertFieldNameToId("fkbl",detailTable); +// 明细2款项类型 +const detail2PaymentTypeId = WfForm.convertFieldNameToId("kxlx",detailTable); +// 明细2前后字段 +const detail2AroundId = WfForm.convertFieldNameToId("qh",detailTable); +// 明细2天数字段 +const detail2DayId = WfForm.convertFieldNameToId("ts",detailTable); +// 明细2预计付款日期 +const detail2ComPayDateId = WfForm.convertFieldNameToId("yjfkrq",detailTable); +// 对应日期 +const detail2TempDateField = WfForm.convertFieldNameToId("dyrq", detailTable); +// 需要计算的款项类型集合 +const computeDatePayType = ['2', '4', '5']; +// 款项类型预计对应日期取值 +const paymentTypeGetValue = { + 2: (index)=>{ + console.log('将主表的 mainWorkFlowEndId : ' + mainWorkFlowEndId + ' val : ' + WfForm.getFieldValue(mainWorkFlowEndId) + ' 赋值给明细 ' + `${detail2TempDateField}_${index}`); + WfForm.changeFieldValue(`${detail2TempDateField}_${index}`,{value : WfForm.getFieldValue(mainWorkFlowEndId)}); + }, + 4: (index)=>{ + WfForm.changeFieldValue(`${detail2TempDateField}_${index}`,{value : WfForm.getFieldValue(mainActualCheckId)}); + }, + 5: (index)=>{ + WfForm.changeFieldValue(`${detail2TempDateField}_${index}`,{value : WfForm.getFieldValue(mainActualCheckId)}); + } +} +$(()=>{ + init(); +}); + +function init(){ + + let obj = { + 'detailPaymentTypeId':detail2PaymentTypeId, + 'detailTempDateId': detail2TempDateField, + 'around': detail2AroundId, + 'detailComPayDateId': detail2ComPayDateId, + 'dayId': detail2DayId, + 'computeDatePayType': computeDatePayType, + 'paymentTypeGetValue': paymentTypeGetValue + } + // 主表字段发生变化 + mainFieldChangeDetailCom(mainProjectId, detailTable, obj); + // 明细的款项类型字段变化绑定 + detailFieldChangeDetailCom(`${detail2PaymentTypeId},${detail2AroundId},${detail2DayId}`, obj); + submitCallback(detailTable, detail2PayProportionId); + +} diff --git a/javascript/xuanran.wang/schroeder/js/Seal.js b/javascript/xuanran.wang/schroeder/js/Seal.js new file mode 100644 index 0000000..334ce52 --- /dev/null +++ b/javascript/xuanran.wang/schroeder/js/Seal.js @@ -0,0 +1,151 @@ + +// 打印盖章 +const pritGz = 1; +// 鉴伪盖章 +const jwGz = 3; +// 开门盖章 +const kmGz = 4; +// 用印方式字段名 +const sealTypeId = WfForm.convertFieldNameToId("yyfs"); +// 用印方式字段名明细 +const detailSealTypeId = WfForm.convertFieldNameToId("yylx","detail_1"); +// 是否需要加骑缝章 +const detailQfzField = WfForm.convertFieldNameToId("sfjgqfz","detail_1"); +// 否 +const no = 1; +// 是 +const yes = 0;// 组合用印 +const zh = 6; +// 取章用印 +const qzyy = 7; +// 是否归档 +const lastField = WfForm.convertFieldNameToId("sfgd"); +// 来源 +const source = WfForm.convertFieldNameToId("htspcfyy"); +//属于合同 +const isht = WfForm.convertFieldNameToId("zyht"); +//完成法神 +const islaw = WfForm.convertFieldNameToId("wcfs"); +// 用印文件字段 +const detailFileTypeId = WfForm.convertFieldNameToId("yywj","detail_1"); + +// 主表 +const mainsealtype = WfForm.convertFieldNameToId("yzzl"); +// 主表合同专用章次数 +const mainht = WfForm.convertFieldNameToId("htzyzcshj"); +// 主表公章次数 +const maingz = WfForm.convertFieldNameToId("gzcshj"); +// 主表法人章次数 +const mainfr = WfForm.convertFieldNameToId("frzcshj"); + +// 必填 +const required = 3; +// 只读 +const readOnly = 1; +// 可编辑 +const edit = 2; +// 默认文件docid +const defaultfile = 85; +// 明细1用印文件 +jQuery(document).ready(()=>{ + let sourceVal = WfForm.getFieldValue(source); + console.log('sourceVal ', sourceVal) + if(sourceVal == 0){ + WfForm.changeSingleField(isht,{value:yes}, {viewAttr:readOnly}); + WfForm.changeSingleField(islaw,{value:yes}, {viewAttr:readOnly}); + // 明细表用印文件字段做只读 + var rowArr = WfForm.getDetailAllRowIndexStr("detail_1").split(","); + for(var i=0; i dataList = Arrays.stream(choiceData.split(",")).collect(Collectors.toList()); - List requestIds = CommonUtil.doCreateWorkFlow(modelId, dataList); // 通过数据审批生成流程 - List errorData = new ArrayList<>(); - for (int i = 0; i < requestIds.size(); i++) { - if (Util.getIntValue(requestIds.get(i), -1) < 0) { - errorData.add(dataList.get(i)); + try { + User logInUser = HrmUserVarify.getUser(request, response); + if(logInUser == null){ + return ApiResult.error(403,"请先登录!"); } + String choiceData = request.getParameter("choiceData"); + if(StringUtils.isBlank(choiceData)){ + return ApiResult.error(403,"请勾选数据!"); + } + int modelId = Util.getIntValue(request.getParameter("modelId"), -1); + String triggerWorkflowSetId = Util.null2DefaultStr(request.getParameter("triggerWorkflowSetId"), ""); + String createDateField = Util.null2DefaultStr(request.getParameter("createDateField"), ""); + if(modelId < 0 || StringUtils.isBlank(triggerWorkflowSetId) || StringUtils.isBlank(createDateField)){ + logger.info(Util.logStr("modelId : {}, triggerWorkflowSetId : {}, createDateField : {}", modelId, triggerWorkflowSetId, createDateField)); + return ApiResult.error(403,"api必要参数未配置!"); + } + return ApiResult.success(JSONObject.toJSONString( createWorkFlowService.hrmCusCreateWorkFlow(choiceData, createDateField, triggerWorkflowSetId, modelId))); + }catch (Exception e){ + logger.error(Util.logStr(e.getMessage())); + logger.error(Util.getErrString(e)); + return ApiResult.error("接口发生异常!"); } - logger.error(Util.logStr("执行创建流程失败集合: {}",JSONObject.toJSONString(errorData))); // 构建日志字符串 - return ApiResult.success(errorData); + } + + @Path("gysCusCreateWorkFlow") + @POST + @Produces(MediaType.TEXT_PLAIN) + public String gysCusCreateWorkFlow(@Context HttpServletRequest request, @Context HttpServletResponse response) { + try { + User logInUser = HrmUserVarify.getUser(request, response); + if(logInUser == null){ + return ApiResult.error(403,"请先登录!"); + } + String choiceData = request.getParameter("choiceData"); + if(StringUtils.isBlank(choiceData)){ + return ApiResult.error(403,"请勾选数据!"); + } + // 执行创建流程数据审批的模块id + int dataApprovalModelId = Util.getIntValue(request.getParameter("dataApprovalModelId"), -1); + // 待合并数据审批id + int createTriggerId = Util.getIntValue(request.getParameter("createTriggerId"), -1); + // 数据同步配置参数 + String asyncCode = Util.null2DefaultStr(request.getParameter("asyncCode"), ""); + // 带合并模块id + String dataModelId = Util.null2DefaultStr(request.getParameter("dataModelId"), ""); + if(createTriggerId < 0 || StringUtils.isBlank(asyncCode) || dataApprovalModelId < 0 || StringUtils.isBlank(dataModelId)){ + logger.info(Util.logStr("createTriggerId : {}, asyncCode : {}, dataApprovalModelId : {}", createTriggerId, asyncCode, dataApprovalModelId)); + return ApiResult.error(403,"api必要参数未配置!"); + } + return ApiResult.success(createWorkFlowService.supplierCusCreateWorkFlow(String.valueOf(createTriggerId), dataModelId, asyncCode, choiceData, dataApprovalModelId)); + }catch (Exception e){ + logger.error(Util.logStr(e.getMessage())); + logger.error(Util.getErrString(e)); + return ApiResult.error("接口发生异常!"); + } + + } + + + } diff --git a/src/main/java/com/api/xuanran/wang/saic_travel/model_create_workflow/service/CreateWorkFlowService.java b/src/main/java/com/api/xuanran/wang/saic_travel/model_create_workflow/service/CreateWorkFlowService.java new file mode 100644 index 0000000..6e175cf --- /dev/null +++ b/src/main/java/com/api/xuanran/wang/saic_travel/model_create_workflow/service/CreateWorkFlowService.java @@ -0,0 +1,233 @@ +package com.api.xuanran.wang.saic_travel.model_create_workflow.service; + +import aiyh.utils.ApiResult; +import aiyh.utils.Util; +import aiyh.utils.excention.CustomerException; +import com.alibaba.fastjson.JSONObject; +import com.icbc.api.internal.apache.http.impl.cookie.S; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.collections.MapUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.log4j.Logger; +import weaver.conn.RecordSet; +import weaver.general.TimeUtil; +import weaver.xuanran.wang.common.mapper.CommonMapper; +import weaver.xuanran.wang.common.util.CommonUtil; +import weaver.xuanran.wang.common.util.CusInfoToOAUtil; +import weaver.xuanran.wang.saic_travel.model_data_async.config.eneity.DataAsyncDetail; +import weaver.xuanran.wang.saic_travel.model_data_async.config.eneity.DataAsyncMain; +import weaver.xuanran.wang.saic_travel.model_data_async.constant.DataAsyncConstant; +import weaver.xuanran.wang.saic_travel.model_data_async.service.DataAsyncConfigService; + +import java.util.*; +import java.util.stream.Collectors; + +/** + *

+ * + * @Author xuanran.wang + * @Date 2022/12/15 14:33 + */ +public class CreateWorkFlowService { + + private final DataAsyncConfigService dataAsyncConfigService = new DataAsyncConfigService(); + private final CommonMapper commonMapper = Util.getMapper(CommonMapper.class); + private final Logger logger = Util.getLogger(); + + /** + *

人员绩效创建流程

+ * @author xuanran.wang + * @dateTime 2022/12/15 17:07 + * @param choiceData 选择的数据 + * @param createDateField 创建日期字段 + * @param triggerWorkflowSetId 数据审批id + * @param modelId 模块id + * @return 流程创建失败的数据id + **/ + public List hrmCusCreateWorkFlow(String choiceData, String createDateField, String triggerWorkflowSetId, int modelId){ + String name = commonMapper.getModelNameByModelId(String.valueOf(modelId)); + List dataList = Arrays.stream(choiceData.split(",")).collect(Collectors.toList()); + RecordSet rs = new RecordSet(); + List> splitList = CommonUtil.splitList(dataList); + for (List list : splitList) { + List ids = list.stream().map(item -> Util.getIntValue(item, -1)).collect(Collectors.toList()); + if(CollectionUtils.isEmpty(ids)){ + continue; + } + String updateCreatDateSql = "update " + name + " set " + createDateField + " = '"+ TimeUtil.getCurrentDateString() +"' where id in ( " + StringUtils.join(ids,",") + " )"; + if(!rs.executeUpdate(updateCreatDateSql)){ + throw new CustomerException(Util.logStr("更新建模表数据失败!, 当前sql : {} ", updateCreatDateSql)); + } + } + // 数据审批配置Id + String[] triggerIds = triggerWorkflowSetId.split(","); + logger.info("triggerIds : " + JSONObject.toJSONString(triggerIds)); + List errorData = new ArrayList<>(); + for (String id : triggerIds) { + String sql = "select id from " + name; + String condition = commonMapper.getConditionByTriggerId(id); + if(StringUtils.isNotBlank(condition)){ + sql += " where " + condition; + } + logger.info(Util.logStr("人员创建流程查询数据sql : {}", sql)); + List filterIds = filterIds(sql); + List dataIds = dataList.stream().filter(filterIds::contains).collect(Collectors.toList()); + if(CollectionUtils.isNotEmpty(dataIds)){ + List requestIds = CommonUtil.doCreateWorkFlow(modelId, dataIds, Util.getIntValue(id, -1)); // 通过数据审批生成流程 + for (int i = 0; i < requestIds.size(); i++) { + if (Util.getIntValue(requestIds.get(i), -1) < 0) { + errorData.add(dataList.get(i)); + } + } + }else { + logger.info("当前数据都不满足触发条件!"); + } + logger.error(Util.logStr("人员创建流程执行创建流程失败集合: {}",JSONObject.toJSONString(errorData))); // 构建日志字符串 + } + return errorData; + } + + /** + *

+ * @author xuanran.wang + * @dateTime 2022/12/15 17:11 + * @param createTriggerId 勾选数据模块 数据审批id + * @param dataModelId 勾选数据的模块id + * @param asyncCode 数据同步配置 + * @param choiceData 选择的数据 + * @param dataApprovalModelId 创建流程的模块id + * @return requestId + **/ + public String supplierCusCreateWorkFlow(String createTriggerId, String dataModelId, String asyncCode, String choiceData, int dataApprovalModelId){ + // 查询来源数据待合并 数据审批配置 + Map configByTriggerId = commonMapper.getConfigByTriggerId(String.valueOf(createTriggerId)); + if(MapUtils.isEmpty(configByTriggerId)){ + return ApiResult.error(403,"请给模块id = [ "+createTriggerId + " ] 配置数据审批!"); + } + // 待合并的表名 + String dataTable = commonMapper.getModelNameByModelId(dataModelId); + String sql = "select id from " + dataTable; + // 触发条件 + String condition = Util.null2DefaultStr(configByTriggerId.get("showcondition"), ""); + String successWriteBack = Util.null2DefaultStr(configByTriggerId.get("successwriteback"), ""); + if(StringUtils.isNotBlank(condition)){ + sql += " where " + condition; + } + List dataList = Arrays.stream(choiceData.split(",")).collect(Collectors.toList()); + logger.info(Util.logStr("查询数据sql : {}", sql)); + List filterIds = filterIds(sql); + // 过滤之后的数据id + List dataIds = dataList.stream().filter(filterIds::contains).collect(Collectors.toList()); + List requestIds = new ArrayList<>(); + if(!CollectionUtils.isEmpty(dataIds)){ + String dataId = asyncModelData(asyncCode, dataIds, dataApprovalModelId); + requestIds = CommonUtil.doCreateWorkFlow(dataApprovalModelId, Collections.singletonList(dataId)); + if(CollectionUtils.isEmpty(requestIds)){ + throw new CustomerException("流程创建失败!"); + } + if(CollectionUtils.isNotEmpty(requestIds) && !(Util.getIntValue(requestIds.get(0),-1) < 0 && StringUtils.isNotBlank(successWriteBack))){ + RecordSet rs = new RecordSet(); + sql = "update " + dataTable + " set " + successWriteBack + " where " + Util.getSubINClause(StringUtils.join(dataIds, ","),"id"," in "); + if (!rs.executeUpdate(sql)) { + logger.error(Util.logStr("回写sql : {}", sql)); + throw new CustomerException("流程创建成功, 但回写失败!"); + } + } + return requestIds.get(0); + }else { + logger.info("当前数据都不满足触发条件!"); + } + return ""; + } + + + /** + *

通过配置数据同步至建模

+ * @author xuanran.wang + * @dateTime 2022/12/2 13:28 + * @param configCode 配置标识 + * @param modelId 模块id + **/ + public String asyncModelData(String configCode, List dataIds, int modelId) { + DataAsyncMain asyncConfig = dataAsyncConfigService.getDataAsyncConfigByUniqueCode(configCode); + String dataSource = asyncConfig.getDataSource(); + String selectSql = dataAsyncConfigService.getSelectSql(asyncConfig); + List asyncDetailList = asyncConfig.getDataAsyncDetailList(); + selectSql += " where " + Util.getSubINClause(StringUtils.join(dataIds, ","),"id"," in "); + RecordSet rs = new RecordSet(); + if (!rs.executeQuery(selectSql)) { + throw new CustomerException(Util.logStr("执行查询数据源sql失败! 当前sql:{}", selectSql)); + } + // 主表同步配置条件 + List mainConfigList = asyncDetailList.stream().filter(item -> !DataAsyncConstant.DETAIL_TABLE.equals(item.getMainOrDetail())).collect(Collectors.toList()); + List detailConfigList = asyncDetailList.stream().filter(item -> DataAsyncConstant.DETAIL_TABLE.equals(item.getMainOrDetail())).collect(Collectors.toList()); + String mainId = ""; + if (rs.next()){ + // 先把数据同步到主表 + LinkedHashMap params = getValue(mainConfigList, rs, dataSource); + mainId = CusInfoToOAUtil.getDataId(modelId, params); + logger.info("生成建模mainId : " + mainId); + } + rs.executeQuery(selectSql); + ArrayList> detailParams = new ArrayList<>(); + while (rs.next()){ + LinkedHashMap value = getValue(detailConfigList, rs, dataSource); + value.put("mainid", mainId); + detailParams.add(value); + } + CusInfoToOAUtil.executeDetailBatch(asyncConfig.getAsyncTargetModelTableName()+ "_dt" + asyncConfig.getDetailIndex(),detailParams); + return mainId; + } + + /** + *

转换值

+ * @author xuanran.wang + * @dateTime 2022/12/15 16:29 + * @param asyncDetailList 配置集合 + * @param rs 结果集 + * @param dataSource 数据来源 + * @return 自定义表插入参数 + **/ + public LinkedHashMap getValue(List asyncDetailList, RecordSet rs, String dataSource){ + LinkedHashMap map = new LinkedHashMap<>(); + for (DataAsyncDetail dataAsyncDetail : asyncDetailList) { + String field = ""; + switch (dataSource){ + case DataAsyncConstant.DATA_SOURCE_MODEL:{ + field = dataAsyncDetail.getDataSourceModelFiledName(); + }break; + case DataAsyncConstant.DATA_SOURCE_CUS_TABLE:{ + field = dataAsyncDetail.getCusTableField(); + }break; + default:throw new CustomerException("暂不支持的数据来源"); + } + // 同步建模字段 + String asyncModelTableField = dataAsyncDetail.getAsyncModelTableField(); + Object value = dataAsyncConfigService.getFieldValue(rs, field, dataAsyncDetail, 0); + map.put(asyncModelTableField, value); + } + if(MapUtils.isEmpty(map)){ + throw new CustomerException("转换配置生成参数map为空!"); + } + return map; + } + + /** + *

获取数据id

+ * @author xuanran.wang + * @dateTime 2022/12/15 13:22 + * @param sql 获取执行条件sql + * @return 数据id + **/ + public List filterIds(String sql){ + RecordSet rs = new RecordSet(); + ArrayList res = new ArrayList<>(); + if (rs.executeQuery(sql)) { + while (rs.next()){ + res.add(Util.null2DefaultStr(rs.getString(1),"")); + } + } + return res; + } + +} diff --git a/src/main/java/weaver/xuanran/wang/bme/action/ContractApplyComDateAction.java b/src/main/java/weaver/xuanran/wang/bme/action/ContractApplyComDateAction.java new file mode 100644 index 0000000..000e4d5 --- /dev/null +++ b/src/main/java/weaver/xuanran/wang/bme/action/ContractApplyComDateAction.java @@ -0,0 +1,91 @@ +package weaver.xuanran.wang.bme.action; + +import aiyh.utils.Util; +import aiyh.utils.action.SafeCusBaseAction; +import aiyh.utils.annotation.RequiredMark; +import aiyh.utils.excention.CustomerException; +import org.apache.commons.lang3.StringUtils; +import weaver.conn.RecordSetTrans; +import weaver.hrm.User; +import weaver.soa.workflow.request.RequestInfo; + +import java.util.Map; + +/** + *

柏美施工合同修改日期action

+ * + * @Author xuanran.wang + * @Date 2022/12/20 11:33 + */ +public class ContractApplyComDateAction extends SafeCusBaseAction { + + /** + *

施工合同项目字段

+ **/ + @RequiredMark + private String buildContractProjectField; + /** + *

施工合同主表名

+ **/ + @RequiredMark + private String buildContractTable; + /** + *

施工合同明细表表名

+ **/ + @RequiredMark + private String detailContractTable; + /** + *

施工合同明细表更新日期字段

+ **/ + @RequiredMark + private String detailContractDateFiled; + /** + *

验收流程项目字段

+ **/ + @RequiredMark + private String projectField; + /** + *

验收流程日期字段

+ **/ + @RequiredMark + private String checkDateField; + /** + *

明细表更新验收日期的条件

+ **/ + private String updateWhere; + + @Override + public void doSubmit(String requestId, String billTable, int workflowId, User user, RequestInfo requestInfo) { + RecordSetTrans rs = requestInfo.getRsTrans(); + rs.setAutoCommit(false); + try { + Map mainTableValue = getMainTableValue(requestInfo); + // 验收流程的实际验收日期 + String checkDate = mainTableValue.get(checkDateField); + String project = mainTableValue.get(projectField); + if(StringUtils.isBlank(checkDate) || StringUtils.isBlank(project)){ + log.error(Util.logStr("checkDate:{}, project:{}", checkDate, project)); + throw new CustomerException("实际验收日期或项目字段字段为空!"); + } + String selectSql = "select id from " + buildContractTable + " where " + buildContractProjectField + " = ?"; + if(rs.executeQuery(selectSql, project) && rs.next()){ + String mainId = rs.getString("id"); + String updateSql = "update " + detailContractTable + " set " + detailContractDateFiled + " = ? where mainid = ?"; + if(StringUtils.isNotBlank(updateWhere)){ + updateSql += " and " + updateWhere; + } + if(!rs.executeUpdate(updateSql, checkDate, mainId)){ + log.error(Util.logStr("更新合同明细表sql:{}, 参数:{}", updateSql, new String[]{checkDate, mainId})); + throw new CustomerException("更新合同sql错误!"); + } + rs.commit(); + }else{ + log.error(Util.logStr("查询施工合同关联项目sql : {}", selectSql)); + } + }catch (Exception e){ + rs.rollback(); + throw new CustomerException(Util.logStr("更新施工合同实际验收日期发生异常: {} ", e.getMessage())); + } + } + +} diff --git a/src/main/java/weaver/xuanran/wang/bme/action/CusCreateWaterNoAction.java b/src/main/java/weaver/xuanran/wang/bme/action/CusCreateWaterNoAction.java new file mode 100644 index 0000000..ca7d9eb --- /dev/null +++ b/src/main/java/weaver/xuanran/wang/bme/action/CusCreateWaterNoAction.java @@ -0,0 +1,111 @@ +package weaver.xuanran.wang.bme.action; + +import aiyh.utils.Util; +import aiyh.utils.action.SafeCusBaseAction; +import aiyh.utils.annotation.RequiredMark; +import aiyh.utils.excention.CustomerException; +import weaver.conn.RecordSet; +import weaver.conn.RecordSetTrans; +import weaver.hrm.User; +import weaver.soa.workflow.request.RequestInfo; +import weaver.xuanran.wang.common.util.CommonUtil; +import weaver.xuanran.wang.common.util.CusInfoToOAUtil; + +import java.util.LinkedHashMap; +import java.util.Map; + +/** + *

柏美存货档案流程生成流水号

+ *

+ * 流程主表的存货档案编码生成流水号 格式:存货分类编码 + 4位流水号 DUJE0101 DUJE0199 => DUJE0201 + *

+ * + * @Author xuanran.wang + * @Date 2022/12/22 13:18 + */ +public class CusCreateWaterNoAction extends SafeCusBaseAction { + + /** + *

存货分类编码字段

+ **/ + @RequiredMark + private String invClassificationCode; + + /** + *

存货编码 生成编号后写入这个字段

+ **/ + @RequiredMark + private String inventoryCode; + + /** + *

生成流水号日志记录模块id

+ **/ + private String serialNumberModelId; + + private static final String START_NO = "0101"; + + @Override + public void doSubmit(String requestId, String billTable, int workflowId, User user, RequestInfo requestInfo) { + log.info("----------- CusCreateWaterNoAction Begin " + requestId + "-----------"); + RecordSetTrans rsts = new RecordSetTrans(); + rsts.setAutoCommit(false); + try { + Map mainTableValue = getMainTableValue(requestInfo); + String invClassificationCodeVal = mainTableValue.get(invClassificationCode); + String nextInventoryCode = getNextInventoryCode(invClassificationCodeVal); + String updateSql = "update " + billTable + " set " + inventoryCode + " = ? where requestid = ?"; + if(!rsts.executeUpdate(updateSql, nextInventoryCode, requestId)){ + log.error(Util.logStr("sql :{}, nextInventoryCode : {}, requestId: {}", updateSql, nextInventoryCode, requestId)); + throw new CustomerException("更新表单存货编码字段失败!"); + } + }catch (Exception e){ + throw new CustomerException(Util.logStr("生成存货编码Action异常: [{}]",e.getMessage())); + } + } + + /** + *

根据分类编码获取下一个流水号

+ * @author xuanran.wang + * @dateTime 2022/12/22 14:08 + * @param inventoryCode 分类编码 + * @return 分类编码+四位流水号 + **/ + private synchronized String getNextInventoryCode(String inventoryCode){ + RecordSet rs = new RecordSet(); + String modelTableName = CommonUtil.getModelTableNameById(Util.getIntValue(serialNumberModelId, -1)); + String sql = "select max(serialNumber) serialNumber from " + modelTableName + " where invClassificationCode = ? order by createDateTime"; + String res = ""; + if(rs.executeQuery(sql, inventoryCode)){ + if (!rs.next()) { + res = inventoryCode + START_NO; + }else { + String serialNumber = rs.getString(1); + String front = serialNumber.substring(0,2); + String end = serialNumber.substring(3); + int frontInt = Util.getIntValue(front); + int endInt = Util.getIntValue(end); + String endStr = ""; + String frontStr = ""; + if(++endInt >= 100){ + frontInt += 1; + endInt = 1; + } + if(endInt < 10){ + endStr = "0" + endInt; + } + if(frontInt < 10){ + frontStr = "0" + frontInt; + } + res = frontStr + endStr; + } + } + LinkedHashMap map = new LinkedHashMap<>(); + map.put("invClassificationCode", inventoryCode); + map.put("serialNumber", res); + map.put("serialCode", inventoryCode + res); + CusInfoToOAUtil.getDataId(Util.getIntValue(serialNumberModelId, -1), map); + return res; + } + + +} \ No newline at end of file diff --git a/src/main/java/weaver/xuanran/wang/common/mapper/CommonMapper.java b/src/main/java/weaver/xuanran/wang/common/mapper/CommonMapper.java index 7520a12..b932268 100644 --- a/src/main/java/weaver/xuanran/wang/common/mapper/CommonMapper.java +++ b/src/main/java/weaver/xuanran/wang/common/mapper/CommonMapper.java @@ -50,4 +50,11 @@ public interface CommonMapper { "ON mp.id = mpd.mainId " + "WHERE mp.modeid = #{modelId} AND mp.isSystem = 1 AND mp.iSSystemFlag = 1") Map getExpendConfigByModeId(@ParamMapper("modelId") int modelId); + + @Select("select * from mode_triggerworkflowset where id = #{triggerId}") + Map getConfigByTriggerId(@ParamMapper("triggerId") String triggerId); + + @Select("select showcondition from mode_triggerworkflowset where id = #{triggerId}") + String getConditionByTriggerId(@ParamMapper("triggerId") String triggerId); + } diff --git a/src/main/java/weaver/xuanran/wang/common/util/CommonUtil.java b/src/main/java/weaver/xuanran/wang/common/util/CommonUtil.java index f1c9c82..0a037d3 100644 --- a/src/main/java/weaver/xuanran/wang/common/util/CommonUtil.java +++ b/src/main/java/weaver/xuanran/wang/common/util/CommonUtil.java @@ -232,6 +232,16 @@ public class CommonUtil { } } + /** + *

将集合进行分割

+ * @author xuanran.wang + * @dateTime 2022/11/25 16:01 + * @param list 待分割的集合 + * @return 分割集合 + **/ + public static List> splitList(List list) { + return splitList(list, SQL_IN_PAGE_SIZE); + } /** *

将集合进行分割

* @author xuanran.wang @@ -337,6 +347,9 @@ public class CommonUtil { * @return true/false **/ public static boolean deleteDataByIds(List ids, String tableName,int pageSize) { + if(CollectionUtils.isEmpty(ids)){ + return true; + } List> lists = CommonUtil.splitList(ids, pageSize); for (List list : lists) { boolean success = commonMapper.deleteModelDataByIds(tableName, list); @@ -526,4 +539,61 @@ public class CommonUtil { return requestIds; } + /** + *

通过数据审批生成流程

+ * @author xuanran.wang + * @dateTime 2022/12/1 21:14 + * @param modeId 模块id + * @param dataIds 模块数据id集合 + * @param triggerWorkflowSetId 数据审批id + **/ + public static List doCreateWorkFlow(int modeId, List dataIds, int triggerWorkflowSetId){ + if(modeId < 0){ + throw new CustomerException("模块id不能小于0!"); + } + if(triggerWorkflowSetId < 0){ + throw new CustomerException("自定义数据审批id不能小于0!"); + } + if(org.springframework.util.CollectionUtils.isEmpty(dataIds)){ + logger.info("暂无数据要生成流程!"); + return Collections.emptyList(); + } + Map expendConfig = commonMapper.getExpendConfigByModeId(modeId); + logger.info(Util.logStr("expendConfig :{}", JSONObject.toJSONString(expendConfig))); + int expendId = expendConfig.get("id"); + int formId = expendConfig.get("formId"); + ArrayList requestIds = new ArrayList<>(); + if(expendId > 0 && triggerWorkflowSetId > 0){ + for (String daId : dataIds) { + ModeDataApproval modeDataApproval = new ModeDataApproval(); + modeDataApproval.setUser(new User(1)); + modeDataApproval.setBillid(Util.getIntValue(daId)); + modeDataApproval.setFormid(formId); + modeDataApproval.setModeid(modeId); + modeDataApproval.setTriggerWorkflowSetId(triggerWorkflowSetId); + modeDataApproval.setPageexpandid(expendId); + Map resMap = modeDataApproval.approvalDataResult(); + logger.info(Util.logStr("模块数据id : {}, 创建流程结果 : {}", daId, JSONObject.toJSONString(resMap))); + requestIds.add(Util.null2String(resMap.get("requestid"))); + } + } + return requestIds; + } + + /** + *

根据模块id获取表名

+ * @author xuanran.wang + * @dateTime 2022/12/22 14:18 + * @param modelId 模块id + * @return 模块表名 + **/ + public static String getModelTableNameById(int modelId){ + if(modelId < 0){ + throw new CustomerException("模块id不能小于0!"); + } + return commonMapper.getModelNameByModelId(String.valueOf(modelId)); + } + + + } diff --git a/src/main/java/weaver/xuanran/wang/common/util/CusInfoToOAUtil.java b/src/main/java/weaver/xuanran/wang/common/util/CusInfoToOAUtil.java index b02e57f..125fd16 100644 --- a/src/main/java/weaver/xuanran/wang/common/util/CusInfoToOAUtil.java +++ b/src/main/java/weaver/xuanran/wang/common/util/CusInfoToOAUtil.java @@ -16,6 +16,7 @@ import weaver.general.TimeUtil; import weaver.xuanran.wang.common.mapper.CommonMapper; import java.util.*; +import java.util.stream.Collectors; /** * @Author xuanran.wang @@ -26,7 +27,7 @@ public class CusInfoToOAUtil { private static final ModeDataIdUpdate modeDataIdUpdate = ModeDataIdUpdate.getInstance(); private static final ModeRightInfo moderightinfo = new ModeRightInfo(); private static final Logger log = Util.getLogger(); - public static final String TABLE_NAME_PLACEHOLDER = "#\\{tableName}"; + private static final String TABLE_NAME_PLACEHOLDER = "#\\{tableName}"; /** *

将自定义信息写入建模

@@ -74,7 +75,7 @@ public class CusInfoToOAUtil { String whereSql, List whereParams, boolean needDel) { - return executeBatch(modelId, Collections.singletonList(new LinkedHashMap<>(params)), whereSql, whereParams, needDel).get(0); + return executeBatch(modelId, Collections.singletonList(new LinkedHashMap<>(params)), whereSql,Collections.singletonList(whereParams), needDel, Collections.emptyList()).get(0); } /** @@ -87,7 +88,7 @@ public class CusInfoToOAUtil { **/ public static List executeBatch( int modelId, List> params) { - return executeBatch(modelId, params, "", Collections.emptyList(), true); + return executeBatch(modelId, params, "", Collections.emptyList()); } /** @@ -111,8 +112,13 @@ public class CusInfoToOAUtil { if(StringUtils.isBlank(tableName)){ throw new CustomerException("模块id为 " + modelId + ", 在系统中暂没查询到对应表单!"); } - return executeBatch(modelId, tableName, params, whereSql, whereParams, true); + ArrayList> lists = new ArrayList<>(); + for (String param : whereParams) { + lists.add(new ArrayList<>(Collections.singleton(param))); + } + return executeBatch(modelId, tableName, params, whereSql, lists, true, Collections.emptyList()); } + /** *

将自定义信息写入建模

* @author xuanran.wang @@ -124,11 +130,12 @@ public class CusInfoToOAUtil { * @param needDel 更新失败是否需要删除已经插入的数据 * @return 建模数据id集合 **/ - public static List executeBatch( int modelId, - List> params, - String whereSql, - List whereParams, - boolean needDel) { + public static List executeBatch( int modelId, + List> params, + String whereSql, + List> whereParams, + boolean needDel, + List> updateParams) { if(modelId < 0){ throw new RuntimeException("建模模块id不能小于0!"); } @@ -136,7 +143,7 @@ public class CusInfoToOAUtil { if(StringUtils.isBlank(tableName)){ throw new CustomerException("模块id为 " + modelId + ", 在系统中暂没查询到对应表单!"); } - return executeBatch(modelId, tableName, params, whereSql, whereParams, needDel); + return executeBatch(modelId, tableName, params, whereSql, whereParams, needDel, updateParams); } /** @@ -149,57 +156,75 @@ public class CusInfoToOAUtil { * @param whereSql 重复数据条件sql * @param whereParams 重复数据参数集合 * @param needDel 更新失败是否需要删除已经插入的数据 + * @param updateParams 更新某条数据的部分字段 * @return 建模数据id集合 **/ public static List executeBatch( int modelId, String tableName, List> params, String whereSql, - List whereParams, - boolean needDel) { + List> whereParams, + boolean needDel, + List> updateParams) { + // 如果要对模块数据中重复的进行更新则判断待插入的集合大小和判断重复的集合大小参数长度是否一致 if(StringUtils.isNotBlank(whereSql)){ if(CollectionUtils.isEmpty(whereParams) || CollectionUtils.isEmpty(params) || whereParams.size() != params.size()){ + log.error(Util.logStr("params : {}", JSONObject.toJSONString(params))); + log.error(Util.logStr("whereSql : {}", whereSql)); + log.error(Util.logStr("whereParams : {} ", JSONObject.toJSONString(whereParams))); + log.error(Util.logStr("updateParams : {} ", updateParams)); throw new CustomerException("使用批量更新时如果需要对重复数据进行更新,参数集合和判断重复参数集合大小必须相等!"); } } RecordSet rs = new RecordSet(); List dataIds = new ArrayList<>(); - List wheres = new ArrayList<>(); + List paramsWheres = new ArrayList<>(); + List updateWheres = new ArrayList<>(); + whereSql = Util.sbc2dbcCase(whereSql); + whereSql = whereSql.replaceAll(TABLE_NAME_PLACEHOLDER, tableName); + // 需要插入的建模参数 + List> tempParams = new ArrayList<>(); + // 如果建模中已经存在只想更新部分字段参数 + List> tempUpdateParams = new ArrayList<>(); for (int i = 0; i < params.size(); i++) { int mainId = -1; if(StringUtils.isNotBlank(whereSql)){ - whereSql = Util.sbc2dbcCase(whereSql); - whereSql = whereSql.replaceAll(TABLE_NAME_PLACEHOLDER, tableName); - if (rs.executeQuery(whereSql, whereParams) && rs.next()) { + // 如果匹配到数据 + if (rs.executeQuery(whereSql, whereParams.get(i)) && rs.next()) { mainId = Util.getIntValue(rs.getString(1),-1); + updateWheres.add(Util.createPrepWhereImpl().whereAnd("id").whereEqual(mainId)); + dataIds.add(String.valueOf(mainId)); + if(!CollectionUtils.isEmpty(updateParams)){ + tempUpdateParams.add(updateParams.get(i)); + }else { + tempUpdateParams.add(params.get(i)); + } }else { - log.info("whereSql : " + whereSql); - log.info("参数 : " + whereParams); + log.info(Util.logStr("==== 未匹配到数据 ==== whereSql : {}, 参数 : {}", whereSql, JSONObject.toJSONString(whereParams.get(i)))); } } if(mainId < 0){ mainId = getNewIdByModelInfo(tableName, modelId); + paramsWheres.add(Util.createPrepWhereImpl().whereAnd("id").whereEqual(mainId)); + dataIds.add(String.valueOf(mainId)); + tempParams.add(params.get(i)); } - dataIds.add(String.valueOf(mainId)); - wheres.add(Util.createPrepWhereImpl().whereAnd("id").whereEqual(mainId)); } - BatchSqlResultImpl batchSql = Util.createSqlBuilder().updateBatchSql(tableName, params, wheres); - String sqlStr = batchSql.getSqlStr(); - List batchList = batchSql.getBatchList(); - if(!rs.executeBatchSql(sqlStr, batchList)){ - log.error(Util.logStr("batchSql:{}", sqlStr)); - log.error(Util.logStr("batchList:{}", JSONObject.toJSONString(batchList))); - log.error(Util.logStr("whereList:{}", JSONObject.toJSONString(wheres))); + try { + if(CollectionUtils.isNotEmpty(tempParams) && CollectionUtils.isNotEmpty(paramsWheres)){ + execute(tableName, tempParams, paramsWheres); + } + if(CollectionUtils.isNotEmpty(tempUpdateParams) && CollectionUtils.isNotEmpty(updateWheres)){ + execute(tableName, tempUpdateParams, updateWheres); + } + }catch (Exception e){ if(needDel){ if (!deleteModelDataByIds(String.valueOf(modelId), dataIds)) { log.error(Util.logStr("删除数据失败!未删除数据集合:{}", JSONObject.toJSONString(dataIds))); } } - throw new CustomerException("执行批量更新sql失败!"); - } - if(CollectionUtils.isEmpty(dataIds)){ - throw new CustomerException("建模数据生成失败!"); + throw new CustomerException(e.getMessage()); } for (String dataId : dataIds) { moderightinfo.rebuildModeDataShareByEdit(1, modelId, Integer.parseInt(dataId)); @@ -207,6 +232,49 @@ public class CusInfoToOAUtil { return dataIds; } + /** + *

将自定义信息写入建模明细表

+ * @author xuanran.wang + * @dateTime 2022/11/23 17:00 + * @param tableName 表名 + * @param params 需要插入的数据map + * @return 建模数据id集合 + **/ + public static boolean executeDetailBatch(String tableName, List> params){ + RecordSet rs = new RecordSet(); + BatchSqlResultImpl batchSql = Util.createSqlBuilder().insertBatchSql(tableName, params); + String sqlStr = batchSql.getSqlStr(); + List list = batchSql.getBatchList(); + if (!rs.executeBatchSql(sqlStr, list)) { + throw new CustomerException(Util.logStr("明细数据插入失败! sql : {}, params : {}", sqlStr, JSONObject.toJSONString(list))); + } + return true; + } + + /** + *

批量写入建模

+ * @author xuanran.wang + * @dateTime 2022/12/15 10:53 + * @param tableName 表名 + * @param params 建模参数 + * @param wheres where条件 + **/ + public static void execute(String tableName, List> params, List wheres){ +// log.info(Util.logStr("params : [{}],size : [{}]", JSONObject.toJSONString(params), params.size())); +// log.info(Util.logStr("wheres : [{}],size : [{}]", JSONObject.toJSONString(wheres), wheres.size())); + BatchSqlResultImpl batchSql = Util.createSqlBuilder().updateBatchSql(tableName, params, wheres); + String sqlStr = batchSql.getSqlStr(); + List batchList = batchSql.getBatchList(); + RecordSet rs = new RecordSet(); + if(!rs.executeBatchSql(sqlStr, batchList)){ + log.error(Util.logStr("batchSql:{}", sqlStr)); + log.error(Util.logStr("batchList:{}", JSONObject.toJSONString(batchList))); + log.error(Util.logStr("whereList:{}", JSONObject.toJSONString(wheres))); + throw new CustomerException("执行批量更新sql失败!请查看后台cus日志!"); + } + } + + /** *

删除建模数据

* @author xuanran.wang @@ -219,6 +287,14 @@ public class CusInfoToOAUtil { String tableName = commonMapper.getModelNameByModelId(modelId); return commonMapper.deleteModelDataByIds(tableName, ids); } + /** + *

获取建模数据id

+ * @author xuanran.wang + * @dateTime 2022/12/15 10:56 + * @param modelTableName 表名 + * @param modelId 模块id + * @return 新的建模数据id + **/ private static Integer getNewIdByModelInfo(String modelTableName, int modelId){ String currentDateTime = TimeUtil.getCurrentTimeString(); //日期 diff --git a/src/main/java/weaver/xuanran/wang/epdi/datapush/eneity/DetailRequestConfig.java b/src/main/java/weaver/xuanran/wang/epdi/datapush/eneity/DetailRequestConfig.java new file mode 100644 index 0000000..f227c77 --- /dev/null +++ b/src/main/java/weaver/xuanran/wang/epdi/datapush/eneity/DetailRequestConfig.java @@ -0,0 +1,21 @@ +package weaver.xuanran.wang.epdi.datapush.eneity; + + +import lombok.Data; + +/** + * @Author xuanran.wang + * @Date 2022/6/18 16:47 + */ +@Data +public class DetailRequestConfig { + private String paramName; + private String paramType; + private String getValueType; + private String valueContext; + private String tableName; + private String workFlowField; + private String fieldName; + private String detailId; + private String parentName; +} diff --git a/src/main/java/weaver/xuanran/wang/epdi/datapush/eneity/MainRequestConfig.java b/src/main/java/weaver/xuanran/wang/epdi/datapush/eneity/MainRequestConfig.java new file mode 100644 index 0000000..bf884f1 --- /dev/null +++ b/src/main/java/weaver/xuanran/wang/epdi/datapush/eneity/MainRequestConfig.java @@ -0,0 +1,25 @@ +package weaver.xuanran.wang.epdi.datapush.eneity; + + +import lombok.Data; + +import java.util.List; + +/** + * @Author xuanran.wang + * @Date 2022/6/18 15:43 + */ +@Data +public class MainRequestConfig { + private String id; + private String uniqueCode; + private String workflow; + private String requestUrl; + private String dataSource; + private String detailIndex; + private String cusSql; + private String configFilePath; + private String enable; + private String methodParameterClassName; + private List detailRequestConfigList; +} diff --git a/src/main/java/weaver/xuanran/wang/saic_travel/model_data_async/config/eneity/DataAsyncDetail.java b/src/main/java/weaver/xuanran/wang/saic_travel/model_data_async/config/eneity/DataAsyncDetail.java index b5ac556..45ad0fc 100644 --- a/src/main/java/weaver/xuanran/wang/saic_travel/model_data_async/config/eneity/DataAsyncDetail.java +++ b/src/main/java/weaver/xuanran/wang/saic_travel/model_data_async/config/eneity/DataAsyncDetail.java @@ -5,7 +5,7 @@ import lombok.*; import java.sql.Timestamp; /** - *

+ *

数据同步配置实体类

* * @Author xuanran.wang * @Date 2022/12/1 14:01 @@ -48,4 +48,16 @@ public class DataAsyncDetail { *

数据来源建模字段名称

**/ private String dataSourceModelFiledName; + /** + *

更新条件

+ **/ + private String updateCriteria; + /** + *

更新字段

+ **/ + private String updateField; + /** + *

主表还是明细表

+ **/ + private String mainOrDetail; } diff --git a/src/main/java/weaver/xuanran/wang/saic_travel/model_data_async/config/eneity/DataAsyncMain.java b/src/main/java/weaver/xuanran/wang/saic_travel/model_data_async/config/eneity/DataAsyncMain.java index 63d4dd2..3b8cbf7 100644 --- a/src/main/java/weaver/xuanran/wang/saic_travel/model_data_async/config/eneity/DataAsyncMain.java +++ b/src/main/java/weaver/xuanran/wang/saic_travel/model_data_async/config/eneity/DataAsyncMain.java @@ -22,5 +22,6 @@ public class DataAsyncMain { private String cusWhere; private String modelTypeTableName; private String asyncTargetModelTableName; + private String detailIndex; private List dataAsyncDetailList; } diff --git a/src/main/java/weaver/xuanran/wang/saic_travel/model_data_async/constant/DataAsyncConstant.java b/src/main/java/weaver/xuanran/wang/saic_travel/model_data_async/constant/DataAsyncConstant.java index 8091b32..7cf6a0a 100644 --- a/src/main/java/weaver/xuanran/wang/saic_travel/model_data_async/constant/DataAsyncConstant.java +++ b/src/main/java/weaver/xuanran/wang/saic_travel/model_data_async/constant/DataAsyncConstant.java @@ -76,4 +76,12 @@ public class DataAsyncConstant { *

转换类型-拆分复制

**/ public static final String CONVERT_RULES_SPLIT_COPY = "5"; + /** + *

主表

+ **/ + public static final String MAIN_TABLE = "0"; + /** + *

明细

+ **/ + public static final String DETAIL_TABLE = "1"; } diff --git a/src/main/java/weaver/xuanran/wang/saic_travel/model_data_async/job/CusDataToModelAsync.java b/src/main/java/weaver/xuanran/wang/saic_travel/model_data_async/job/CusDataToModelAsync.java index 5145d79..63c9725 100644 --- a/src/main/java/weaver/xuanran/wang/saic_travel/model_data_async/job/CusDataToModelAsync.java +++ b/src/main/java/weaver/xuanran/wang/saic_travel/model_data_async/job/CusDataToModelAsync.java @@ -30,9 +30,11 @@ public class CusDataToModelAsync extends BaseCronJob { @Override public void execute() { try { + logger.info("------------ CusDataToModelAsync Begin ------------"); CommonUtil.checkParamNotNull(this); DataAsyncMain dataAsyncConfigByUniqueCode = asyncConfigService.getDataAsyncConfigByUniqueCode(uniqueCode); asyncConfigService.asyncModelData(dataAsyncConfigByUniqueCode, Util.getIntValue(modelId, -1)); + logger.info("------------ CusDataToModelAsync End ------------"); }catch (Exception e){ logger.error(Util.logStr("执行数据同步计划任务失败!异常信息 : {}", e.getMessage())); } diff --git a/src/main/java/weaver/xuanran/wang/saic_travel/model_data_async/mapper/DataAsyncMapper.java b/src/main/java/weaver/xuanran/wang/saic_travel/model_data_async/mapper/DataAsyncMapper.java index f35a416..f105445 100644 --- a/src/main/java/weaver/xuanran/wang/saic_travel/model_data_async/mapper/DataAsyncMapper.java +++ b/src/main/java/weaver/xuanran/wang/saic_travel/model_data_async/mapper/DataAsyncMapper.java @@ -18,6 +18,4 @@ public interface DataAsyncMapper { @CaseConversion(false) RecordSet getRecordSetByCusSql(@SqlString String sql); - - } diff --git a/src/main/java/weaver/xuanran/wang/saic_travel/model_data_async/service/DataAsyncConfigService.java b/src/main/java/weaver/xuanran/wang/saic_travel/model_data_async/service/DataAsyncConfigService.java index c2fc8e8..480ba57 100644 --- a/src/main/java/weaver/xuanran/wang/saic_travel/model_data_async/service/DataAsyncConfigService.java +++ b/src/main/java/weaver/xuanran/wang/saic_travel/model_data_async/service/DataAsyncConfigService.java @@ -2,8 +2,12 @@ package weaver.xuanran.wang.saic_travel.model_data_async.service; import aiyh.utils.Util; import aiyh.utils.excention.CustomerException; +import aiyh.utils.zwl.common.ToolUtil; +import com.alibaba.fastjson.JSONObject; +import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; +import org.jetbrains.annotations.NotNull; import org.springframework.util.Assert; import org.springframework.util.CollectionUtils; import weaver.conn.RecordSet; @@ -62,17 +66,51 @@ public class DataAsyncConfigService { } logger.info("selectSql : " + selectSql); List> linkedHashMapList = new ArrayList<>(); + StringBuilder updateWhereSql = new StringBuilder(); + // 需要更新时候的参数集合 + List> updateLinkedList = new ArrayList<>(); + // 判断是否更新sql的参数 + List> updateWhereParam = new ArrayList<>(); int splitCopy = -1; String splitCopyFiledName = ""; // 复制个数 List splitCopyList = asyncDetailList.stream().filter(item -> DataAsyncConstant.CONVERT_RULES_SPLIT_COPY.equals(item.getConvertRules())).collect(Collectors.toList()); + DataAsyncDetail copyAsyncDetail = null; if(!CollectionUtils.isEmpty(splitCopyList)){ DataAsyncDetail detail = splitCopyList.get(0); + copyAsyncDetail = detail; splitCopy = Util.getIntValue(detail.getCusText(),-1); splitCopyFiledName = Util.null2DefaultStr(detail.getAsyncModelTableField(),""); } + // 更新数据条件 + List updateCriteriaList = asyncDetailList.stream() + .filter(item -> DataAsyncConstant.CONFIG_ENABLE.equals(item.getUpdateCriteria())) + .map(DataAsyncDetail::getAsyncModelTableField) + .collect(Collectors.toList()); + // 更新字段 + List updateFieldList = asyncDetailList.stream() + .filter(item -> DataAsyncConstant.CONFIG_ENABLE.equals(item.getUpdateField())) + .map(DataAsyncDetail::getAsyncModelTableField) + .collect(Collectors.toList()); + // 如果更新条件不为空那么就拼接更新sql + if(!CollectionUtils.isEmpty(updateCriteriaList)){ + StringBuilder sqlSb = new StringBuilder(); + for (int i = 0; i < updateCriteriaList.size(); i++) { + if(i != updateCriteriaList.size() -1 ){ + sqlSb.append(updateCriteriaList.get(i)).append(" = ? and "); + }else { + sqlSb.append(updateCriteriaList.get(i)).append(" = ? "); + } + } + updateWhereSql.append("select id from #{tableName} where ").append(sqlSb); + } while (rs.next()){ + // 建模表插入参数 LinkedHashMap linkedHashMap = new LinkedHashMap<>(); + // 如果数据存在更新参数集合 + LinkedHashMap updateLinkedMap = new LinkedHashMap<>(); + // 更新条件参数 + LinkedHashMap updateParam = new LinkedHashMap<>(); int tempCount = 0; for (DataAsyncDetail dataAsyncDetail : asyncDetailList) { String field = ""; @@ -85,19 +123,49 @@ public class DataAsyncConfigService { }break; default:throw new CustomerException("暂不支持的数据来源"); } + // 同步建模字段 + String asyncModelTableField = dataAsyncDetail.getAsyncModelTableField(); Object value = getFieldValue(rs, field, dataAsyncDetail, tempCount); - linkedHashMap.put(dataAsyncDetail.getAsyncModelTableField(), value); + // 把当前字段和值放到更新条件参数集合中 + if(!CollectionUtils.isEmpty(updateCriteriaList) && updateCriteriaList.contains(asyncModelTableField)){ + updateParam.put(asyncModelTableField, Util.null2DefaultStr(value,"")); + } + // 需要更新时更新字段参数集合 + if(!CollectionUtils.isEmpty(updateCriteriaList) && updateFieldList.contains(asyncModelTableField)){ + updateLinkedMap.put(asyncModelTableField, value); + } + linkedHashMap.put(asyncModelTableField, value); } + updateWhereParam.add(new ArrayList<>(updateParam.values())); linkedHashMapList.add(linkedHashMap); + if(MapUtils.isNotEmpty(updateLinkedMap)){ + updateLinkedList.add(updateLinkedMap); + } // 记录复制 while (++tempCount < splitCopy) { LinkedHashMap copyMap = new LinkedHashMap<>(linkedHashMap); + // 如果更新条件参数map不为空 + if(MapUtils.isNotEmpty(updateLinkedMap)){ + // 需要更新的参数map集合 + LinkedHashMap copyUpdateLinkedMap = new LinkedHashMap<>(updateLinkedMap); + // 如果更新条件中包含拆分复制条件的 + if(copyAsyncDetail != null && updateCriteriaList.contains(copyAsyncDetail.getAsyncModelTableField())){ + updateParam.put(copyAsyncDetail.getAsyncModelTableField(), String.valueOf(tempCount)); + } + // 将拆分复制的值加进去 + if(copyAsyncDetail != null && updateFieldList.contains(copyAsyncDetail.getAsyncModelTableField())){ + copyUpdateLinkedMap.put(splitCopyFiledName, tempCount); + } + updateLinkedList.add(copyUpdateLinkedMap); + updateWhereParam.add(new ArrayList<>(updateParam.values())); + } copyMap.put(splitCopyFiledName, tempCount); linkedHashMapList.add(copyMap); } } - return CusInfoToOAUtil.executeBatch(modelId, linkedHashMapList); + return CusInfoToOAUtil.executeBatch(modelId, linkedHashMapList, updateWhereSql.toString(), updateWhereParam, true, updateLinkedList); } + /** *

根据配置将值转换

* @author xuanran.wang @@ -108,7 +176,7 @@ public class DataAsyncConfigService { * @param count 复制次数 * @return 转换后的值 **/ - public Object getFieldValue(RecordSet recordSet, String field, DataAsyncDetail dataAsyncDetail, int count){ + public Object getFieldValue(RecordSet recordSet, String field, @NotNull DataAsyncDetail dataAsyncDetail, int count){ String convertRules = dataAsyncDetail.getConvertRules(); String dataType = dataAsyncDetail.getDataType(); String cusText = dataAsyncDetail.getCusText(); @@ -131,12 +199,14 @@ public class DataAsyncConfigService { // 自定义sql查询 case DataAsyncConstant.CONVERT_RULES_CUS_SQL: { if(!StringUtils.isBlank(cusText)){ - String cusSql = Util.sbc2dbcCase(cusText); String where = ""; if(StringUtils.isNotBlank(field)){ where = Util.null2DefaultStr(recordSet.getString(field),""); } - tempRs.executeQuery(cusSql, where); + String cusSql = Util.sbc2dbcCase(cusText) + .replace("?",where) + .replace("{main.id}", recordSet.getString("id")); + tempRs.executeQuery(cusSql); if (!tempRs.next()) { logger.error(Util.logStr("执行自定义sql失败!当前sql:{}, 当前参数:{}", cusSql, where)); break; @@ -146,6 +216,7 @@ public class DataAsyncConfigService { }break; case DataAsyncConstant.CONVERT_RULES_DATA_ID: { value = recordSet.getString("id"); + logger.info(Util.logStr("主数据Id : {}", value)); }break; case DataAsyncConstant.CONVERT_RULES_SPLIT_COPY: { value = count; @@ -232,30 +303,33 @@ public class DataAsyncConfigService { * @return 查询数据来源sql **/ public String getSelectSql(DataAsyncMain asyncConfig){ - String dataSource = asyncConfig.getDataSource(); String cusWhere = Util.null2DefaultStr(asyncConfig.getCusWhere(), ""); - String dataSourceTableName = ""; - List asyncDetailList = asyncConfig.getDataAsyncDetailList(); - String selectSql = "select "; - List modelFieldList = new ArrayList<>(); - // 判断数据来源拼接查询sql - switch (dataSource) { - case DataAsyncConstant.DATA_SOURCE_MODEL:{ - modelFieldList = asyncDetailList.stream().map(DataAsyncDetail::getDataSourceModelFiledName).filter(StringUtils::isNotBlank).collect(Collectors.toList()); - dataSourceTableName = asyncConfig.getModelTypeTableName(); - }break; - case DataAsyncConstant.DATA_SOURCE_CUS_TABLE:{ - modelFieldList = asyncDetailList.stream().map(DataAsyncDetail::getCusTableField).filter(StringUtils::isNotBlank).collect(Collectors.toList()); - dataSourceTableName = asyncConfig.getCusTable(); - }break; - default:throw new CustomerException("暂不支持的数据来源!"); - } // 拼接数据源查询sql - selectSql += StringUtils.join(modelFieldList, ",") + " from " + dataSourceTableName; + String selectSql = "select * from " + getTableName(asyncConfig); if(StringUtils.isNotBlank(cusWhere)){ selectSql += " where " + cusWhere; } return selectSql; } + /** + *

根据配置对象获取查询sql

+ * @author xuanran.wang + * @dateTime 2022/12/2 12:56 + * @param asyncConfig 主配置对象 + * @return 查询数据来源sql + **/ + public String getTableName(DataAsyncMain asyncConfig){ + // 判断数据来源拼接查询sql + switch (asyncConfig.getDataSource()) { + case DataAsyncConstant.DATA_SOURCE_MODEL:{ + return asyncConfig.getModelTypeTableName(); + } + case DataAsyncConstant.DATA_SOURCE_CUS_TABLE:{ + return asyncConfig.getCusTable(); + } + default:throw new CustomerException("暂不支持的数据来源!"); + } + } + } diff --git a/src/main/java/weaver/xuanran/wang/schroeder/action/PushSealTaskAction.java b/src/main/java/weaver/xuanran/wang/schroeder/action/PushSealTaskAction.java index f88d2b3..ca81f9e 100644 --- a/src/main/java/weaver/xuanran/wang/schroeder/action/PushSealTaskAction.java +++ b/src/main/java/weaver/xuanran/wang/schroeder/action/PushSealTaskAction.java @@ -1,19 +1,23 @@ package weaver.xuanran.wang.schroeder.action; import aiyh.utils.Util; -import aiyh.utils.action.CusBaseAction; // 基础的action,实现一些基础的参数 +import aiyh.utils.action.SafeCusBaseAction; import aiyh.utils.annotation.RequiredMark; import aiyh.utils.excention.CustomerException; // 自定义异常类 create 2022/3/9 2:20 PM import org.apache.commons.lang3.StringUtils; +import weaver.conn.RecordSet; import weaver.conn.RecordSetTrans; import weaver.hrm.User; import weaver.soa.workflow.request.RequestInfo; -import weaver.workflow.request.RequestManager; +import weaver.xiao.commons.config.entity.RequestMappingConfig; +import weaver.xuanran.wang.common.util.CommonUtil; import weaver.xuanran.wang.common.util.CusInfoToOAUtil; +import weaver.xuanran.wang.schroeder.before.interfaces.CusActionBeforeProcessor; import weaver.xuanran.wang.schroeder.service.SchroederQRCodeService; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; import java.util.*; -import java.util.function.Function; import java.util.stream.Collectors; @@ -23,7 +27,7 @@ import java.util.stream.Collectors; * @Author xuanran.wang * @Date 2022/11/30 16:08 */ -public class PushSealTaskAction extends CusBaseAction { // 基础的action,实现一些基础的参数 +public class PushSealTaskAction extends SafeCusBaseAction { // 基础的action,实现一些基础的参数 /** *

建模配置唯一标识

@@ -47,43 +51,162 @@ public class PushSealTaskAction extends CusBaseAction { // 基础的action, *

文档记录表模块id

**/ @RequiredMark - private String modelId; + private String docLogModelId; + + /** + *

requestId记录表模块id

+ **/ + @RequiredMark + private String requestIdLogModelId; + + /** + *

开门盖章种类

+ **/ + @RequiredMark + private String filePeopleType; + + /** + *

明细序列

+ **/ + @RequiredMark + private String detailNo; + /** + *

响应成功状态码

+ **/ + @RequiredMark + private String successCode; + /** + *

响应任务字段

+ **/ + @RequiredMark + private String backField; + /** + *

前置接口

+ **/ + private String cusBeforeProcessor; + /** + *

请求格式

+ **/ + private String type; private final SchroederQRCodeService schroederQRCodeService = new SchroederQRCodeService(); // 施罗德业务方法 施罗德业务方法 - - @Override // action 提交流程业务处理方法 具体业务逻辑实现 - public void doSubmit(String requestId, String billTable, int workflowId, User user, RequestManager requestManager) { + public void doSubmit(String requestId, String billTable, int workflowId, User user, RequestInfo requestInfo) { log.info("---------- PushSealTaskSealValue Begin " + requestId + "----------"); - RequestInfo requestInfo = requestInfoThreadLocal.get(); - String scanNum = schroederQRCodeService.pushSealTask(onlyMark, billTable, requestId); // 推送数据创建任务 建模配置唯一标识 - RecordSetTrans trans = requestManager.getRsTrans(); + String delSql = ""; + String mainId = ""; + RecordSetTrans trans = new RecordSetTrans(); trans.setAutoCommit(false); - String updateSql = "update " + billTable + " set " + QRCodeField + " = ? where requestid = ?"; // 二维码来源字段 + // 插入模块的参数集合 + List requestIdLogModelIdList = new ArrayList<>(); + List docLogModelIdList = new ArrayList<>(); + // 前置接口做了添加明细表的操作 最后是否需要删除添加的明细 + boolean del = false; + // 执行前置处理 默认添加一行明细 + if(StringUtils.isNotBlank(cusBeforeProcessor)){ + Map pathParam = Util.parseCusInterfacePathParam(cusBeforeProcessor); + String classPath = pathParam.remove("_ClassPath"); + del = executeBeforeProcessor(classPath, requestInfo, null, pathParam); + } + RecordSet mainRs = new RecordSet(); + mainRs.executeQuery("select * from " + billTable + " where requestid = ?", requestId); + mainRs.next(); try{ + mainId = mainRs.getString("id"); + String detailTable = billTable + "_dt" + detailNo; + if(StringUtils.isNotBlank(mainId)){ + delSql = "delete from " + detailTable + " where mainid = ? "; + } + try{ + // 获取明细表数据 + List> detailList = schroederQRCodeService.getDetailList(detailTable, mainId); + List docIds = detailList.stream() + .map(item -> Util.null2DefaultStr(item.get(fileField), "")) + .filter(StringUtils::isNotBlank).collect(Collectors.toList()); + List> docLogParamList = new ArrayList<>(); + for (String docId : docIds) { + LinkedHashMap map = new LinkedHashMap<>(); + map.put("docId", docId); + map.put("enable", 0); + docLogParamList.add(map); + } + // 将docLog数据写入建模 + docLogModelIdList = CusInfoToOAUtil.executeBatch(Util.getIntValue(docLogModelId, -1), docLogParamList, "select id from #{tableName} where docId = ?", docIds); + // requestLog写入建模 + LinkedHashMap map = new LinkedHashMap<>(); + int count = schroederQRCodeService.getTaskIdByRequestId(requestId); + if(Util.getIntValue(String.valueOf(count),-1) < 0){ + count = 1; + }else { + count += 1; + } + map.put("count", count); + map.put("cusRequestId", requestId); + requestIdLogModelIdList = CusInfoToOAUtil.executeBatch(Util.getIntValue(requestIdLogModelId, -1), Collections.singletonList(map)); + }catch (Exception e){ + throw new CustomerException(Util.logStr("数据写入建模异常!:{}", e.getMessage())); + } + + String scanNum = schroederQRCodeService.pushSealTask(onlyMark, billTable, requestId, type, successCode, backField, filePeopleType); // 推送数据创建任务 建模配置唯一标识 + String updateSql = "update " + billTable + " set " + QRCodeField + " = ? where requestid = ?"; // 二维码来源字段 if(!trans.executeUpdate(updateSql, scanNum, requestId)){ throw new CustomerException(Util.logStr("更新表单sql执行失败!sql : {}, 参数 scanNum : {}, requestId : {}", scanNum, requestId)); // 自定义异常类 create 2022/3/9 2:20 PM 构建日志字符串 } - // 获取明细表数据 - List> detailList = getDetailTableValueByDetailNo(1, requestInfo); - List docIds = detailList.stream() - .map(item -> Util.null2DefaultStr(item.get(fileField), "")) - .filter(StringUtils::isNotBlank).collect(Collectors.toList()); - ArrayList> list = new ArrayList<>(); - for (String docId : docIds) { - LinkedHashMap map = new LinkedHashMap<>(); - map.put("docId", docId); - map.put("enable", 0); - list.add(map); - } - // 将数据写入建模 - CusInfoToOAUtil.executeBatch(Util.getIntValue(modelId, -1), list, "select 1 from #{tableName} where docId = ?", docIds); + }catch (Exception e){ + CommonUtil.deleteDataByIds(requestIdLogModelIdList, Util.getIntValue(requestIdLogModelId,-1)); + CommonUtil.deleteDataByIds(docLogModelIdList, Util.getIntValue(docLogModelId,-1)); trans.rollback(); throw new CustomerException(Util.logStr("执行提交方法异常:{}", e.getMessage())); // 自定义异常类 create 2022/3/9 2:20 PM 构建日志字符串 + }finally { + log.info(Util.logStr("del: {}, sql: {}, mainId: {}", del, delSql, mainId)); + if(del && StringUtils.isNotBlank(delSql)){ + RecordSet rs = new RecordSet(); + if(!rs.executeUpdate(delSql, mainId)){ + log.error(Util.logStr("删除明细表失败! sql: {}, mainId: {}", delSql, mainId)); + } + } } trans.commit(); } + + + + /** + *

执行自定义后置处理方法

+ * + * @param className 全路径类名 + * @return 返回值 + */ + private boolean executeBeforeProcessor(String className, RequestInfo requestInfo, + RequestMappingConfig requestMappingConfig, + Map pathParam) { + Class aClass; + try { + aClass = Class.forName(className); + } catch (ClassNotFoundException e) { + throw new IllegalArgumentException("未能找到自定义action前置置处理方法理接口:" + className); + } + Constructor constructor; + try { + constructor = aClass.getConstructor(); + } catch (NoSuchMethodException e) { + throw new IllegalArgumentException(className + "没有空参构造方法,无法获取构造方法对象!"); + } + if (!CusActionBeforeProcessor.class.isAssignableFrom(aClass)) { + throw new IllegalArgumentException("自定义前置置处理接口:" + className + " 不是" + + CusActionBeforeProcessor.class.getName() + "的子类或实现类!"); + } + CusActionBeforeProcessor o; + try { + o = (CusActionBeforeProcessor) constructor.newInstance(); + } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) { + throw new IllegalArgumentException("无法构造" + className + "对象!"); + } + return o.beforeProcessor(requestInfo, requestMappingConfig, pathParam); + } + + } diff --git a/src/main/java/weaver/xuanran/wang/schroeder/action/SalesforceEndpointAction.java b/src/main/java/weaver/xuanran/wang/schroeder/action/SalesforceEndpointAction.java new file mode 100644 index 0000000..2bc8c97 --- /dev/null +++ b/src/main/java/weaver/xuanran/wang/schroeder/action/SalesforceEndpointAction.java @@ -0,0 +1,45 @@ +package weaver.xuanran.wang.schroeder.action; + +import aiyh.utils.Util; +import aiyh.utils.action.SafeCusBaseAction; +import aiyh.utils.annotation.RequiredMark; +import aiyh.utils.excention.CustomerException; +import weaver.hrm.User; +import weaver.soa.workflow.request.RequestInfo; +import weaver.xuanran.wang.schroeder.service.SchroederQRCodeService; + +/** + *

施罗德强制结束任务action

+ * + * @Author xuanran.wang + * @Date 2022/12/23 10:49 + */ +public class SalesforceEndpointAction extends SafeCusBaseAction { + + /** + *

建模配置唯一标识

+ **/ + @RequiredMark + private String onlyMark; + /** + *

响应成功状态码

+ **/ + @RequiredMark + private String successCode; + /** + *

请求方式

+ **/ + @RequiredMark + private String type; + + private final SchroederQRCodeService schroederQRCodeService = new SchroederQRCodeService(); + + @Override + public void doSubmit(String requestId, String billTable, int workflowId, User user, RequestInfo requestInfo) { + try { + schroederQRCodeService.pushSealTask(onlyMark, billTable, requestId,type, successCode,"",""); + }catch (Exception e){ + throw new CustomerException(Util.logStr("执行提交方法异常:{}", e.getMessage())); // + } + } +} diff --git a/src/main/java/weaver/xuanran/wang/schroeder/before/PushSealTaskBeforeProcessor.java b/src/main/java/weaver/xuanran/wang/schroeder/before/PushSealTaskBeforeProcessor.java new file mode 100644 index 0000000..9102938 --- /dev/null +++ b/src/main/java/weaver/xuanran/wang/schroeder/before/PushSealTaskBeforeProcessor.java @@ -0,0 +1,62 @@ +package weaver.xuanran.wang.schroeder.before; + +import aiyh.utils.Util; +import aiyh.utils.excention.CustomerException; +import aiyh.utils.sqlUtil.sqlResult.impl.PrepSqlResultImpl; +import com.alibaba.fastjson.JSONObject; +import org.apache.log4j.Logger; +import weaver.conn.RecordSet; +import weaver.soa.workflow.request.RequestInfo; +import weaver.xiao.commons.config.entity.RequestMappingConfig; +import weaver.xuanran.wang.schroeder.before.interfaces.CusActionBeforeProcessor; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + *

将主表数据插入到明细

+ * + * @Author xuanran.wang + * @Date 2022/12/21 16:44 + */ +public class PushSealTaskBeforeProcessor implements CusActionBeforeProcessor { + + private final Logger logger = Util.getLogger(); + + /** + * weaver.xuanran.wang.schroeder.before.PushSealTaskBeforeProcessor?whereSql=`yyfs in (4,7)`&mapping=`yzzl:yzzl,htzyzcshj:htzyzcs,gzcshj:gzcs,frzcshj:frzcs`&detailNo=1 + */ + @Override + public boolean beforeProcessor(RequestInfo requestInfo, RequestMappingConfig requestMappingConfig, Map pathParam) { + String whereSql = pathParam.get("whereSql"); + String tableName = requestInfo.getRequestManager().getBillTableName(); + String sql = "select * from " + tableName + " where requestid = ? and " + whereSql; + RecordSet rs = new RecordSet(); + // 如果主表数据符合插入条件 + // mapping=sas:dashdjas,dhjsadh:dfhjs + logger.info(Util.logStr("前置接口 : sql : {}, 路径参数: {}", sql, JSONObject.toJSONString(pathParam))); + if(rs.executeQuery(sql, requestInfo.getRequestid()) && rs.next()){ + HashMap detailMap = new HashMap<>(); + String mapping = pathParam.get("mapping"); + String detailNo = pathParam.get("detailNo"); + String[] split = mapping.split(","); + for (String str : split) { + String[] map = str.split(":"); + detailMap.put(map[1], Util.null2DefaultStr(rs.getString(map[0]),"")); + } + detailMap.put("mainid", rs.getString("id")); + // 用印文件docId + detailMap.put(pathParam.get("fileField"),pathParam.get("fileFieldValue")); + PrepSqlResultImpl sqlResult = Util.createSqlBuilder().insertSql(tableName + "_dt" + detailNo, detailMap); + String sqlStr = sqlResult.getSqlStr(); + List args = sqlResult.getArgs(); + if (!rs.executeUpdate(sqlStr, args)) { + throw new CustomerException(Util.logStr("明细数据插入失败! sql : {}, params : {}", sqlStr, JSONObject.toJSONString(args))); + } + return true; + } + return false; + } + +} diff --git a/src/main/java/weaver/xuanran/wang/schroeder/before/interfaces/CusActionBeforeProcessor.java b/src/main/java/weaver/xuanran/wang/schroeder/before/interfaces/CusActionBeforeProcessor.java new file mode 100644 index 0000000..972f74a --- /dev/null +++ b/src/main/java/weaver/xuanran/wang/schroeder/before/interfaces/CusActionBeforeProcessor.java @@ -0,0 +1,23 @@ +package weaver.xuanran.wang.schroeder.before.interfaces; + +import weaver.soa.workflow.request.RequestInfo; +import weaver.xiao.commons.config.entity.RequestMappingConfig; + +import java.util.Map; + +/** + *

前置接口处理

+ * + * @Author xuanran.wang + * @Date 2022/12/21 16:40 + */ +public interface CusActionBeforeProcessor { + /** + * 前置处理接口 + * @param requestInfo 流程参数 + * @param requestMappingConfig 根据onlyMark生成的配置对象 + * @param pathParam 自定义前置处理类路径参数 + * @return 是否继续执行 + */ + boolean beforeProcessor(RequestInfo requestInfo, RequestMappingConfig requestMappingConfig, Map pathParam); +} diff --git a/src/main/java/weaver/xuanran/wang/schroeder/cus_field_value/PushSealTaskSealValue.java b/src/main/java/weaver/xuanran/wang/schroeder/cus_field_value/PushSealTaskSealValue.java index 1b9dc5b..eb4605c 100644 --- a/src/main/java/weaver/xuanran/wang/schroeder/cus_field_value/PushSealTaskSealValue.java +++ b/src/main/java/weaver/xuanran/wang/schroeder/cus_field_value/PushSealTaskSealValue.java @@ -27,7 +27,6 @@ public class PushSealTaskSealValue implements CusInterfaceGetValue { // 自定 @Override // 获取参数值 public Object execute(Map mainMap, Map detailMap, String currentValue, Map pathParam) { logger.info(Util.logStr("路径参数:[{}]", JSONObject.toJSONString(pathParam))); - logger.info("路径参数(字符串拼接) : " + JSONObject.toJSONString(pathParam));// 构建日志字符串 // 接口字段 String sealSnField = pathParam.get("sealSnField"); String sealNumField = pathParam.get("sealNumField"); @@ -39,7 +38,6 @@ public class PushSealTaskSealValue implements CusInterfaceGetValue { // 自定 if(checkBlank(sealSnField, sealNumField, sealSnCusSql, sealNumCusSql)){ throw new CustomerException(Util.logStr("自定义类路径中必要参数为空,请检查!当前pathParam : {}", JSONObject.toJSONString(pathParam))); // 自定义异常类 create 2022/3/9 2:20 PM 构建日志字符串 } - logger.info(Util.logStr("当前值 : {}", currentValue)); // 构建日志字符串 // 如果为空返回空集合 if(StringUtils.isBlank(currentValue)){ return Collections.emptyList(); diff --git a/src/main/java/weaver/xuanran/wang/schroeder/mapper/SchroederMapper.java b/src/main/java/weaver/xuanran/wang/schroeder/mapper/SchroederMapper.java index 1812c4c..9e53859 100644 --- a/src/main/java/weaver/xuanran/wang/schroeder/mapper/SchroederMapper.java +++ b/src/main/java/weaver/xuanran/wang/schroeder/mapper/SchroederMapper.java @@ -3,6 +3,7 @@ package weaver.xuanran.wang.schroeder.mapper; import aiyh.utils.annotation.recordset.ParamMapper; import aiyh.utils.annotation.recordset.Select; import aiyh.utils.annotation.recordset.SqlMapper; +import com.icbc.api.internal.apache.http.impl.cookie.S; import java.util.List; import java.util.Map; @@ -41,5 +42,20 @@ public interface SchroederMapper { List> selectSealFileList(@ParamMapper("fileField") String fileField, @ParamMapper("tableName") String tableName, @ParamMapper("mainId") String mainId); + /** + *

得到任务Id

+ * @author xuanran.wang + * @dateTime 2022/12/21 9:39 + * @param cusRequestId 请求id + * @return taskId + **/ + @Select("select max(count) count " + + "from uf_request_task_log " + + "where cusRequestId = #{cusRequestId} " + + "group by cusRequestId") + Integer selectTaskId(@ParamMapper("cusRequestId") String cusRequestId); + @Select("select * from $t{tableName} where mainid = #{mainId}") + List> detailList(@ParamMapper("tableName") String tableName, + @ParamMapper("mainId") String mainId); } diff --git a/src/main/java/weaver/xuanran/wang/schroeder/service/SchroederQRCodeService.java b/src/main/java/weaver/xuanran/wang/schroeder/service/SchroederQRCodeService.java index ad6af3b..8d1f67a 100644 --- a/src/main/java/weaver/xuanran/wang/schroeder/service/SchroederQRCodeService.java +++ b/src/main/java/weaver/xuanran/wang/schroeder/service/SchroederQRCodeService.java @@ -5,29 +5,21 @@ import aiyh.utils.excention.CustomerException; // 自定义异常类 create 20 import aiyh.utils.httpUtil.ResponeVo; import aiyh.utils.httpUtil.util.HttpUtils; import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; import com.fasterxml.jackson.core.JsonProcessingException; -import com.google.zxing.qrcode.encoder.QRCode; -import com.icbc.api.internal.apache.http.M; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; -import org.junit.Test; -import org.springframework.beans.BeanUtils; import weaver.conn.RecordSet; -import weaver.mobile.plugin.ecology.QRCodeComInfo; import weaver.xiao.commons.config.entity.RequestMappingConfig; import weaver.xiao.commons.config.service.DealWithMapping; import weaver.xuanran.wang.schroeder.mapper.SchroederMapper; import javax.ws.rs.core.MediaType; -import java.io.File; import java.io.IOException; +import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; import java.util.stream.Collectors; /** @@ -38,10 +30,6 @@ import java.util.stream.Collectors; */ public class SchroederQRCodeService { private static final int SUCCESS_CODE = 200; - /** - *

成功状态码

- **/ - private static final int SUCCESS_STATUS= 0; /** *

接口响应信息

**/ @@ -54,91 +42,154 @@ public class SchroederQRCodeService { *

接口响应状态字段

**/ private static final String STATUS_FIELD = "status"; + /** + *

get

+ **/ + public static final String GET = "GET"; + /** + *

post

+ **/ + public static final String POST = "POST"; + /** + *

requestId记录表名

+ **/ private final DealWithMapping dealWithMapping = new DealWithMapping(); private final Logger log = Util.getLogger(); // 获取日志对象 private final HttpUtils httpUtils = new HttpUtils(); + { httpUtils.getGlobalCache().header.put("Content-Type", MediaType.APPLICATION_JSON); // 全局请求头 } + private final SchroederMapper schroederMapper = Util.getMapper(SchroederMapper.class); /** - *

推送数据创建任务

- * @author xuanran.wang - * @dateTime 2022/12/5 17:05 - * @param onlyMark 唯一编码 + *

推送数据

+ * + * @param onlyMark 唯一编码 * @param billTable 表名 * @param requestId 请求id + * @param type 请求类型 + * @param successCode 成功状态码 + * @param backField 响应字段 + * @param filePeopleType 骑缝章的 filePeopleType * @return 响应数据 + * @author xuanran.wang + * @dateTime 2022/12/5 17:05 **/ - public String pushSealTask(String onlyMark, String billTable, String requestId){ - String res = ""; + public String pushSealTask(String onlyMark, String billTable, + String requestId, String type, + String successCode, String backField,String filePeopleType) { RequestMappingConfig requestMappingConfig = dealWithMapping.treeDealWithUniqueCode(onlyMark); // 将配置参数通过唯一标识查询处理成树形结构 - String cusWhere = Util.null2DefaultStr(requestMappingConfig.getCusWhereSql(),""); - if(StringUtils.isNotBlank(cusWhere)){ - cusWhere = DealWithMapping.sbc2dbcCase(cusWhere); // 全角转半角 + Map requestParam = getParamsMap(requestMappingConfig, billTable, requestId, filePeopleType); + String url = requestMappingConfig.getRequestUrl(); + ResponeVo responeVo = null; + try { + switch (type){ + case GET: { + responeVo = httpUtils.apiGet(url, requestParam, new HashMap<>()); + }break; + case POST: { + responeVo = httpUtils.apiPost(url, requestParam); + }break; + default:throw new CustomerException("暂不支持的请求方式!"); + } + } catch (IOException e) { + throw new CustomerException(Util.logStr("发送请求发生异常! : {}", e.getMessage())); // 自定义异常类 create 2022/3/9 2:20 PM 构建日志字符串 } - String selectMainSql = "select * from " + billTable + " where requestid = ? " + cusWhere; - log.info("查询主表数据sql { " + selectMainSql + " }, requestId { " + requestId + " }"); - RecordSet recordSet = new RecordSet(); - recordSet.executeQuery(selectMainSql, requestId); - if (recordSet.next()) { - dealWithMapping.setMainTable(billTable); - Map requestParam = dealWithMapping.getRequestParam(recordSet, requestMappingConfig); - // 如果明细数据存在骑缝章时候增加一行数据进去 - changeRequestMap(requestParam, billTable + "_dt1", recordSet.getString("id")); - // 解析请求参数配置树,转换成请求参数 - log.info(Util.logStr("请求json : {}", JSONObject.toJSONString(requestParam))); // 构建日志字符串 - String url = requestMappingConfig.getRequestUrl(); - ResponeVo responeVo = null; - try { - responeVo = httpUtils.apiPost(url, requestParam); - } catch (IOException e) { - throw new CustomerException(Util.logStr("发送印章请求发生异常! : {}", e.getMessage())); // 自定义异常类 create 2022/3/9 2:20 PM 构建日志字符串 - } - Map headers = httpUtils.getGlobalCache().header; // 全局请求头 - if (responeVo.getCode() != SUCCESS_CODE) { // 相应状态码 - log.error(Util.logStr("can not fetch [{}],this request params is [{}]," + // 构建日志字符串 - "this request heard is [{}],but response status code is [{}]," + - "this response is [{}]", url, JSON.toJSON(requestParam), JSON.toJSONString(headers), responeVo.getCode(), // 相应状态码 - responeVo.getEntityString())); // 相应内容 - throw new CustomerException(Util.logStr("can not fetch [{}]", url)); // 自定义异常类 create 2022/3/9 2:20 PM 构建日志字符串 - } - Map response; - log.info(Util.logStr("this response is [{}]", responeVo.getEntityString())); // 构建日志字符串 相应内容 - try { - response = responeVo.getEntityMap(); // 根据相应结果转化为map集合 - log.info(Util.logStr("接口响应:{}", JSONObject.toJSONString(response))); // 构建日志字符串 - } catch (JsonProcessingException e) { - log.error(Util.logStr("push data error, can not parse response to map," + // 构建日志字符串 - "this response is [{}], url is [{}],request params is [{}], request heard is [{}];", - responeVo.getEntityString(), url, JSON.toJSONString(requestParam), JSON.toJSONString(headers))); // 相应内容 - throw new CustomerException(Util.logStr("push data error, can not parse response to map")); // 自定义异常类 create 2022/3/9 2:20 PM 构建日志字符串 - } - int status = (int) response.get(STATUS_FIELD); - if(SUCCESS_STATUS != status){ - throw new CustomerException(Util.logStr("接口响应码不为0,接口响应信息:{}", Util.null2DefaultStr(response.get(MESSAGE_FIELD),""))); // 自定义异常类 create 2022/3/9 2:20 PM 构建日志字符串 - } - res = Util.null2DefaultStr(response.get(SCAN_NUM_FIELD),""); + return parseResponseVo(responeVo, url, requestParam, successCode, backField); + } + + /** + *

解析响应对象

+ * @author xuanran.wang + * @dateTime 2022/12/23 11:25 + * @param responseVo 响应对象 + * @param url 地址 + * @param requestParam 请求 + * @param successCode 成功响应标识 + * @param backField 回传字段 + * @return 回传字段的值 + **/ + private String parseResponseVo(ResponeVo responseVo, String url, + Map requestParam, + String successCode, String backField){ + String res = ""; + Map headers = httpUtils.getGlobalCache().header;// 全局请求头 + if (responseVo.getCode() != SUCCESS_CODE) { // 相应状态码 + log.error(Util.logStr("can not fetch [{}],this request params is [{}]," + // 构建日志字符串 + "this request heard is [{}],but response status code is [{}]," + + "this response is [{}]", url, JSON.toJSON(requestParam), JSON.toJSONString(headers), responseVo.getCode(), // 相应状态码 + responseVo.getEntityString())); // 相应内容 + throw new CustomerException(Util.logStr("can not fetch [{}]", url)); // 自定义异常类 create 2022/3/9 2:20 PM 构建日志字符串 } - if(StringUtils.isBlank(res)){ - throw new CustomerException("获取接口中响应任务字段为空, 请检查!"); // 自定义异常类 create 2022/3/9 2:20 PM + Map response; + log.info(Util.logStr("this response is [{}]", responseVo.getEntityString())); // 构建日志字符串 相应内容 + try { + response = responseVo.getEntityMap(); // 根据相应结果转化为map集合 + } catch (JsonProcessingException e) { + log.error(Util.logStr("push data error, can not parse response to map," + // 构建日志字符串 + "this response is [{}], url is [{}],request params is [{}], request heard is [{}];", + responseVo.getEntityString(), url, JSON.toJSONString(requestParam), JSON.toJSONString(headers))); // 相应内容 + throw new CustomerException(Util.logStr("push data error, can not parse response to map")); // 自定义异常类 create 2022/3/9 2:20 PM 构建日志字符串 + } + String status = Util.null2DefaultStr(response.get(STATUS_FIELD), ""); + if (!successCode.equals(status)) { + throw new CustomerException(Util.logStr("接口响应码不为 : [{}],接口响应信息: {}", successCode, Util.null2DefaultStr(response.get(MESSAGE_FIELD), ""))); // 自定义异常类 create 2022/3/9 2:20 PM 构建日志字符串 + } + if(StringUtils.isNotBlank(backField)){ + res = Util.null2DefaultStr(response.get(backField), ""); + if (StringUtils.isBlank(res)) { + throw new CustomerException("获取接口中响应任务字段为空, 请检查!"); // 自定义异常类 create 2022/3/9 2:20 PM + } } return res; } /** - *

骑缝章修改请求参数

+ *

根据配置获取响应信息

* @author xuanran.wang - * @dateTime 2022/12/13 14:15 - * @param requestParam 请求参数 + * @dateTime 2022/12/23 11:02 + * @param requestMappingConfig 请求配置主体 * @param billTable 表名 - * @param mainId 主表id + * @param requestId 请求id + * @param filePeopleType 骑缝章的filePeopleType + * @return 参数配置map **/ - public void changeRequestMap(Map requestParam, String billTable, String mainId){ + public Map getParamsMap(RequestMappingConfig requestMappingConfig, String billTable, String requestId, String filePeopleType) { + String cusWhere = Util.null2DefaultStr(requestMappingConfig.getCusWhereSql(), ""); + if (StringUtils.isNotBlank(cusWhere)) { + cusWhere = DealWithMapping.sbc2dbcCase(cusWhere); // 全角转半角 + } + String selectMainSql = "select * from " + billTable + " where requestid = ? " + cusWhere; + log.info(Util.logStr("查询主表数据sql : {}, requestId : {}", selectMainSql, requestId)); + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(selectMainSql, requestId); + Map requestParam = new HashMap<>(); + if (recordSet.next()) { + dealWithMapping.setMainTable(billTable); + requestParam = dealWithMapping.getRequestParam(recordSet, requestMappingConfig); + // 如果明细数据存在骑缝章时候增加一行数据进去 + if (StringUtils.isNotBlank(filePeopleType)) { + changeRequestMap(requestParam, billTable + "_dt1", recordSet.getString("id"), filePeopleType); + } + } + return requestParam; + } + + /** + *

骑缝章修改请求参数

+ * + * @param requestParam 请求参数 + * @param billTable 表名 + * @param mainId 主表id + * @author xuanran.wang + * @dateTime 2022/12/13 14:15 + **/ + public void changeRequestMap(Map requestParam, String billTable, String mainId, String filePeopleType) { List> files = (List>) requestParam.get("file"); List> detail1List = schroederMapper.selectSealTaskInfoList(billTable, mainId); - if(CollectionUtils.isEmpty(detail1List) || CollectionUtils.isEmpty(files)){ + if (CollectionUtils.isEmpty(detail1List) || CollectionUtils.isEmpty(files)) { return; } // 遍历明细数据 @@ -148,25 +199,53 @@ public class SchroederQRCodeService { // 从生成的请求参数map中开始匹配 List> filterFiles = files.stream() .filter(item -> { - String filePath = Util.null2DefaultStr(item.get("filePath"), ""); - String docId = Util.null2DefaultStr(filePath.substring(filePath.lastIndexOf("=") + 1),""); + String filePath = Util.null2DefaultStr(item.get("fileUrlPath"), ""); + String docId = Util.null2DefaultStr(filePath.substring(filePath.lastIndexOf("=") + 1), ""); return sealFile.equals(docId); }) .collect(Collectors.toList()); - if(CollectionUtils.isNotEmpty(filterFiles)){ + if (CollectionUtils.isNotEmpty(filterFiles)) { // 只有一个能匹配 Map o = filterFiles.get(0); HashMap tempMap = o.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> a, HashMap::new)); // 印章集合 + List> sealList = new ArrayList<>(); HashMap seal = new HashMap<>(); - seal.put("sealSn",Util.null2DefaultStr(detailItem.get("qfzzl"),"")); - seal.put("sealNum",Util.null2DefaultStr(detailItem.get("qfzcs"),"0")); - tempMap.put("seal", seal); + seal.put("sealSn", Util.null2DefaultStr(detailItem.get("qfzzl"), "")); + seal.put("sealNum", Util.null2DefaultStr(detailItem.get("qfzcs"), "0")); + sealList.add(seal); + tempMap.put("seal", sealList); + tempMap.put("filePeopleType", filePeopleType); files.add(tempMap); } } } + + /** + *

获取taskId

+ * + * @return 任务id + * @author xuanran.wang + * @dateTime 2022/12/21 9:42 + **/ + public Integer getTaskIdByRequestId(String requestId) { + return schroederMapper.selectTaskId(requestId); + } + + /** + *

获取明细数据

+ * + * @param tableName 明细表名 + * @param mainId 主id + * @return 明细表数据 + * @author xuanran.wang + * @dateTime 2022/12/21 18:03 + **/ + public List> getDetailList(String tableName, String mainId) { + return schroederMapper.detailList(tableName, mainId); + } + } diff --git a/src/main/java/weaver/xuanran/wang/traffic_bank/waco_first/service/WacoDataPushOAService.java b/src/main/java/weaver/xuanran/wang/traffic_bank/waco_first/service/WacoDataPushOAService.java index e328250..3578d66 100644 --- a/src/main/java/weaver/xuanran/wang/traffic_bank/waco_first/service/WacoDataPushOAService.java +++ b/src/main/java/weaver/xuanran/wang/traffic_bank/waco_first/service/WacoDataPushOAService.java @@ -2,6 +2,7 @@ package weaver.xuanran.wang.traffic_bank.waco_first.service; import aiyh.utils.Util; import aiyh.utils.excention.CustomerException; +import com.alibaba.fastjson.JSONObject; import com.jcraft.jsch.ChannelSftp; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; @@ -103,9 +104,11 @@ public class WacoDataPushOAService { for (Info info : infos) { List docDetailParam = new ArrayList<>(); Map param = getParamsMapByInfo(secCategory, info, docDetailParam); + logger.info("param : " + JSONObject.toJSONString(param)); String dataId = CusInfoToOAUtil.getDataId(modelId, param, whereSql, Collections.singletonList(info.getInfoId())); + logger.info("dataId : " + JSONObject.toJSONString(dataId)); ids.add(dataId); docDetailContentParams.add(docDetailParam); } diff --git a/src/test/java/xuanran/wang/saic_travel/model_data_async/AsyncTest.java b/src/test/java/xuanran/wang/saic_travel/model_data_async/AsyncTest.java index a95e623..5214895 100644 --- a/src/test/java/xuanran/wang/saic_travel/model_data_async/AsyncTest.java +++ b/src/test/java/xuanran/wang/saic_travel/model_data_async/AsyncTest.java @@ -1,17 +1,25 @@ package xuanran.wang.saic_travel.model_data_async; +import aiyh.utils.ApiResult; +import aiyh.utils.Util; +import aiyh.utils.excention.CustomerException; import basetest.BaseTest; import com.alibaba.fastjson.JSONObject; +import com.api.xuanran.wang.saic_travel.model_create_workflow.service.CreateWorkFlowService; +import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.junit.Test; +import weaver.conn.RecordSet; import weaver.formmode.data.ModeDataApproval; -import weaver.general.Util; +import weaver.general.TimeUtil; import weaver.hrm.User; +import weaver.xuanran.wang.common.mapper.CommonMapper; import weaver.xuanran.wang.common.util.CommonUtil; import weaver.xuanran.wang.saic_travel.model_data_async.config.eneity.DataAsyncMain; import weaver.xuanran.wang.saic_travel.model_data_async.service.DataAsyncConfigService; import java.util.*; +import java.util.stream.Collectors; /** *

@@ -21,7 +29,8 @@ import java.util.*; */ public class AsyncTest extends BaseTest { private DataAsyncConfigService dataAsyncConfigService = new DataAsyncConfigService(); - + private final CommonMapper commonMapper = Util.getMapper(CommonMapper.class); + private final CreateWorkFlowService createWorkFlowService = new CreateWorkFlowService(); @Test public void testGetConfig(){ // DataAsyncMain hrmAsyncTest = dataAsyncConfigService.getDataAsyncConfigByUniqueCode("hrmAsyncTest"); @@ -45,24 +54,71 @@ public class AsyncTest extends BaseTest { @Test public void testAsync(){ -// try { -// DataAsyncMain config = dataAsyncConfigService.getDataAsyncConfigByUniqueCode("wacoTest"); -// List data = dataAsyncConfigService.asyncModelData(config, 109); -// log.info("生成的数据id : " + JSONObject.toJSONString(data)); -// }catch (Exception e){ -// log.error("生成建模数据异常 : " + e.getMessage()); + try { + DataAsyncMain config = dataAsyncConfigService.getDataAsyncConfigByUniqueCode("hrmAsyncTest"); + List data = dataAsyncConfigService.asyncModelData(config, 109); + log.info("生成的数据id : " + JSONObject.toJSONString(data)); + }catch (Exception e){ + log.error("生成建模数据异常 : " + e.getMessage()); + } + +// String choiceData = "2357,2358,2274,2275"; +// String triggerWorkflowSetId = "4"; +// // 勾选的数据集合 +// List dataList = Arrays.stream(choiceData.split(",")).collect(Collectors.toList()); +// RecordSet rs = new RecordSet(); +// List> splitList = CommonUtil.splitList(dataList); +// String name = commonMapper.getModelNameByModelId(String.valueOf(109)); +// for (List list : splitList) { +// List ids = list.stream().map(item -> aiyh.utils.Util.getIntValue(item, -1)).collect(Collectors.toList()); +// if(CollectionUtils.isEmpty(ids)){ +// continue; +// } +// } +// String sql = "select id from " + name; +// for (String id : triggerWorkflowSetId.split(",")) { +// String condition = commonMapper.getConditionByTriggerId(id); +// if(StringUtils.isNotBlank(condition)){ +// sql += " where " + condition; +// } +// log.info(aiyh.utils.Util.logStr("查询数据sql : {}", sql)); +// List filterIds = filterIds(sql); +// List dataIds = dataList.stream().filter(filterIds::contains).collect(Collectors.toList()); +// List requestIds = CommonUtil.doCreateWorkFlow(109, dataIds, aiyh.utils.Util.getIntValue(id, -1)); // 通过数据审批生成流程 +// List errorData = new ArrayList<>(); +// for (int i = 0; i < requestIds.size(); i++) { +// if (aiyh.utils.Util.getIntValue(requestIds.get(i), -1) < 0) { +// errorData.add(dataList.get(i)); +// } +// } +// log.error(Util.logStr("执行创建流程失败集合: {}",JSONObject.toJSONString(errorData))); // 构建日志字符串 // } // List list = CommonUtil.doCreateWorkFlow(109, data); // log.info("触发成功 : " + JSONObject.toJSONString(list)); - log.info("select hr.email from HrmResource hr where status in (0,1,2,3) AND "+ Util.getSubINClause("1,3,323,124,544","id","in") + " and " + Util.getSubINClause("1","id","not in")); - log.info(Util.getSubINClause("1,3,323,124,544","id","in",2)); +// log.info("select hr.email from HrmResource hr where status in (0,1,2,3) AND "+ Util.getSubINClause("1,3,323,124,544","id","in") + " and " + Util.getSubINClause("1","id","not in")); +// log.info(Util.getSubINClause("1,3,323,124,544","id","in",2)); + } + + public List filterIds(String sql){ + RecordSet rs = new RecordSet(); + ArrayList res = new ArrayList<>(); + if (rs.executeQuery(sql)) { + while (rs.next()){ + res.add(Util.null2DefaultStr(rs.getString(1),"")); + } + } + return res; } @Test - public void testNotNull(){ - String str = "jssjhgdkjs?docId={?}&{$requestid}"; - System.out.println(str.replace("{?}", "123") - .replace("{$requestid}", "12194283")); + public void testNotNull() { + try { + String datas = "2600,2601,2602,2603,2599,2598"; + String gys = createWorkFlowService.supplierCusCreateWorkFlow("6", "109", "gys", datas, 110); + log.info(" gys : " + gys); + }catch (Exception e){ + log.error("e => " + e.getMessage()); + } } public boolean checkNull(String ... args){ diff --git a/src/test/java/xuanran/wang/schroeder/download_file/DownLoadFileTest.java b/src/test/java/xuanran/wang/schroeder/download_file/DownLoadFileTest.java index cfd995b..a3e0bf2 100644 --- a/src/test/java/xuanran/wang/schroeder/download_file/DownLoadFileTest.java +++ b/src/test/java/xuanran/wang/schroeder/download_file/DownLoadFileTest.java @@ -1,6 +1,7 @@ package xuanran.wang.schroeder.download_file; import aiyh.utils.Util; +import aiyh.utils.sqlUtil.sqlResult.impl.PrepSqlResultImpl; import basetest.BaseTest; import com.alibaba.fastjson.JSONObject; import com.api.xuanran.wang.schroeder.download_file.mapper.DownLoadFileMapper; @@ -154,4 +155,49 @@ public class DownLoadFileTest extends BaseTest { String resultString = text.replaceAll("2", replacement); log.info("resultString " + resultString); } + + @Test + public void testBefore(){ + Map pathParam = Util.parseCusInterfacePathParam("weaver.xuanran.wang.schroeder.before.PushSealTaskBeforeProcessor?whereSql=`yyfs in (4,7)`&mapping=`yzzl:yzzl,htzyzcshj:htzyzcs,gzcshj:gzcs,frzcshj:frzcs`&detailNo=1"); + HashMap detailMap = new HashMap<>(); + String mapping = pathParam.get("mapping"); + String detailNo = pathParam.get("detailNo"); + String[] split = mapping.split(","); + for (String str : split) { + String[] map = str.split(":"); + detailMap.put(map[1], map[0]); + } + detailMap.put("mainid", "1"); + PrepSqlResultImpl sqlResult = Util.createSqlBuilder().insertSql("121212" + "_dt" + detailNo, detailMap); + String sqlStr = sqlResult.getSqlStr(); + List args = sqlResult.getArgs(); + log.info("sqlStr : " + sqlStr); + log.info("args : " + args); + } + + @Test + public void testUrl(){ + String serialNumber = "0199"; + String front = serialNumber.substring(0,2); + String end = serialNumber.substring(2); + log.info("front " + front); + log.info("end " + end); + int frontInt = Util.getIntValue(front); + int endInt = Util.getIntValue(end); + log.info("frontInt " + frontInt); + log.info("endInt " + endInt); + String endStr = ""; + String frontStr = ""; + if(++endInt >= 100){ + frontInt += 1; + endInt = 1; + } + if(endInt < 10){ + endStr = "0" + endInt; + } + if(frontInt < 10){ + frontStr = "0" + frontInt; + } + log.info(frontStr + endStr); + } } diff --git a/src/test/java/xuanran/wang/traffic_bank/waco_first/WacoFirstTest.java b/src/test/java/xuanran/wang/traffic_bank/waco_first/WacoFirstTest.java index 5a966ed..3699a15 100644 --- a/src/test/java/xuanran/wang/traffic_bank/waco_first/WacoFirstTest.java +++ b/src/test/java/xuanran/wang/traffic_bank/waco_first/WacoFirstTest.java @@ -72,7 +72,7 @@ public class WacoFirstTest extends BaseTest { public void testFinally() throws IOException { String currentDate = TimeUtil.getCurrentDateString(); String WACO_TEMP_PATH = "WACO" + File.separator + "temp" + File.separator; - String fileName = currentDate.replaceAll("-","") + ".zip"; + String fileName = "20221208.zip"; String zipOATempPath = GCONST.getSysFilePath() + WACO_TEMP_PATH + fileName; try { String tempFolder = GCONST.getSysFilePath() + WACO_TEMP_PATH; From 868fc51f2db97b61cac8220434f00ef8ff3192ee Mon Sep 17 00:00:00 2001 From: wangxuanran <3055088966@qq.com> Date: Tue, 3 Jan 2023 09:40:04 +0800 Subject: [PATCH 28/33] =?UTF-8?q?mq=E6=B6=88=E6=81=AF=E9=98=9F=E5=88=97?= =?UTF-8?q?=E5=BC=80=E5=8F=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../xuanran.wang/bme/js/BuildContractApply.js | 15 +- javascript/xuanran.wang/bme/js/Common.js | 21 + .../bme/js/PurchaseContractApply.js | 12 +- .../xuanran.wang/bme/js/SaleContractApply.js | 1 + pom.xml | 8 + .../action/ContractApplyComDateAction.java | 7 +- .../asset/action/AssetDataPushAction.java | 65 +++ .../asset/service/AssetDataPushService.java | 111 +++++ .../constant/RequestPushConstant.java | 94 ++++ .../datapush/eneity/DetailRequestConfig.java | 16 +- .../datapush/eneity/MainRequestConfig.java | 9 +- .../datapush/mapper/RequestPushMapper.java | 50 +++ .../datapush/service/RequestPushService.java | 401 ++++++++++++++++++ .../xuanran/wang/shyl/mq/RocketMQFactory.java | 51 +++ .../wang/shyl/mq/RocketMQListener.java | 68 +++ .../shyl/mq/constant/RocketMQConstant.java | 15 + .../wang/shyl/mq/consumer/OrgConsumer.java | 41 ++ .../shyl/mq/consumer/PassWordConsumer.java | 40 ++ .../shyl/mq/consumer/UserInfoConsumer.java | 35 ++ .../wang/shyl/mq/entity/MQMessage.java | 44 ++ .../wang/shyl/mq/entity/ModifyPassWord.java | 43 ++ .../xuanran/wang/shyl/mq/entity/Org.java | 38 ++ .../xuanran/wang/shyl/mq/entity/UserInfo.java | 61 +++ .../wang/shyl/mq/mapper/ConsumerMapper.java | 35 ++ .../shyl/mq/service/CusInfoActionService.java | 20 + .../shyl/mq/service/impl/OrgServiceImpl.java | 28 ++ .../shyl/mq/service/impl/UserServiceImpl.java | 49 +++ .../mq/service/interfaces/CreateAction.java | 14 + .../mq/service/interfaces/DeleteAction.java | 14 + .../mq/service/interfaces/PassWordAction.java | 14 + .../mq/service/interfaces/UpdateAction.java | 14 + .../xuanran/wang/shyl/mq/util/RocketUtil.java | 104 +++++ .../wang/ambofo/checkuser/CheckUserTest.java | 9 + .../wang/epdi/datapush/RequestDataPush.java | 31 ++ 34 files changed, 1556 insertions(+), 22 deletions(-) create mode 100644 src/main/java/weaver/xuanran/wang/epdi/asset/action/AssetDataPushAction.java create mode 100644 src/main/java/weaver/xuanran/wang/epdi/asset/service/AssetDataPushService.java create mode 100644 src/main/java/weaver/xuanran/wang/epdi/datapush/constant/RequestPushConstant.java create mode 100644 src/main/java/weaver/xuanran/wang/epdi/datapush/mapper/RequestPushMapper.java create mode 100644 src/main/java/weaver/xuanran/wang/epdi/datapush/service/RequestPushService.java create mode 100644 src/main/java/weaver/xuanran/wang/shyl/mq/RocketMQFactory.java create mode 100644 src/main/java/weaver/xuanran/wang/shyl/mq/RocketMQListener.java create mode 100644 src/main/java/weaver/xuanran/wang/shyl/mq/constant/RocketMQConstant.java create mode 100644 src/main/java/weaver/xuanran/wang/shyl/mq/consumer/OrgConsumer.java create mode 100644 src/main/java/weaver/xuanran/wang/shyl/mq/consumer/PassWordConsumer.java create mode 100644 src/main/java/weaver/xuanran/wang/shyl/mq/consumer/UserInfoConsumer.java create mode 100644 src/main/java/weaver/xuanran/wang/shyl/mq/entity/MQMessage.java create mode 100644 src/main/java/weaver/xuanran/wang/shyl/mq/entity/ModifyPassWord.java create mode 100644 src/main/java/weaver/xuanran/wang/shyl/mq/entity/Org.java create mode 100644 src/main/java/weaver/xuanran/wang/shyl/mq/entity/UserInfo.java create mode 100644 src/main/java/weaver/xuanran/wang/shyl/mq/mapper/ConsumerMapper.java create mode 100644 src/main/java/weaver/xuanran/wang/shyl/mq/service/CusInfoActionService.java create mode 100644 src/main/java/weaver/xuanran/wang/shyl/mq/service/impl/OrgServiceImpl.java create mode 100644 src/main/java/weaver/xuanran/wang/shyl/mq/service/impl/UserServiceImpl.java create mode 100644 src/main/java/weaver/xuanran/wang/shyl/mq/service/interfaces/CreateAction.java create mode 100644 src/main/java/weaver/xuanran/wang/shyl/mq/service/interfaces/DeleteAction.java create mode 100644 src/main/java/weaver/xuanran/wang/shyl/mq/service/interfaces/PassWordAction.java create mode 100644 src/main/java/weaver/xuanran/wang/shyl/mq/service/interfaces/UpdateAction.java create mode 100644 src/main/java/weaver/xuanran/wang/shyl/mq/util/RocketUtil.java create mode 100644 src/test/java/xuanran/wang/epdi/datapush/RequestDataPush.java diff --git a/javascript/xuanran.wang/bme/js/BuildContractApply.js b/javascript/xuanran.wang/bme/js/BuildContractApply.js index a58d098..723ec25 100644 --- a/javascript/xuanran.wang/bme/js/BuildContractApply.js +++ b/javascript/xuanran.wang/bme/js/BuildContractApply.js @@ -21,6 +21,7 @@ const detail2ComPayDateId = WfForm.convertFieldNameToId("yjfkrq",detailTable); const detail2TempDateField = WfForm.convertFieldNameToId("dyrq", detailTable); // 需要计算的款项类型集合 const computeDatePayType = ['0']; +const DETAIL_MAX_SIZE = 5; // 款项类型预计对应日期取值 const paymentTypeGetValue = { 0: (index)=>{ @@ -37,16 +38,22 @@ jQuery().ready(function(){ 'computeDatePayType': computeDatePayType, 'paymentTypeGetValue': paymentTypeGetValue } - // 默认增加5条 - for (let i = 0; i < 5; i++) { - WfForm.addDetailRow(detailTable,{ [detail2PaymentTypeId]: {value: i}}); + let rowArr = WfForm.getDetailAllRowIndexStr(detailTable).split(","); + + if(rowArr.length !== DETAIL_MAX_SIZE){ + // 默认增加5条 + for (let i = 0; i < 5; i++) { + WfForm.addDetailRow(detailTable,{ [detail2PaymentTypeId]: {value: i}}); + } } + changeDetailFieldReadOnly(detailTable, detail2ComPayDateId, detail2PaymentTypeId, computeDatePayType) + // 主表字段发生变化 mainFieldChangeDetailCom(contractSignDateId, detailTable, configObj); // 明细的款项类型字段变化绑定 - detailFieldChangeDetailCom(`${detail2AroundId},${detail2DayId}`, configObj); + detailFieldChangeDetailCom(`${detail2PaymentTypeId},${detail2AroundId},${detail2DayId}`, configObj); submitCallback(detailTable, detail2PayProportionId); diff --git a/javascript/xuanran.wang/bme/js/Common.js b/javascript/xuanran.wang/bme/js/Common.js index 230e7f0..4aae9d3 100644 --- a/javascript/xuanran.wang/bme/js/Common.js +++ b/javascript/xuanran.wang/bme/js/Common.js @@ -152,3 +152,24 @@ function changeDetailPayDate(obj){ WfForm.changeFieldAttr(`${detailComPayDateId}_${index}`, EDIT); } } + +/** + * 改变明细表字段只读 + * @param detailTable + * @param detailComDateField + * @param detailPaymentTypeId + * @param readOnlyArr + */ +function changeDetailFieldReadOnly(detailTable, detailComDateField, detailPaymentTypeId, readOnlyArr){ + let rowArr = WfForm.getDetailAllRowIndexStr(detailTable).split(","); + for(let i=0; i < rowArr.length; i++){ + let index = rowArr[i]; + if(index !== ""){ + let paymentType = WfForm.getFieldValue(`${detailPaymentTypeId}_${index}`); + // 先进行赋值 + if(readOnlyArr.includes(paymentType)){ + WfForm.changeFieldAttr(`${detailComDateField}_${index}`, READ_ONLY); + } + } + } +} diff --git a/javascript/xuanran.wang/bme/js/PurchaseContractApply.js b/javascript/xuanran.wang/bme/js/PurchaseContractApply.js index f4b95b1..4303665 100644 --- a/javascript/xuanran.wang/bme/js/PurchaseContractApply.js +++ b/javascript/xuanran.wang/bme/js/PurchaseContractApply.js @@ -4,10 +4,12 @@ */ // 明细表 const detailTable = "detail_3"; -// 主表项目字段 -const mainProjectId = WfForm.convertFieldNameToId("xmmc"); +// 主表订单编号字段 +const mainProjectId = WfForm.convertFieldNameToId("ddh1"); // 主表合同签订日期 const contractSignDateId = WfForm.convertFieldNameToId("htqdrq"); +// 主表订单申请日期 +const mainPOApplyId = WfForm.convertFieldNameToId("rkdsqrq"); // 明细2付款比例字段 const detailPayProportionId = WfForm.convertFieldNameToId("fkbl",detailTable); // 明细2款项类型 @@ -28,10 +30,10 @@ const paymentTypeGetValue = { WfForm.changeFieldValue(`${detailTempDateField}_${index}`,{value : WfForm.getFieldValue(contractSignDateId)}); }, 2: (index)=>{ - WfForm.changeFieldValue(`${detailTempDateField}_${index}`,{value : WfForm.getFieldValue(mainActualCheckId)}); + WfForm.changeFieldValue(`${detailTempDateField}_${index}`,{value : WfForm.getFieldValue(mainPOApplyId)}); }, 4: (index)=>{ - WfForm.changeFieldValue(`${detailTempDateField}_${index}`,{value : WfForm.getFieldValue(mainActualCheckId)}); + WfForm.changeFieldValue(`${detailTempDateField}_${index}`,{value : WfForm.getFieldValue(mainPOApplyId)}); } } $(()=>{ @@ -49,7 +51,7 @@ function init(){ 'computeDatePayType': computeDatePayType, 'paymentTypeGetValue': paymentTypeGetValue } - + changeDetailFieldReadOnly(detailTable, detailComPayDateId, detailPaymentTypeId, computeDatePayType) // 主表字段发生变化 mainFieldChangeDetailCom(`${mainProjectId},${contractSignDateId}`, detailTable, obj); // 明细的款项类型字段变化绑定 diff --git a/javascript/xuanran.wang/bme/js/SaleContractApply.js b/javascript/xuanran.wang/bme/js/SaleContractApply.js index 87cb38d..2836a58 100644 --- a/javascript/xuanran.wang/bme/js/SaleContractApply.js +++ b/javascript/xuanran.wang/bme/js/SaleContractApply.js @@ -52,6 +52,7 @@ function init(){ 'computeDatePayType': computeDatePayType, 'paymentTypeGetValue': paymentTypeGetValue } + changeDetailFieldReadOnly(detailTable, detail2ComPayDateId, detail2PaymentTypeId, computeDatePayType) // 主表字段发生变化 mainFieldChangeDetailCom(mainProjectId, detailTable, obj); // 明细的款项类型字段变化绑定 diff --git a/pom.xml b/pom.xml index 348d3ae..35aac38 100644 --- a/pom.xml +++ b/pom.xml @@ -80,6 +80,14 @@ + + org.apache.rocketmq + rocketmq-client + 4.4.0 + + + + diff --git a/src/main/java/weaver/xuanran/wang/bme/action/ContractApplyComDateAction.java b/src/main/java/weaver/xuanran/wang/bme/action/ContractApplyComDateAction.java index 000e4d5..2739c08 100644 --- a/src/main/java/weaver/xuanran/wang/bme/action/ContractApplyComDateAction.java +++ b/src/main/java/weaver/xuanran/wang/bme/action/ContractApplyComDateAction.java @@ -56,7 +56,8 @@ public class ContractApplyComDateAction extends SafeCusBaseAction { @Override public void doSubmit(String requestId, String billTable, int workflowId, User user, RequestInfo requestInfo) { - RecordSetTrans rs = requestInfo.getRsTrans(); + log.info(Util.logStr("--------------- requestId : {} Begin ---------------", requestId)); + RecordSetTrans rs = new RecordSetTrans(); rs.setAutoCommit(false); try { Map mainTableValue = getMainTableValue(requestInfo); @@ -74,13 +75,13 @@ public class ContractApplyComDateAction extends SafeCusBaseAction { if(StringUtils.isNotBlank(updateWhere)){ updateSql += " and " + updateWhere; } + log.info(Util.logStr("更新合同明细表sql:{}, 参数:{}, {}", updateSql, checkDate, mainId)); if(!rs.executeUpdate(updateSql, checkDate, mainId)){ - log.error(Util.logStr("更新合同明细表sql:{}, 参数:{}", updateSql, new String[]{checkDate, mainId})); throw new CustomerException("更新合同sql错误!"); } rs.commit(); }else{ - log.error(Util.logStr("查询施工合同关联项目sql : {}", selectSql)); + log.error(Util.logStr("查询施工合同关联项目sql暂未查到数据! sql {} ,{}", selectSql, requestId)); } }catch (Exception e){ rs.rollback(); diff --git a/src/main/java/weaver/xuanran/wang/epdi/asset/action/AssetDataPushAction.java b/src/main/java/weaver/xuanran/wang/epdi/asset/action/AssetDataPushAction.java new file mode 100644 index 0000000..20a60c0 --- /dev/null +++ b/src/main/java/weaver/xuanran/wang/epdi/asset/action/AssetDataPushAction.java @@ -0,0 +1,65 @@ +package weaver.xuanran.wang.epdi.asset.action; + +import aiyh.utils.Util; +import aiyh.utils.action.SafeCusBaseAction; +import aiyh.utils.annotation.PrintParamMark; +import aiyh.utils.annotation.RequiredMark; +import aiyh.utils.excention.CustomerException; +import org.apache.commons.lang3.StringUtils; +import weaver.conn.RecordSet; +import weaver.hrm.User; +import weaver.soa.workflow.request.RequestInfo; +import weaver.xuanran.wang.epdi.asset.service.AssetDataPushService; +/** + *

资产模块action

+ * + * @Author xuanran.wang + * @Date 2022/12/26 11:11 + */ +public class AssetDataPushAction extends SafeCusBaseAction { + /** + *

配置唯一标识

+ **/ + @RequiredMark + @PrintParamMark + private String uniqueCode; + /** + *

接口返回字段

+ **/ + @PrintParamMark + private String backField; + /** + *

token建模配置唯一标识

+ **/ + @RequiredMark + @PrintParamMark + private String tokenUniqueCode; + /** + *

主表字段

+ *

+ * 如果存在数据回写 就会把接口返回字段对应的值回写到此字段中 + *

+ **/ + @PrintParamMark + private String tableField; + + private final AssetDataPushService assetDataPushService = new AssetDataPushService(); + @Override + public void doSubmit(String requestId, String billTable, int workflowId, User user, RequestInfo requestInfo) { + try { + log.info("----------------- AssetDataPushAction Begin " + requestId + " -----------------"); + RecordSet updateRs = new RecordSet(); + String backVal = assetDataPushService.dataPush(uniqueCode, tokenUniqueCode, requestId, backField); + // 如果接口响应字段值不为空并且表单回写字段不为空 + if(StringUtils.isNotBlank(backVal) && StringUtils.isNotBlank(tableField)){ + String updateSql = "update " + billTable + " set " + tableField + " = ? where requestid = ?"; + if (!updateRs.executeUpdate(updateSql, backVal, requestId)) { + log.error(Util.logStr("更新表单sql : {}, 接口响应参数 : {}, 请求id : {}", backVal, requestId)); + throw new CustomerException("接口数据回写表单失败!"); + } + } + }catch (Exception e){ + throw new CustomerException(Util.logStr("数据推送action异常 : {}", e.getMessage())); + } + } +} diff --git a/src/main/java/weaver/xuanran/wang/epdi/asset/service/AssetDataPushService.java b/src/main/java/weaver/xuanran/wang/epdi/asset/service/AssetDataPushService.java new file mode 100644 index 0000000..f8260ca --- /dev/null +++ b/src/main/java/weaver/xuanran/wang/epdi/asset/service/AssetDataPushService.java @@ -0,0 +1,111 @@ +package weaver.xuanran.wang.epdi.asset.service; + +import aiyh.utils.Util; +import aiyh.utils.excention.CustomerException; +import aiyh.utils.httpUtil.ResponeVo; +import aiyh.utils.httpUtil.util.HttpUtils; +import com.alibaba.fastjson.JSON; +import com.fasterxml.jackson.core.JsonProcessingException; +import org.apache.commons.lang3.StringUtils; +import org.apache.log4j.Logger; +import weaver.xuanran.wang.epdi.datapush.eneity.MainRequestConfig; +import weaver.xuanran.wang.epdi.datapush.service.RequestPushService; + +import javax.ws.rs.core.MediaType; +import java.io.IOException; +import java.util.Map; + +/** + *

上海电力研究院数据推送业务方法

+ * + * @Author xuanran.wang + * @Date 2022/12/26 11:13 + */ +public class AssetDataPushService { + /** + *

接口响应信息

+ **/ + private static final String MESSAGE_FIELD = "repmsg"; + /** + *

接口响应处理成功标识

+ **/ + private static final String SUCCESS_CODE = "1"; + /** + *

接口响应状态码字段

+ **/ + private static final String SUCCESS_CODE_FIELD = "repcode"; + private static final String TOKEN_FIELD = "token"; + private final RequestPushService requestPushService = new RequestPushService(); + private final HttpUtils httpUtils = new HttpUtils(); + { + httpUtils.getGlobalCache().header.put("Content-Type", MediaType.APPLICATION_JSON); // 全局请求头 + } + private final Logger log = Util.getLogger(); + + /** + *

数据推送

+ * @author xuanran.wang + * @dateTime 2022/12/26 14:21 + * @param uniqueCode 请求体的建模配置唯一标识 + * @param tokenUniqueCode token建模配置唯一标识 + * @param requestId 请求id + * @param backField 回写字段 + * @return 响应返回信息 + **/ + public String dataPush(String uniqueCode, String tokenUniqueCode, String requestId, String backField){ + String token = dataPush(tokenUniqueCode, requestId, TOKEN_FIELD); + log.info(Util.logStr("token : [{}]", token)); + httpUtils.getGlobalCache().header.put("token", token); + return dataPush(uniqueCode, requestId, backField); + } + + /** + *

数据推送

+ * @author xuanran.wang + * @dateTime 2022/12/26 11:27 + * @param uniqueCode 配置唯一标识 + * @param requestId 请求id + * @param backField 响应返回字段 + * @return 响应返回信息 + **/ + private String dataPush(String uniqueCode, String requestId, String backField){ + String res = ""; + MainRequestConfig config = requestPushService.getRequestPushConfigByUniqueCode(uniqueCode); + Map requestParam = requestPushService.getRequestParam(config, requestId); + String url = config.getRequestUrl(); + Map headers = httpUtils.getGlobalCache().header;// 全局请 + ResponeVo responseVo = null; + try { + responseVo = httpUtils.apiPost(url, requestParam); + } catch (IOException e) { + throw new CustomerException(Util.logStr("发送请求发生异常! : {}", e.getMessage())); // 自定义异常类 create 2022/3/9 2:20 PM 构建日志字符串 + } + if (responseVo.getCode() != 200) { // 相应状态码 + log.error(Util.logStr("can not fetch [{}],this request params is [{}]," + // 构建日志字符串 + "this request heard is [{}],but response status code is [{}]," + + "this response is [{}]", url, JSON.toJSON(requestParam), JSON.toJSONString(headers), responseVo.getCode(), // 相应状态码 + responseVo.getEntityString())); // 相应内容 + throw new CustomerException(Util.logStr("can not fetch [{}]", url)); // 自定义异常类 create 2022/3/9 2:20 PM 构建日志字符串 + } + Map response; + try { + response = responseVo.getEntityMap(); // 根据相应结果转化为map集合 + } catch (JsonProcessingException e) { + log.error(Util.logStr("push data error, can not parse response to map," + // 构建日志字符串 + "this response is [{}], url is [{}],request params is [{}], request heard is [{}];", + responseVo.getEntityString(), url, JSON.toJSONString(requestParam), JSON.toJSONString(headers))); // 相应内容 + throw new CustomerException(Util.logStr("push data error, can not parse response to map")); // 自定义异常类 create 2022/3/9 2:20 PM 构建日志字符串 + } + String successCode = Util.null2DefaultStr(response.get(SUCCESS_CODE_FIELD), ""); + if (!successCode.equals(SUCCESS_CODE)) { + throw new CustomerException(Util.logStr("接口响应码不为 : [{}],接口响应信息: {}", successCode, Util.null2DefaultStr(response.get(MESSAGE_FIELD), ""))); // 自定义异常类 create 2022/3/9 2:20 PM 构建日志字符串 + } + if(StringUtils.isNotBlank(backField)){ + res = Util.null2DefaultStr(response.get(backField), ""); + if (StringUtils.isBlank(res)) { + throw new CustomerException("获取接口中指定返回字段 [ " + backField+ " ] 为空, 请检查!"); // 自定义异常类 create 2022/3/9 2:20 PM + } + } + return res; + } +} diff --git a/src/main/java/weaver/xuanran/wang/epdi/datapush/constant/RequestPushConstant.java b/src/main/java/weaver/xuanran/wang/epdi/datapush/constant/RequestPushConstant.java new file mode 100644 index 0000000..6a93a84 --- /dev/null +++ b/src/main/java/weaver/xuanran/wang/epdi/datapush/constant/RequestPushConstant.java @@ -0,0 +1,94 @@ +package weaver.xuanran.wang.epdi.datapush.constant; + +/** + *

uf_request_push配置表常量

+ * + * @Author xuanran.wang + * @Date 2022/12/1 14:18 + */ +public class RequestPushConstant { + /** + *

配置建模表名

+ **/ + public static final String MODEL_TABLE_NAME = "uf_request_push"; + /** + *

数据类型-普通

+ **/ + public static final String PARAM_NODE_TYPE_GENERAL = "0"; + /** + *

数据类型-对象

+ **/ + public static final String PARAM_NODE_TYPE_OBJ = "1"; + /** + *

数据类型-数组

+ **/ + public static final String PARAM_NODE_TYPE_LIST = "2"; + /** + *

配置启用

+ **/ + public static final String CONFIG_ENABLE = "0"; + /** + *

数据类型-String

+ **/ + public static final String DATA_TYPE_STRING = "0"; + /** + *

数据类型-Int

+ **/ + public static final String DATA_TYPE_INT = "1"; + /** + *

数据类型-Double

+ **/ + public static final String DATA_TYPE_DOUBLE = "2"; + /** + *

数据类型-Date

+ **/ + public static final String DATA_TYPE_DATE = "3"; + /** + *

数据类型-DateTime

+ **/ + public static final String DATA_TYPE_DATE_TIME = "4"; + /** + *

数据类型-自定义时间格式

+ **/ + public static final String DATA_TYPE_CUS_DATE = "7"; + /** + *

数据类型-时间戳

+ **/ + public static final String DATA_TYPE_TIME_TIMESTAMP = "8"; + /** + *

转换类型-当前表单字段

+ **/ + public static final String CONVERT_RULES_TABLE_FIELD = "0"; + /** + *

转换类型-默认值

+ **/ + public static final String CONVERT_RULES_DEFAULT = "1"; + /** + *

转换类型-自定义SQL

+ **/ + public static final String CONVERT_RULES_NOW_TIME = "3"; + /** + *

转换类型-当前时间

+ **/ + public static final String CONVERT_RULES_CUS_SQL = "4"; + /** + *

转换类型-requestId

+ **/ + public static final String CONVERT_RULES_REQUEST_ID = "5"; + /** + *

转换类型-数据id

+ **/ + public static final String CONVERT_RULES_DATA_ID = "6"; + /** + *

主表

+ **/ + public static final String DATASOURCE_MAIN_TABLE = "0"; + /** + *

明细

+ **/ + public static final String DATASOURCE_DETAIL_TABLE = "1"; + /** + *

根节点

+ **/ + public static final String ROOT_NODE = ""; +} diff --git a/src/main/java/weaver/xuanran/wang/epdi/datapush/eneity/DetailRequestConfig.java b/src/main/java/weaver/xuanran/wang/epdi/datapush/eneity/DetailRequestConfig.java index f227c77..6590154 100644 --- a/src/main/java/weaver/xuanran/wang/epdi/datapush/eneity/DetailRequestConfig.java +++ b/src/main/java/weaver/xuanran/wang/epdi/datapush/eneity/DetailRequestConfig.java @@ -3,19 +3,25 @@ package weaver.xuanran.wang.epdi.datapush.eneity; import lombok.Data; +import java.util.List; + /** + *

配置表明细表实体类

+ * * @Author xuanran.wang - * @Date 2022/6/18 16:47 + * @Date 2022/12/23 16:20 */ @Data public class DetailRequestConfig { private String paramName; + private String paramNodeType; + private String detailIndex; + private String parentName; private String paramType; private String getValueType; private String valueContext; - private String tableName; private String workFlowField; - private String fieldName; - private String detailId; - private String parentName; + private String dataSource; + private String workFlowFieldName; + private List detailRequestConfigList; } diff --git a/src/main/java/weaver/xuanran/wang/epdi/datapush/eneity/MainRequestConfig.java b/src/main/java/weaver/xuanran/wang/epdi/datapush/eneity/MainRequestConfig.java index bf884f1..fc9b565 100644 --- a/src/main/java/weaver/xuanran/wang/epdi/datapush/eneity/MainRequestConfig.java +++ b/src/main/java/weaver/xuanran/wang/epdi/datapush/eneity/MainRequestConfig.java @@ -6,8 +6,10 @@ import lombok.Data; import java.util.List; /** + *

配置表主表实体类

+ * * @Author xuanran.wang - * @Date 2022/6/18 15:43 + * @Date 2022/12/23 16:20 */ @Data public class MainRequestConfig { @@ -15,11 +17,8 @@ public class MainRequestConfig { private String uniqueCode; private String workflow; private String requestUrl; - private String dataSource; - private String detailIndex; private String cusSql; - private String configFilePath; private String enable; - private String methodParameterClassName; + private String tableName; private List detailRequestConfigList; } diff --git a/src/main/java/weaver/xuanran/wang/epdi/datapush/mapper/RequestPushMapper.java b/src/main/java/weaver/xuanran/wang/epdi/datapush/mapper/RequestPushMapper.java new file mode 100644 index 0000000..a08f0eb --- /dev/null +++ b/src/main/java/weaver/xuanran/wang/epdi/datapush/mapper/RequestPushMapper.java @@ -0,0 +1,50 @@ +package weaver.xuanran.wang.epdi.datapush.mapper; + +import aiyh.utils.annotation.recordset.CaseConversion; +import aiyh.utils.annotation.recordset.ParamMapper; +import aiyh.utils.annotation.recordset.Select; +import aiyh.utils.annotation.recordset.SqlMapper; +import weaver.xuanran.wang.epdi.datapush.constant.RequestPushConstant; +import weaver.xuanran.wang.epdi.datapush.eneity.DetailRequestConfig; +import weaver.xuanran.wang.epdi.datapush.eneity.MainRequestConfig; + +import java.util.List; + +/** + *

数据推送配置mapper

+ * + * @Author xuanran.wang + * @Date 2022/12/1 14:35 + */ +@SqlMapper +public interface RequestPushMapper { + + /** + *

获取配置表主表对象

+ * @author xuanran.wang + * @dateTime 2022/12/1 14:39 + * @return 主表配置对象 + **/ + @Select("select a.*,b.tablename tableName " + + "from "+ RequestPushConstant.MODEL_TABLE_NAME +" a " + + "left join workflow_table_view b " + + "on a.workFlow = b.id " + + "where uniqueCode = #{uniqueCode} and enable = " + RequestPushConstant.CONFIG_ENABLE) + @CaseConversion(value = false) + MainRequestConfig getRequestPushMainConfig(@ParamMapper("uniqueCode") String uniqueCod); + + /** + *

获取配置表明细对象集合

+ * @author xuanran.wang + * @dateTime 2022/12/1 14:40 + * @param mainId 主表主数据id + * @return 明细配置集合 + **/ + @Select("select a.*,b.fieldname workFlowFieldName " + + "from "+ RequestPushConstant.MODEL_TABLE_NAME + "_dt1 a " + + "left join workflow_field_table_view b " + + "on a.workFlowField = b.id " + + "where mainid = #{mainId} and enable = " + RequestPushConstant.CONFIG_ENABLE) + @CaseConversion(value = false) + List getRequestPushDetailConfig(@ParamMapper("mainId") String mainId); +} diff --git a/src/main/java/weaver/xuanran/wang/epdi/datapush/service/RequestPushService.java b/src/main/java/weaver/xuanran/wang/epdi/datapush/service/RequestPushService.java new file mode 100644 index 0000000..18e2558 --- /dev/null +++ b/src/main/java/weaver/xuanran/wang/epdi/datapush/service/RequestPushService.java @@ -0,0 +1,401 @@ +package weaver.xuanran.wang.epdi.datapush.service; + +import aiyh.utils.Util; +import aiyh.utils.excention.CustomerException; +import com.alibaba.fastjson.JSONObject; +import org.apache.commons.lang3.StringUtils; +import org.apache.log4j.Logger; +import org.springframework.util.Assert; +import weaver.conn.RecordSet; +import weaver.xuanran.wang.epdi.datapush.constant.RequestPushConstant; +import weaver.xuanran.wang.epdi.datapush.eneity.DetailRequestConfig; +import weaver.xuanran.wang.epdi.datapush.eneity.MainRequestConfig; +import weaver.xuanran.wang.epdi.datapush.mapper.RequestPushMapper; +import weaver.zwl.common.ToolUtil; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.*; +import java.util.stream.Collectors; + +/** + *

上海电力设计院数据推送业务方法

+ * + * @Author xuanran.wang + * @Date 2022/12/23 16:20 + */ +public class RequestPushService { + private final RequestPushMapper requestPushMapper = Util.getMapper(RequestPushMapper.class); + private String tempTableName = ""; + private final ToolUtil toolUtil = new ToolUtil(); + + private final Logger logger = Util.getLogger(); + + /** + *

获取配置对象

+ * @author xuanran.wang + * @dateTime 2022/12/1 15:09 + * @param uniqueCode 唯一标识 + * @return 配置对象 + **/ + public MainRequestConfig getRequestPushConfigByUniqueCode(String uniqueCode){ + MainRequestConfig requestPushMainConfig = requestPushMapper.getRequestPushMainConfig(uniqueCode); + Assert.notNull(requestPushMainConfig,"主表配置对象获取为空, 请检查!"); + List requestPushDetailConfig = requestPushMapper.getRequestPushDetailConfig(requestPushMainConfig.getId()); + Assert.notEmpty(requestPushDetailConfig, "明细表配置集合获取为空, 请检查!"); + requestPushMainConfig.setDetailRequestConfigList(requestPushDetailConfig); + return requestPushMainConfig; + } + + /** + *

根据配置转换流程表单

+ * @author xuanran.wang + * @dateTime 2022/12/23 17:17 + * @param mainRequestConfig 建模配置对象 + * @param requestId 请求id + * @return 转换后的流程参数map + **/ + public Map getRequestParam(MainRequestConfig mainRequestConfig, String requestId){ + HashMap res = new HashMap<>(); + // 请求配置的表 + try { + List configList = mainRequestConfig.getDetailRequestConfigList(); + // 过滤根节点 + List rootNodeList = configList + .stream() + .filter(item -> RequestPushConstant.ROOT_NODE.equals(item.getParentName())) + .collect(Collectors.toList()); + // 设置子节点 + for (DetailRequestConfig detailRequestConfig : rootNodeList) { + setChildList(detailRequestConfig, configList); + } + String workflowType = mainRequestConfig.getWorkflow(); + if(StringUtils.isBlank(workflowType)){ + setObjValue(rootNodeList, res, null, null); + }else { + String mainTableName = mainRequestConfig.getTableName(); + this.tempTableName = mainTableName; + RecordSet mainRs = new RecordSet(); + String sql = "select * from " + mainTableName + " where requestid = ?"; + if (mainRs.executeQuery(sql,requestId)) { + if (mainRs.next()) { + setObjValue(rootNodeList, res, mainRs, null); + } + } + } + }catch (Exception e){ + throw new RuntimeException("执行getRequestParam发生异常 : " + e.getMessage()); + } + return res; + } + + /** + *

<递归设置子对象/h1> + * @author xuanran.wang + * @dateTime 2022/12/23 17:16 + * @param detailRequestConfig 明细配置对象 + * @param detailRequestConfigList 明细配置对象集合 + **/ + private void setChildList(DetailRequestConfig detailRequestConfig, List detailRequestConfigList){ + try { + // 节点类型 + String paramNodeType = detailRequestConfig.getParamNodeType(); + // 参数名称 + String paramName = detailRequestConfig.getParamName(); + // 递归设置子节点 + if(!RequestPushConstant.PARAM_NODE_TYPE_GENERAL.equals(paramNodeType)){ + List childList = + detailRequestConfigList.stream().filter( + config -> paramName.equals(config.getParentName()) + ).collect(Collectors.toList()); + detailRequestConfig.setDetailRequestConfigList(childList); + for (DetailRequestConfig requestConfig : childList) { + setChildList(requestConfig, detailRequestConfigList); + } + } + }catch (Exception e){ + throw new RuntimeException("执行setChildList发生异常 : " + e.getMessage()); + } + } + + /** + *

设置对象类型配置参数值

+ * @author xuanran.wang + * @dateTime 2022/12/23 17:25 + * @param configList 配置集合 + * @param res map + * @param mainRs 主表结果集 + * @param detailRs 明细结果集 + **/ + private void setObjValue(List configList, HashMap res, RecordSet mainRs, RecordSet detailRs) { + try { + for (DetailRequestConfig requestConfig : configList) { + // 参数类型 + String paramType = requestConfig.getParamNodeType(); + String paramName = requestConfig.getParamName(); + List childConfigList = requestConfig.getDetailRequestConfigList(); + // 集合 + if (RequestPushConstant.PARAM_NODE_TYPE_LIST.equals(paramType)) { + List list = new ArrayList<>(); + setListValue(requestConfig,childConfigList, list, mainRs); + res.put(paramName, list); + } else if (RequestPushConstant.PARAM_NODE_TYPE_OBJ.equals(paramType)) { + // 对象 + HashMap map = new HashMap<>(); + this.setObjValue(childConfigList, map, mainRs, detailRs); + }else{ + // 普通对象 + Object value = setCommonParamValue(requestConfig, mainRs, detailRs); + res.put(paramName, value); + } + } + }catch (Exception e){ + throw new RuntimeException("执行setObjValue发生异常 : " + e.getMessage()); + } + } + + /** + *

设置集合类型配置参数值

+ * @author xuanran.wang + * @dateTime 2022/12/23 17:26 + * @param detailRequestConfig 配置对象 + * @param childList 子节点配置集合 + * @param list 当前配置对象的集合 + * @param mainRs 主表结果集 + **/ + private void setListValue(DetailRequestConfig detailRequestConfig, + List childList, + List list, + RecordSet mainRs) { + try { + // 子项数据来源 + String dataSource = detailRequestConfig.getDataSource(); + // 主表 + if (RequestPushConstant.DATASOURCE_MAIN_TABLE.equals(dataSource)) { + HashMap map = new HashMap<>(); + this.setObjValue(childList, map, mainRs, null); + list.add(map); + }else if(RequestPushConstant.DATASOURCE_DETAIL_TABLE.equals(dataSource)){ + // 子表 + int mainId = weaver.general.Util.getIntValue(mainRs.getString("id")); + String sql = "select * from " + tempTableName + "_dt" + detailRequestConfig.getDetailIndex() + " where mainid = " + mainId; + RecordSet detailRs = new RecordSet(); + if(detailRs.executeQuery(sql)){ + while (detailRs.next()) { + HashMap map = new HashMap<>(); + this.setObjValue(childList, map, mainRs, detailRs); + list.add(map); + } + } + } + }catch (Exception e){ + throw new RuntimeException("执行setListValue发生异常 : " + e.getMessage()); + } + } + + /** + *

设置普通参数类型配置参数值

+ * @author xuanran.wang + * @dateTime 2022/12/23 17:27 + * @param detailRequestConfig 配置对象 + * @param mainRs 主表结果集 + * @param detailRs 明细结果集 + * @return 转化后的值 + **/ + private Object setCommonParamValue(DetailRequestConfig detailRequestConfig, RecordSet mainRs, RecordSet detailRs){ + String paramType = detailRequestConfig.getParamType(); + String getValueType = detailRequestConfig.getGetValueType(); + String valueContext = detailRequestConfig.getValueContext(); + String dataSource = detailRequestConfig.getDataSource(); + String paramName = detailRequestConfig.getParamName(); + String requestId = ""; + int mainId = -1; + if(null != mainRs){ + requestId = mainRs.getString("requestid"); + mainId = Util.getIntValue(mainRs.getString("id")); + } + int detailId = -1; + if(null != detailRs){ + detailId = Util.getIntValue(detailRs.getString("id")); + } + Object value = ""; + switch (getValueType) { + // 流程字段 + case RequestPushConstant.CONVERT_RULES_TABLE_FIELD: { + value = getRecordsetVal(detailRequestConfig, mainRs, detailRs); + } + break; + // 默认值 + case RequestPushConstant.CONVERT_RULES_DEFAULT: { + value = getRecordsetVal(detailRequestConfig, mainRs, detailRs); + value = Util.null2String(valueContext) + .replace("{?requestid}", requestId) + .replace("{?}", String.valueOf(value)); + } + break; + // 当前时间 + case RequestPushConstant.CONVERT_RULES_NOW_TIME: { + value = new Date(); + } + break; + // 自定义sql查询 + case RequestPushConstant.CONVERT_RULES_CUS_SQL: { + String tempValue = Util.null2DefaultStr(getRecordsetVal(detailRequestConfig, mainRs, detailRs),""); + value = toolUtil.getValueByChangeRule(valueContext, tempValue, requestId, detailId); + } + break; + // requestId + case RequestPushConstant.CONVERT_RULES_REQUEST_ID: { + value = requestId; + } + break; + // 数据id + case RequestPushConstant.CONVERT_RULES_DATA_ID: { + if (RequestPushConstant.DATASOURCE_MAIN_TABLE.equals(dataSource)) { + value = mainId; + } else { + value = detailId; + } + } + break; + default: + throw new CustomerException("不支持的取值方式"); + } + switch (paramType) { + // String类型 + case RequestPushConstant.DATA_TYPE_STRING: { + value = Util.null2DefaultStr(value, ""); + } + break; + // int类型 + case RequestPushConstant.DATA_TYPE_INT: { + value = Util.getIntValue(Util.null2DefaultStr(value, ""),0); + } + break; + // double类型 + case RequestPushConstant.DATA_TYPE_DOUBLE: { + value = Util.getDoubleValue(Util.null2DefaultStr(value, ""),0.00); + } + break; + // 日期类型 + case RequestPushConstant.DATA_TYPE_DATE: { + if (Objects.isNull(value)) { + value = ""; + break; + } + try { + Date date = value instanceof Date ? (Date) value : parseDate(String.valueOf(value)); + value = this.diyDateFortMat(date, "yyyy-MM-dd"); + } catch (Exception e) { + throw new CustomerException("时间处理异常:参数>>" + paramName); + } + } + break; + // 时间日期类型 + case RequestPushConstant.DATA_TYPE_DATE_TIME: { + if (Objects.isNull(value)) { + value = ""; + break; + } + try { + Date date = value instanceof Date ? (Date) value : parseDate(String.valueOf(value)); + value = this.diyDateFortMat(date, "yyyy-MM-dd HH:mm:ss"); + } catch (Exception e) { + throw new CustomerException("时间处理异常:参数>>" + paramName + " 异常信息:" + e); + } + } + break; + // 自定义时间格式化类型 + case RequestPushConstant.DATA_TYPE_CUS_DATE: { + if (Objects.isNull(value)) { + value = ""; + break; + } + try { + Date date = value instanceof Date ? (Date) value : parseDate(String.valueOf(value)); + value = this.diyDateFortMat(date, valueContext); + } catch (Exception e) { + throw new CustomerException("时间处理异常:参数>>" + paramName + " 异常信息:" + e.getMessage()); + } + } + break; + // 时间戳类型 + case RequestPushConstant.DATA_TYPE_TIME_TIMESTAMP: { + if (Objects.isNull(value)) { + value = ""; + break; + } + try { + Date date = value instanceof Date ? (Date) value : parseDate(String.valueOf(value)); + assert date != null; + value = date.getTime(); + } catch (Exception e) { + throw new CustomerException("时间处理异常:参数>>" + paramName + " 异常信息:" + e.getMessage()); + } + } + break; + default: return value; + } + return value; + } + + /** + *

获取表单字段的值

+ * @author xuanran.wang + * @dateTime 2022/12/23 17:42 + * @param config 配置对象 + * @param mainRs 主表结果集 + * @param detailRs 明细表结果集 + * @return 结果集中的值 + **/ + public Object getRecordsetVal(DetailRequestConfig config, RecordSet mainRs, RecordSet detailRs){ + String fieldName = config.getWorkFlowFieldName(); + String dataSource = config.getDataSource(); + if(StringUtils.isBlank(fieldName) || StringUtils.isBlank(dataSource)){ + return ""; + } + Object value = ""; + if (RequestPushConstant.DATASOURCE_MAIN_TABLE.equals(dataSource)) { + value = Util.null2DefaultStr(mainRs.getString(fieldName),""); + } else { + value = Util.null2DefaultStr(detailRs.getString(fieldName),""); + } + return value; + } + + /** + *

将日期字符串转换为Date对象

+ * + * @param dateStr 日期字符串 + * @return 日期对象 + */ + private static Date parseDate(String dateStr) { + ThreadLocal SIMPLE_DATE_FORMAT = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd")); + if (dateStr == null || dateStr.length() == 0) { + return null; + } + String regex = "\\/|\\.|年|月|日"; + Date date = null; + try { + date = SIMPLE_DATE_FORMAT.get().parse(dateStr.replaceAll(regex, "-")); + return date; + } catch (ParseException e) { + throw new CustomerException("无法将" + dateStr + "转换为日期对象!", e); + } + } + + /** + * 自定义时间格式化 + * + * @param date 日期 + * @param tempStr 格式化字符串 + * @return + */ + private String diyDateFortMat(Date date, String tempStr) { + SimpleDateFormat simpleDateFormat = new SimpleDateFormat(tempStr); + return simpleDateFormat.format(date); + } + + + +} diff --git a/src/main/java/weaver/xuanran/wang/shyl/mq/RocketMQFactory.java b/src/main/java/weaver/xuanran/wang/shyl/mq/RocketMQFactory.java new file mode 100644 index 0000000..efeb869 --- /dev/null +++ b/src/main/java/weaver/xuanran/wang/shyl/mq/RocketMQFactory.java @@ -0,0 +1,51 @@ +package weaver.xuanran.wang.shyl.mq; + +import aiyh.utils.Util; +import aiyh.utils.excention.CustomerException; +import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer; +import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently; +import org.apache.rocketmq.common.consumer.ConsumeFromWhere; +import org.apache.rocketmq.common.protocol.heartbeat.MessageModel; +import weaver.xuanran.wang.shyl.mq.constant.RocketMQConstant; +import weaver.xuanran.wang.shyl.mq.util.RocketUtil; + +import java.util.HashMap; +import java.util.Map; + +/** + *

rocketMQ工厂

+ * + * @Author xuanran.wang + * @Date 2022/12/29 14:21 + */ +public class RocketMQFactory { + public static Map> CONFIG_MAPS = new HashMap<>(16); + public static DefaultMQPushConsumer getMQPushConsumer(String configName, MessageListenerConcurrently messageListenerConcurrently){ + try { + Map configMap = new HashMap<>(); + if(!CONFIG_MAPS.containsKey(configName)){ + configMap = RocketUtil.initMQConfigMap(configName); + CONFIG_MAPS.put(configName, configMap); + } + int maxReconsumeTimes = Util.getIntValue(Util.null2String(configMap.get("MaxReconsumeTimes")), RocketMQConstant.DEFAULT_MAX_RECONSUME_TIMES); + // 声明一个消费者consumer,需要传入一个组 weaver-consumer + DefaultMQPushConsumer consumer = new DefaultMQPushConsumer(Util.null2String(configMap.get("ConsumerGroup"))); + // 设置集群的NameServer地址,多个地址之间以分号分隔 183.192.65.118:9876 + consumer.setNamesrvAddr(Util.null2String(configMap.get("NameServer"))); + // 设置consumer的消费策略 + consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET); + // 集群模式消费,广播消费不会重试 + consumer.setMessageModel(MessageModel.CLUSTERING); + // 设置最大重试次数,默认是16次 + consumer.setMaxReconsumeTimes(maxReconsumeTimes); + // 设置consumer所订阅的Topic和Tag,*代表全部的Tag AUTH_CONSOLE_USERINFO_TOPIC + consumer.subscribe(Util.null2String(configMap.get("Topic")), Util.null2String(configMap.get("Tag"))); + // Listener,主要进行消息的逻辑处理,监听topic,如果有消息就会立即去消费 + consumer.registerMessageListener(messageListenerConcurrently); + return consumer; + }catch (Exception e){ + throw new CustomerException(Util.logStr("consumer init error, now config name is : {} error : {}",configName, e.getMessage())); + } + } + +} diff --git a/src/main/java/weaver/xuanran/wang/shyl/mq/RocketMQListener.java b/src/main/java/weaver/xuanran/wang/shyl/mq/RocketMQListener.java new file mode 100644 index 0000000..b72f25c --- /dev/null +++ b/src/main/java/weaver/xuanran/wang/shyl/mq/RocketMQListener.java @@ -0,0 +1,68 @@ +package weaver.xuanran.wang.shyl.mq; + +import aiyh.utils.Util; +import aiyh.utils.excention.CustomerException; +import org.apache.log4j.Logger; +import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer; +import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import java.util.Map; + +/** + *

上海团校RocketMQListener

+ * + * @Author xuanran.wang + * @Date 2022/12/29 12:25 + */ +public abstract class RocketMQListener extends HttpServlet { + private static final Logger log = Util.getLogger(); + private String configName; + public RocketMQListener() { + } + public RocketMQListener(String configName) { + this.configName = configName; + } + @Override + public void init() throws ServletException { + super.init(); + initialized(); + } + + /** + *

消费者初始化

+ * @author xuanran.wang + * @dateTime 2022/12/29 21:48 + **/ + public void initialized() { + DefaultMQPushConsumer consumer = null; + log.info(Util.logStr("---- consumer : {} initialized start ----", configName)); + try { + try { + // 根据配置文件初始化一个consumer对象 + consumer = RocketMQFactory.getMQPushConsumer(configName, service()); + }catch (Exception e){ + throw new CustomerException(Util.logStr("the consumer init exception : {}", e.getMessage())); + } + try { + // 调用start()方法启动consumer + consumer.start(); + }catch (Exception e){ + throw new CustomerException(Util.logStr("the consumer start exception : {}", e.getMessage())); + } + log.info(Util.logStr("---- consumer : {} initialized end ----", configName)); + }catch (Exception e){ + log.info(Util.logStr("---- consumer : {} initialized error ----", configName)); + log.error(Util.getErrString(e)); + } + } + + /** + *

每个消费者自定义的消费业务方法

+ * @author xuanran.wang + * @dateTime 2022/12/29 21:49 + * @return MessageListenerConcurrently 消费者消费方法 + **/ + public abstract MessageListenerConcurrently service(); +} diff --git a/src/main/java/weaver/xuanran/wang/shyl/mq/constant/RocketMQConstant.java b/src/main/java/weaver/xuanran/wang/shyl/mq/constant/RocketMQConstant.java new file mode 100644 index 0000000..806fd5e --- /dev/null +++ b/src/main/java/weaver/xuanran/wang/shyl/mq/constant/RocketMQConstant.java @@ -0,0 +1,15 @@ +package weaver.xuanran.wang.shyl.mq.constant; + +/** + *

RocketMQ常量

+ * + * @Author xuanran.wang + * @Date 2022/12/30 13:25 + */ +public class RocketMQConstant { + public static final String CREATE_ACTION = "CREATE_ACTION"; + public static final String UPDATE_ACTION = "UPDATE_ACTION"; + public static final String DELETE_ACTION = "DELETE_ACTION"; + public static final String PASSWORD_ACTION = "PASSWORD_ACTION"; + public static final int DEFAULT_MAX_RECONSUME_TIMES = 5; +} diff --git a/src/main/java/weaver/xuanran/wang/shyl/mq/consumer/OrgConsumer.java b/src/main/java/weaver/xuanran/wang/shyl/mq/consumer/OrgConsumer.java new file mode 100644 index 0000000..0f2d536 --- /dev/null +++ b/src/main/java/weaver/xuanran/wang/shyl/mq/consumer/OrgConsumer.java @@ -0,0 +1,41 @@ +package weaver.xuanran.wang.shyl.mq.consumer; + +import aiyh.utils.Util; +import com.alibaba.fastjson.JSONObject; +import org.apache.log4j.Logger; +import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext; +import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus; +import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently; +import org.apache.rocketmq.common.message.MessageExt; +import weaver.xuanran.wang.shyl.mq.RocketMQFactory; +import weaver.xuanran.wang.shyl.mq.RocketMQListener; +import weaver.xuanran.wang.shyl.mq.util.RocketUtil; + +import java.util.List; +import java.util.Map; + +/** + *

部门队列消费者

+ * + * @Author xuanran.wang + * @Date 2022/12/29 14:35 + */ +public class OrgConsumer extends RocketMQListener { + + private static final Logger log = Util.getLogger(); + private static final String CONFIG_NAME = "OrgConsumer"; + + public OrgConsumer(){ + super(CONFIG_NAME); + } + + @Override + public MessageListenerConcurrently service() { + return (List list, ConsumeConcurrentlyContext consumeConcurrentlyContext)->{ + Map map = RocketMQFactory.CONFIG_MAPS.get(CONFIG_NAME); + log.info(Util.logStr("{} service config is {}", CONFIG_NAME, JSONObject.toJSONString(map))); + return ConsumeConcurrentlyStatus.RECONSUME_LATER; + }; + } + +} diff --git a/src/main/java/weaver/xuanran/wang/shyl/mq/consumer/PassWordConsumer.java b/src/main/java/weaver/xuanran/wang/shyl/mq/consumer/PassWordConsumer.java new file mode 100644 index 0000000..38d28e9 --- /dev/null +++ b/src/main/java/weaver/xuanran/wang/shyl/mq/consumer/PassWordConsumer.java @@ -0,0 +1,40 @@ +package weaver.xuanran.wang.shyl.mq.consumer; + +import aiyh.utils.Util; +import com.alibaba.fastjson.JSONObject; +import org.apache.log4j.Logger; +import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext; +import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus; +import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently; +import org.apache.rocketmq.common.message.MessageExt; +import weaver.xuanran.wang.shyl.mq.RocketMQFactory; +import weaver.xuanran.wang.shyl.mq.RocketMQListener; + +import java.util.List; +import java.util.Map; + +/** + *

密码修改队列消费者

+ * + * @Author xuanran.wang + * @Date 2022/12/29 14:35 + */ +public class PassWordConsumer extends RocketMQListener { + + private static final Logger log = Util.getLogger(); + public static final String CONFIG_NAME = "PassWordConsumer"; + + public PassWordConsumer(){ + super(CONFIG_NAME); + } + + @Override + public MessageListenerConcurrently service() { + return (List list, ConsumeConcurrentlyContext consumeConcurrentlyContext)->{ + Map map = RocketMQFactory.CONFIG_MAPS.get(CONFIG_NAME); + log.info(Util.logStr("{} service config is {}", CONFIG_NAME, JSONObject.toJSONString(map))); + return ConsumeConcurrentlyStatus.RECONSUME_LATER; + }; + } + +} diff --git a/src/main/java/weaver/xuanran/wang/shyl/mq/consumer/UserInfoConsumer.java b/src/main/java/weaver/xuanran/wang/shyl/mq/consumer/UserInfoConsumer.java new file mode 100644 index 0000000..62909ef --- /dev/null +++ b/src/main/java/weaver/xuanran/wang/shyl/mq/consumer/UserInfoConsumer.java @@ -0,0 +1,35 @@ +package weaver.xuanran.wang.shyl.mq.consumer; + +import aiyh.utils.Util; +import org.apache.log4j.Logger; +import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext; +import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently; +import org.apache.rocketmq.common.message.MessageExt; +import weaver.xuanran.wang.shyl.mq.RocketMQListener; +import weaver.xuanran.wang.shyl.mq.service.impl.UserServiceImpl; +import weaver.xuanran.wang.shyl.mq.util.RocketUtil; + +import java.util.List; + +/** + *

用户队列消费者

+ * + * @Author xuanran.wang + * @Date 2022/12/29 14:35 + */ +public class UserInfoConsumer extends RocketMQListener { + private static final Logger log = Util.getLogger(); + public static final String CONFIG_NAME = "UserInfoConsumer"; + + public UserInfoConsumer(){ + super(CONFIG_NAME); + } + + private final UserServiceImpl userInfoService = new UserServiceImpl(); + + @Override + public MessageListenerConcurrently service() { + return (List msg, ConsumeConcurrentlyContext consumeConcurrentlyContext)-> RocketUtil.execute(msg, consumeConcurrentlyContext, userInfoService, CONFIG_NAME); + } + +} diff --git a/src/main/java/weaver/xuanran/wang/shyl/mq/entity/MQMessage.java b/src/main/java/weaver/xuanran/wang/shyl/mq/entity/MQMessage.java new file mode 100644 index 0000000..1c005ab --- /dev/null +++ b/src/main/java/weaver/xuanran/wang/shyl/mq/entity/MQMessage.java @@ -0,0 +1,44 @@ +package weaver.xuanran.wang.shyl.mq.entity; + +import lombok.Data; + +/** + *

mq消息实体类

+ * + * @Author xuanran.wang + * @Date 2022/12/30 13:09 + */ +@Data +public class MQMessage { + /** + *

消息ID

+ **/ + private String id; + /** + *

消息队列名

+ *

+ * AUTH_CONSOLE_USERINFO_TOPIC: 用户队列; + * AUTH_CONSOLE_ORG_TOPIC: 机构队列; + * AUTH_CONSOLE_USERINFO_PASSWORD_TOPIC: 密码修改队列 + *

+ **/ + private String topic; + /** + *

消息内容操作类型

+ *

+ * CREATE_ACTION:新增; + * UPDATE_ACTION: 修改; + * DELETE_ACTION: 删除; + * PASSWORD_ACTION: 修改密码 + *

+ **/ + private String actionType; + /** + *

消息发送时间

+ **/ + private String sendTime; + /** + *

消息业务内容,json 格式,分业务(用户、机构、密码修改)

+ **/ + private String content; +} diff --git a/src/main/java/weaver/xuanran/wang/shyl/mq/entity/ModifyPassWord.java b/src/main/java/weaver/xuanran/wang/shyl/mq/entity/ModifyPassWord.java new file mode 100644 index 0000000..6ba71b3 --- /dev/null +++ b/src/main/java/weaver/xuanran/wang/shyl/mq/entity/ModifyPassWord.java @@ -0,0 +1,43 @@ +package weaver.xuanran.wang.shyl.mq.entity; + +/** + *

密码修改

+ * + * @Author xuanran.wang + * @Date 2022/12/30 13:59 + */ +public class ModifyPassWord { + /** + *

主键

+ **/ + private String id; + /** + *

用户ID

+ **/ + private String uid; + /** + *

用户账号

+ **/ + private String username; + /** + *

用户名称

+ **/ + private String displayName; + /** + *

旧密码

+ **/ + private String oldPassword; + /** + *

新密码

+ **/ + private String password; + /** + *

确认密码

+ **/ + private String confirmPassword; + /** + *

盐值

+ **/ + private String decipherable; + +} diff --git a/src/main/java/weaver/xuanran/wang/shyl/mq/entity/Org.java b/src/main/java/weaver/xuanran/wang/shyl/mq/entity/Org.java new file mode 100644 index 0000000..10c9ad8 --- /dev/null +++ b/src/main/java/weaver/xuanran/wang/shyl/mq/entity/Org.java @@ -0,0 +1,38 @@ + +package weaver.xuanran.wang.shyl.mq.entity; + +import lombok.Data; + +/** + *

机构实体

+ * + * @Author xuanran.wang + * @Date 2022/12/30 13:56 + */ +@Data +public class Org { + /** + *

机构ID

+ **/ + private String id; + /** + *

机构编号

+ **/ + private String orgCode; + /** + *

机构名称

+ **/ + private String orgName; + /** + *

机构父级ID

+ **/ + private String parentId; + /** + *

机构排序号

+ **/ + private String sortIndex; + /** + *

机构状态

+ **/ + private String status; +} diff --git a/src/main/java/weaver/xuanran/wang/shyl/mq/entity/UserInfo.java b/src/main/java/weaver/xuanran/wang/shyl/mq/entity/UserInfo.java new file mode 100644 index 0000000..2849a15 --- /dev/null +++ b/src/main/java/weaver/xuanran/wang/shyl/mq/entity/UserInfo.java @@ -0,0 +1,61 @@ +package weaver.xuanran.wang.shyl.mq.entity; + +import lombok.Data; + +/** + *

用户实体

+ * + * @Author xuanran.wang + * @Date 2022/12/30 13:52 + */ +@Data +public class UserInfo { + /** + *

用户ID

+ **/ + private String id; + /** + *

用户账号

+ **/ + private String userName; + /** + *

用户名称

+ **/ + private String displayName; + /** + *

用户性别

+ **/ + private String gender; + /** + *

用户生日

+ **/ + private String birthDate; + /** + *

用户证件类型

+ **/ + private String idType; + /** + *

用户证件号

+ **/ + private String idCardNo; + /** + *

用户邮箱

+ **/ + private String email; + /** + *

用户手机号

+ **/ + private String mobile; + /** + *

用户机构ID

+ **/ + private String departmentId; + /** + *

用户机构名称

+ **/ + private String department; + /** + *

用户状态

+ **/ + private String status; +} diff --git a/src/main/java/weaver/xuanran/wang/shyl/mq/mapper/ConsumerMapper.java b/src/main/java/weaver/xuanran/wang/shyl/mq/mapper/ConsumerMapper.java new file mode 100644 index 0000000..d9757b1 --- /dev/null +++ b/src/main/java/weaver/xuanran/wang/shyl/mq/mapper/ConsumerMapper.java @@ -0,0 +1,35 @@ +package weaver.xuanran.wang.shyl.mq.mapper; + +import aiyh.utils.annotation.recordset.ParamMapper; +import aiyh.utils.annotation.recordset.Update; + +/** + *

消费者mapper

+ * + * @Author xuanran.wang + * @Date 2022/12/30 14:19 + */ +public interface ConsumerMapper { + + /** + *

通过outKey更新人员状态为离职

+ * @author xuanran.wang + * @dateTime 2022/12/30 14:33 + * @param outKey 外部系统id + * @return 更新成功/失败 + **/ + @Update("update hrmresource set status = 5 where outkey = #{outKey}") + boolean updateUserStatusByOutKey(@ParamMapper("outKey") String outKey); + + /** + *

通过outKey删除部门信息

+ * @author xuanran.wang + * @dateTime 2022/12/30 14:33 + * @param outKey 外部系统id + * @return 删除是否成功 + **/ + @Update("delete hrmdepartment where outkey = #{outKey}") + boolean deleteDepartmentByOutKey(@ParamMapper("outKey") String outKey); + + +} diff --git a/src/main/java/weaver/xuanran/wang/shyl/mq/service/CusInfoActionService.java b/src/main/java/weaver/xuanran/wang/shyl/mq/service/CusInfoActionService.java new file mode 100644 index 0000000..da25254 --- /dev/null +++ b/src/main/java/weaver/xuanran/wang/shyl/mq/service/CusInfoActionService.java @@ -0,0 +1,20 @@ +package weaver.xuanran.wang.shyl.mq.service; + +import aiyh.utils.Util; +import weaver.xuanran.wang.shyl.mq.mapper.ConsumerMapper; +import weaver.xuanran.wang.shyl.mq.service.interfaces.CreateAction; +import weaver.xuanran.wang.shyl.mq.service.interfaces.DeleteAction; +import weaver.xuanran.wang.shyl.mq.service.interfaces.UpdateAction; + +/** + *

抽象类

+ * + * @Author xuanran.wang + * @Date 2022/12/30 13:04 + */ +public abstract class CusInfoActionService implements CreateAction, DeleteAction, UpdateAction { + /** + *

consumer-mapper

+ **/ + protected final ConsumerMapper consumerMapper = Util.getMapper(ConsumerMapper.class); +} diff --git a/src/main/java/weaver/xuanran/wang/shyl/mq/service/impl/OrgServiceImpl.java b/src/main/java/weaver/xuanran/wang/shyl/mq/service/impl/OrgServiceImpl.java new file mode 100644 index 0000000..86212be --- /dev/null +++ b/src/main/java/weaver/xuanran/wang/shyl/mq/service/impl/OrgServiceImpl.java @@ -0,0 +1,28 @@ +package weaver.xuanran.wang.shyl.mq.service.impl; + +import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus; +import weaver.xuanran.wang.shyl.mq.entity.MQMessage; +import weaver.xuanran.wang.shyl.mq.service.CusInfoActionService; + +/** + *

+ * + * @Author xuanran.wang + * @Date 2022/12/30 15:05 + */ +public class OrgServiceImpl extends CusInfoActionService { + @Override + public ConsumeConcurrentlyStatus cusCreateAction(MQMessage message) { + return null; + } + + @Override + public ConsumeConcurrentlyStatus cusDeleteAction(MQMessage message) { + return null; + } + + @Override + public ConsumeConcurrentlyStatus cusUpdateAction(MQMessage message) { + return null; + } +} diff --git a/src/main/java/weaver/xuanran/wang/shyl/mq/service/impl/UserServiceImpl.java b/src/main/java/weaver/xuanran/wang/shyl/mq/service/impl/UserServiceImpl.java new file mode 100644 index 0000000..8beaee6 --- /dev/null +++ b/src/main/java/weaver/xuanran/wang/shyl/mq/service/impl/UserServiceImpl.java @@ -0,0 +1,49 @@ +package weaver.xuanran.wang.shyl.mq.service.impl; + +import aiyh.utils.Util; +import aiyh.utils.excention.CustomerException; +import com.alibaba.fastjson.JSONObject; +import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus; +import weaver.xuanran.wang.shyl.mq.entity.MQMessage; +import weaver.xuanran.wang.shyl.mq.entity.UserInfo; +import weaver.xuanran.wang.shyl.mq.mapper.ConsumerMapper; +import weaver.xuanran.wang.shyl.mq.service.CusInfoActionService; + +/** + *

用户业务方法

+ * + * @Author xuanran.wang + * @Date 2022/12/30 13:04 + */ +public class UserServiceImpl extends CusInfoActionService { + + @Override + public ConsumeConcurrentlyStatus cusCreateAction(MQMessage message) { + String content = message.getContent(); + UserInfo userInfo = JSONObject.parseObject(content, UserInfo.class); + return null; + } + + @Override + public ConsumeConcurrentlyStatus cusDeleteAction(MQMessage message) { + try { + String content = message.getContent(); + UserInfo userInfo = JSONObject.parseObject(content, UserInfo.class); + String id = userInfo.getId(); + boolean success = consumerMapper.updateUserStatusByOutKey(id); + if(!success){ + throw new CustomerException(Util.logStr("update user status error!")); + } + return ConsumeConcurrentlyStatus.CONSUME_SUCCESS; + }catch (Exception e){ + throw new CustomerException(Util.logStr("cusDeleteAction execute error : [{}]!", e.getMessage())); + } + } + + @Override + public ConsumeConcurrentlyStatus cusUpdateAction(MQMessage message) { + String content = message.getContent(); + UserInfo userInfo = JSONObject.parseObject(content, UserInfo.class); + return null; + } +} diff --git a/src/main/java/weaver/xuanran/wang/shyl/mq/service/interfaces/CreateAction.java b/src/main/java/weaver/xuanran/wang/shyl/mq/service/interfaces/CreateAction.java new file mode 100644 index 0000000..018e37a --- /dev/null +++ b/src/main/java/weaver/xuanran/wang/shyl/mq/service/interfaces/CreateAction.java @@ -0,0 +1,14 @@ +package weaver.xuanran.wang.shyl.mq.service.interfaces; + +import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus; +import weaver.xuanran.wang.shyl.mq.entity.MQMessage; + +/** + *

新增接口

+ * + * @Author xuanran.wang + * @Date 2022/12/30 13:00 + */ +public interface CreateAction { + ConsumeConcurrentlyStatus cusCreateAction(MQMessage message); +} diff --git a/src/main/java/weaver/xuanran/wang/shyl/mq/service/interfaces/DeleteAction.java b/src/main/java/weaver/xuanran/wang/shyl/mq/service/interfaces/DeleteAction.java new file mode 100644 index 0000000..ff2bc9e --- /dev/null +++ b/src/main/java/weaver/xuanran/wang/shyl/mq/service/interfaces/DeleteAction.java @@ -0,0 +1,14 @@ +package weaver.xuanran.wang.shyl.mq.service.interfaces; + +import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus; +import weaver.xuanran.wang.shyl.mq.entity.MQMessage; + +/** + *

删除接口

+ * + * @Author xuanran.wang + * @Date 2022/12/30 13:02 + */ +public interface DeleteAction { + ConsumeConcurrentlyStatus cusDeleteAction(MQMessage message); +} diff --git a/src/main/java/weaver/xuanran/wang/shyl/mq/service/interfaces/PassWordAction.java b/src/main/java/weaver/xuanran/wang/shyl/mq/service/interfaces/PassWordAction.java new file mode 100644 index 0000000..956e1cb --- /dev/null +++ b/src/main/java/weaver/xuanran/wang/shyl/mq/service/interfaces/PassWordAction.java @@ -0,0 +1,14 @@ +package weaver.xuanran.wang.shyl.mq.service.interfaces; + +import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus; +import weaver.xuanran.wang.shyl.mq.entity.MQMessage; + +/** + *

密码修改接口

+ * + * @Author xuanran.wang + * @Date 2022/12/30 13:03 + */ +public interface PassWordAction { + ConsumeConcurrentlyStatus cusPassWordAction(MQMessage message); +} diff --git a/src/main/java/weaver/xuanran/wang/shyl/mq/service/interfaces/UpdateAction.java b/src/main/java/weaver/xuanran/wang/shyl/mq/service/interfaces/UpdateAction.java new file mode 100644 index 0000000..0ad59b4 --- /dev/null +++ b/src/main/java/weaver/xuanran/wang/shyl/mq/service/interfaces/UpdateAction.java @@ -0,0 +1,14 @@ +package weaver.xuanran.wang.shyl.mq.service.interfaces; + +import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus; +import weaver.xuanran.wang.shyl.mq.entity.MQMessage; + +/** + *

更新接口

+ * + * @Author xuanran.wang + * @Date 2022/12/30 13:01 + */ +public interface UpdateAction { + ConsumeConcurrentlyStatus cusUpdateAction(MQMessage message); +} diff --git a/src/main/java/weaver/xuanran/wang/shyl/mq/util/RocketUtil.java b/src/main/java/weaver/xuanran/wang/shyl/mq/util/RocketUtil.java new file mode 100644 index 0000000..a3af6cc --- /dev/null +++ b/src/main/java/weaver/xuanran/wang/shyl/mq/util/RocketUtil.java @@ -0,0 +1,104 @@ +package weaver.xuanran.wang.shyl.mq.util; + +import aiyh.utils.Util; +import aiyh.utils.excention.CustomerException; +import com.alibaba.fastjson.JSONObject; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.collections.MapUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.log4j.Logger; +import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext; +import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus; +import org.apache.rocketmq.common.message.MessageExt; +import weaver.xuanran.wang.shyl.mq.constant.RocketMQConstant; +import weaver.xuanran.wang.shyl.mq.RocketMQFactory; +import weaver.xuanran.wang.shyl.mq.entity.MQMessage; +import weaver.xuanran.wang.shyl.mq.service.CusInfoActionService; + +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; + +/** + *

rocketMQ集成工具类

+ * + * @Author xuanran.wang + * @Date 2022/12/29 21:03 + */ +public class RocketUtil { + private static final Logger log = Util.getLogger(); + + /** + *

初始化配置文件对象

+ * @author xuanran.wang + * @dateTime 2022/12/29 12:53 + **/ + public static Map initMQConfigMap(String configName){ + Map config = Util.getProperties2Map(configName); + if(MapUtils.isEmpty(config)){ + throw new CustomerException(Util.logStr("please check /filesystem/prop/prop2map {}.properties file is exist!", configName)); + } + for (Map.Entry entry : config.entrySet()) { + String key = Util.null2DefaultStr(entry.getKey(),""); + String value = Util.null2DefaultStr(entry.getValue(),""); + if(StringUtils.isBlank(key) || StringUtils.isBlank(value)){ + throw new CustomerException(Util.logStr("the config file key is empty or key = {} value is empty!", key)); + } + } + log.info(Util.logStr("ConfigName : {} , MQConfig : {} ",configName, JSONObject.toJSONString(config))); + return config; + } + + /** + *

执行自定义业务方法

+ * @author xuanran.wang + * @dateTime 2022/12/30 13:34 + * @param msg mq消息 + * @param consumeConcurrentlyContext 消费者 + * @param cusInfoActionService 传具体的业务方法 + * @param configName 配置名称 + * @return mq消费状态 + **/ + public static ConsumeConcurrentlyStatus execute(List msg, ConsumeConcurrentlyContext consumeConcurrentlyContext, + CusInfoActionService cusInfoActionService, String configName){ + Map configMap = RocketMQFactory.CONFIG_MAPS.get(configName); + log.info(Util.logStr("{} service config is {}", configName, JSONObject.toJSONString(configMap))); + int maxReconsumeTimes = Util.getIntValue(Util.null2String(configMap.get("MaxReconsumeTimes")),RocketMQConstant.DEFAULT_MAX_RECONSUME_TIMES); + try { + if (CollectionUtils.isNotEmpty(msg)) { + MessageExt messageExt = msg.get(0); + String msgBody = ""; + MQMessage mqMessage = null; + try { + msgBody = new String(messageExt.getBody(), StandardCharsets.UTF_8); + mqMessage = JSONObject.parseObject(msgBody, MQMessage.class); + }catch (Exception e){ + throw new CustomerException(Util.logStr("parse msgBody to Message error current msgBody is {}, the error is {}", msg, e.getMessage())); + } + String actionType = mqMessage.getActionType(); + switch (actionType){ + case RocketMQConstant.CREATE_ACTION:{ + return cusInfoActionService.cusCreateAction(mqMessage); + } + case RocketMQConstant.UPDATE_ACTION:{ + return cusInfoActionService.cusUpdateAction(mqMessage); + } + case RocketMQConstant.DELETE_ACTION:{ + return cusInfoActionService.cusDeleteAction(mqMessage); + } + default: throw new CustomerException(Util.logStr("current actionType : [{}] is not supported!", actionType)); + } + }else { + log.error("the msgList is empty!"); + } + } catch (Exception e) { + // 如果重试达到最大还是异常那么先返回成功 oa将错误日志记录到日志中 + if (msg.get(0).getReconsumeTimes() == maxReconsumeTimes) { + return ConsumeConcurrentlyStatus.CONSUME_SUCCESS; + } else { + return ConsumeConcurrentlyStatus.RECONSUME_LATER; + } + } + return ConsumeConcurrentlyStatus.CONSUME_SUCCESS; + } +} diff --git a/src/test/java/xuanran/wang/ambofo/checkuser/CheckUserTest.java b/src/test/java/xuanran/wang/ambofo/checkuser/CheckUserTest.java index ebc2770..a7fe51f 100644 --- a/src/test/java/xuanran/wang/ambofo/checkuser/CheckUserTest.java +++ b/src/test/java/xuanran/wang/ambofo/checkuser/CheckUserTest.java @@ -4,6 +4,7 @@ import aiyh.utils.Util; import basetest.BaseTest; import com.api.xuanran.wang.ambofo.checkuser.service.CheckUserService; import org.junit.Test; +import weaver.interfaces.encode.AuthorizationBasic4OAuth2; /** *

安波福校验用户测试类

@@ -24,4 +25,12 @@ public class CheckUserTest extends BaseTest { log.error(Util.getErrString(e)); } } + + @Test + public void testPA(){ + String clientId = "ai-689bbdb3c4834b15af692540c62dc126"; + String clientSecret = "7o88qSgOx0SOCQxR9xFGUm0n"; + AuthorizationBasic4OAuth2 auth2 = new AuthorizationBasic4OAuth2(); + log.info(auth2.encode(clientId + ":" + clientSecret)); + } } diff --git a/src/test/java/xuanran/wang/epdi/datapush/RequestDataPush.java b/src/test/java/xuanran/wang/epdi/datapush/RequestDataPush.java new file mode 100644 index 0000000..dafea68 --- /dev/null +++ b/src/test/java/xuanran/wang/epdi/datapush/RequestDataPush.java @@ -0,0 +1,31 @@ +package xuanran.wang.epdi.datapush; + +import basetest.BaseTest; +import com.alibaba.fastjson.JSONObject; +import org.junit.Test; +import weaver.xuanran.wang.epdi.datapush.eneity.MainRequestConfig; +import weaver.xuanran.wang.epdi.datapush.service.RequestPushService; + +import java.util.Map; + +/** + *

上海电力研究院测试类

+ * + * @Author xuanran.wang + * @Date 2022/12/26 10:14 + */ +public class RequestDataPush extends BaseTest { + + private final RequestPushService requestDataPush = new RequestPushService(); + + @Test + public void testCreatesJson(){ + String requestId = "798800"; + String tableName = ""; + String uniqueCode = "token"; + MainRequestConfig config = requestDataPush.getRequestPushConfigByUniqueCode(uniqueCode); + Map requestParam = requestDataPush.getRequestParam(config, requestId); + log.info("请求参数: " + JSONObject.toJSONString(requestParam)); + + } +} From bef9b98546d372dc98057a3b8906dd91dd357693 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E5=AE=A3=E7=84=B6?= Date: Tue, 3 Jan 2023 21:03:37 +0800 Subject: [PATCH 29/33] =?UTF-8?q?mq=E6=B6=88=E6=81=AF=E9=98=9F=E5=88=97?= =?UTF-8?q?=E6=B6=88=E8=B4=B9=E8=80=85=E4=BB=A3=E7=A0=81=E7=BC=96=E5=86=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../xuanran/wang/shyl/mq/RocketMQFactory.java | 1 + .../shyl/mq/constant/RocketMQConstant.java | 19 ++ .../wang/shyl/mq/consumer/OrgConsumer.java | 8 +- .../shyl/mq/consumer/PassWordConsumer.java | 10 +- .../shyl/mq/consumer/UserInfoConsumer.java | 2 +- .../wang/shyl/mq/entity/ModifyPassWord.java | 3 + .../wang/shyl/mq/mapper/ConsumerMapper.java | 42 +++- .../shyl/mq/service/CusInfoActionService.java | 23 +- .../shyl/mq/service/impl/OrgServiceImpl.java | 150 ++++++++++++- .../mq/service/impl/PassWordServiceImpl.java | 52 +++++ .../shyl/mq/service/impl/UserServiceImpl.java | 204 +++++++++++++++++- .../xuanran/wang/shyl/mq/util/RocketUtil.java | 39 ++-- src/test/resources/ application.properties | 0 13 files changed, 517 insertions(+), 36 deletions(-) create mode 100644 src/main/java/weaver/xuanran/wang/shyl/mq/service/impl/PassWordServiceImpl.java create mode 100644 src/test/resources/ application.properties diff --git a/src/main/java/weaver/xuanran/wang/shyl/mq/RocketMQFactory.java b/src/main/java/weaver/xuanran/wang/shyl/mq/RocketMQFactory.java index efeb869..1153f0f 100644 --- a/src/main/java/weaver/xuanran/wang/shyl/mq/RocketMQFactory.java +++ b/src/main/java/weaver/xuanran/wang/shyl/mq/RocketMQFactory.java @@ -27,6 +27,7 @@ public class RocketMQFactory { configMap = RocketUtil.initMQConfigMap(configName); CONFIG_MAPS.put(configName, configMap); } + // 最大重试次数 int maxReconsumeTimes = Util.getIntValue(Util.null2String(configMap.get("MaxReconsumeTimes")), RocketMQConstant.DEFAULT_MAX_RECONSUME_TIMES); // 声明一个消费者consumer,需要传入一个组 weaver-consumer DefaultMQPushConsumer consumer = new DefaultMQPushConsumer(Util.null2String(configMap.get("ConsumerGroup"))); diff --git a/src/main/java/weaver/xuanran/wang/shyl/mq/constant/RocketMQConstant.java b/src/main/java/weaver/xuanran/wang/shyl/mq/constant/RocketMQConstant.java index 806fd5e..d015a63 100644 --- a/src/main/java/weaver/xuanran/wang/shyl/mq/constant/RocketMQConstant.java +++ b/src/main/java/weaver/xuanran/wang/shyl/mq/constant/RocketMQConstant.java @@ -1,5 +1,8 @@ package weaver.xuanran.wang.shyl.mq.constant; +import java.util.HashMap; +import java.util.Map; + /** *

RocketMQ常量

* @@ -12,4 +15,20 @@ public class RocketMQConstant { public static final String DELETE_ACTION = "DELETE_ACTION"; public static final String PASSWORD_ACTION = "PASSWORD_ACTION"; public static final int DEFAULT_MAX_RECONSUME_TIMES = 5; + public static final String SEX_GIRL = "1"; + public static final String SEX_BOY = "2"; + public static final String STATUS_ENABLE = "1"; + public static final String STATUS_NO_ENABLE = "4"; + public static final String ID_TYPE_UNKNOWN = "0"; + public static final String ID_TYPE_ID_CARD = "1"; + public static final String ID_TYPE_PASSPORT = "3"; + public static final String ID_TYPE_STU_CARD = "4"; + public static final String ID_TYPE_SOLDIER_CARD = "5"; + public static final String DEFAULT_PASSWORD = "1"; + + public static Map SEX_MAPPING = new HashMap<>(); + + static { + SEX_MAPPING.put(SEX_BOY, "0"); + } } diff --git a/src/main/java/weaver/xuanran/wang/shyl/mq/consumer/OrgConsumer.java b/src/main/java/weaver/xuanran/wang/shyl/mq/consumer/OrgConsumer.java index 0f2d536..2633780 100644 --- a/src/main/java/weaver/xuanran/wang/shyl/mq/consumer/OrgConsumer.java +++ b/src/main/java/weaver/xuanran/wang/shyl/mq/consumer/OrgConsumer.java @@ -9,6 +9,7 @@ import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently; import org.apache.rocketmq.common.message.MessageExt; import weaver.xuanran.wang.shyl.mq.RocketMQFactory; import weaver.xuanran.wang.shyl.mq.RocketMQListener; +import weaver.xuanran.wang.shyl.mq.service.impl.OrgServiceImpl; import weaver.xuanran.wang.shyl.mq.util.RocketUtil; import java.util.List; @@ -24,6 +25,7 @@ public class OrgConsumer extends RocketMQListener { private static final Logger log = Util.getLogger(); private static final String CONFIG_NAME = "OrgConsumer"; + private final OrgServiceImpl orgService = new OrgServiceImpl(); public OrgConsumer(){ super(CONFIG_NAME); @@ -31,11 +33,7 @@ public class OrgConsumer extends RocketMQListener { @Override public MessageListenerConcurrently service() { - return (List list, ConsumeConcurrentlyContext consumeConcurrentlyContext)->{ - Map map = RocketMQFactory.CONFIG_MAPS.get(CONFIG_NAME); - log.info(Util.logStr("{} service config is {}", CONFIG_NAME, JSONObject.toJSONString(map))); - return ConsumeConcurrentlyStatus.RECONSUME_LATER; - }; + return (List msg, ConsumeConcurrentlyContext consumeConcurrentlyContext) -> RocketUtil.execute(msg, consumeConcurrentlyContext, orgService, CONFIG_NAME); } } diff --git a/src/main/java/weaver/xuanran/wang/shyl/mq/consumer/PassWordConsumer.java b/src/main/java/weaver/xuanran/wang/shyl/mq/consumer/PassWordConsumer.java index 38d28e9..e45de99 100644 --- a/src/main/java/weaver/xuanran/wang/shyl/mq/consumer/PassWordConsumer.java +++ b/src/main/java/weaver/xuanran/wang/shyl/mq/consumer/PassWordConsumer.java @@ -9,6 +9,8 @@ import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently; import org.apache.rocketmq.common.message.MessageExt; import weaver.xuanran.wang.shyl.mq.RocketMQFactory; import weaver.xuanran.wang.shyl.mq.RocketMQListener; +import weaver.xuanran.wang.shyl.mq.service.impl.PassWordServiceImpl; +import weaver.xuanran.wang.shyl.mq.util.RocketUtil; import java.util.List; import java.util.Map; @@ -28,13 +30,11 @@ public class PassWordConsumer extends RocketMQListener { super(CONFIG_NAME); } + private final PassWordServiceImpl passWordService = new PassWordServiceImpl(); + @Override public MessageListenerConcurrently service() { - return (List list, ConsumeConcurrentlyContext consumeConcurrentlyContext)->{ - Map map = RocketMQFactory.CONFIG_MAPS.get(CONFIG_NAME); - log.info(Util.logStr("{} service config is {}", CONFIG_NAME, JSONObject.toJSONString(map))); - return ConsumeConcurrentlyStatus.RECONSUME_LATER; - }; + return (List msg, ConsumeConcurrentlyContext consumeConcurrentlyContext) -> RocketUtil.execute(msg, consumeConcurrentlyContext, passWordService, CONFIG_NAME); } } diff --git a/src/main/java/weaver/xuanran/wang/shyl/mq/consumer/UserInfoConsumer.java b/src/main/java/weaver/xuanran/wang/shyl/mq/consumer/UserInfoConsumer.java index 62909ef..708c069 100644 --- a/src/main/java/weaver/xuanran/wang/shyl/mq/consumer/UserInfoConsumer.java +++ b/src/main/java/weaver/xuanran/wang/shyl/mq/consumer/UserInfoConsumer.java @@ -29,7 +29,7 @@ public class UserInfoConsumer extends RocketMQListener { @Override public MessageListenerConcurrently service() { - return (List msg, ConsumeConcurrentlyContext consumeConcurrentlyContext)-> RocketUtil.execute(msg, consumeConcurrentlyContext, userInfoService, CONFIG_NAME); + return (List msg, ConsumeConcurrentlyContext consumeConcurrentlyContext) -> RocketUtil.execute(msg, consumeConcurrentlyContext, userInfoService, CONFIG_NAME); } } diff --git a/src/main/java/weaver/xuanran/wang/shyl/mq/entity/ModifyPassWord.java b/src/main/java/weaver/xuanran/wang/shyl/mq/entity/ModifyPassWord.java index 6ba71b3..f147608 100644 --- a/src/main/java/weaver/xuanran/wang/shyl/mq/entity/ModifyPassWord.java +++ b/src/main/java/weaver/xuanran/wang/shyl/mq/entity/ModifyPassWord.java @@ -1,11 +1,14 @@ package weaver.xuanran.wang.shyl.mq.entity; +import lombok.Data; + /** *

密码修改

* * @Author xuanran.wang * @Date 2022/12/30 13:59 */ +@Data public class ModifyPassWord { /** *

主键

diff --git a/src/main/java/weaver/xuanran/wang/shyl/mq/mapper/ConsumerMapper.java b/src/main/java/weaver/xuanran/wang/shyl/mq/mapper/ConsumerMapper.java index d9757b1..e3f87d7 100644 --- a/src/main/java/weaver/xuanran/wang/shyl/mq/mapper/ConsumerMapper.java +++ b/src/main/java/weaver/xuanran/wang/shyl/mq/mapper/ConsumerMapper.java @@ -3,6 +3,8 @@ package weaver.xuanran.wang.shyl.mq.mapper; import aiyh.utils.annotation.recordset.ParamMapper; import aiyh.utils.annotation.recordset.Update; +import java.util.Map; + /** *

消费者mapper

* @@ -15,7 +17,6 @@ public interface ConsumerMapper { *

通过outKey更新人员状态为离职

* @author xuanran.wang * @dateTime 2022/12/30 14:33 - * @param outKey 外部系统id * @return 更新成功/失败 **/ @Update("update hrmresource set status = 5 where outkey = #{outKey}") @@ -31,5 +32,44 @@ public interface ConsumerMapper { @Update("delete hrmdepartment where outkey = #{outKey}") boolean deleteDepartmentByOutKey(@ParamMapper("outKey") String outKey); + /** + *

通过outKey获取部门数据信息

+ * @author xuanran.wang + * @dateTime 2022/12/30 14:33 + * @param outKey 外部系统id + * @return map key : id, val : 分部id + **/ + @Update("select id departmentId, subcompanyid1 subCompanyId from hrmdepartment where outkey = #{outKey}") + Map getDepInfoByOutKey(@ParamMapper("outKey") String outKey); + /** + *

通过outKey获取人力资源id

+ * @author xuanran.wang + * @dateTime 2022/12/30 14:33 + * @param outKey 外部系统id + * @return id + **/ + @Update("select id from hrmresource where outkey = #{outKey}") + String getHrmIdByOutKey(@ParamMapper("outKey") String outKey); + + /** + *

通过outKey获取oa部门id

+ * @author xuanran.wang + * @dateTime 2022/12/30 14:33 + * @param outKey 外部系统id + * @return id + **/ + @Update("select id from hrmdepartment where outkey = #{outKey}") + String getDepIdByOutKey(@ParamMapper("outKey") String outKey); + + /** + *

通过outKey获取oa部门id

+ * @author xuanran.wang + * @dateTime 2022/12/30 14:33 + * @param id 外部系统id + * @return true/false + **/ + @Update("update hrmresource set password = #{password} where id = #{id}") + boolean updatePasswordById(@ParamMapper("id") String id, + @ParamMapper("password") String password); } diff --git a/src/main/java/weaver/xuanran/wang/shyl/mq/service/CusInfoActionService.java b/src/main/java/weaver/xuanran/wang/shyl/mq/service/CusInfoActionService.java index da25254..d9727a5 100644 --- a/src/main/java/weaver/xuanran/wang/shyl/mq/service/CusInfoActionService.java +++ b/src/main/java/weaver/xuanran/wang/shyl/mq/service/CusInfoActionService.java @@ -1,9 +1,12 @@ package weaver.xuanran.wang.shyl.mq.service; import aiyh.utils.Util; +import org.apache.log4j.Logger; +import weaver.conn.RecordSet; import weaver.xuanran.wang.shyl.mq.mapper.ConsumerMapper; import weaver.xuanran.wang.shyl.mq.service.interfaces.CreateAction; import weaver.xuanran.wang.shyl.mq.service.interfaces.DeleteAction; +import weaver.xuanran.wang.shyl.mq.service.interfaces.PassWordAction; import weaver.xuanran.wang.shyl.mq.service.interfaces.UpdateAction; /** @@ -12,9 +15,27 @@ import weaver.xuanran.wang.shyl.mq.service.interfaces.UpdateAction; * @Author xuanran.wang * @Date 2022/12/30 13:04 */ -public abstract class CusInfoActionService implements CreateAction, DeleteAction, UpdateAction { +public abstract class CusInfoActionService implements CreateAction, DeleteAction, UpdateAction, PassWordAction { + protected final RecordSet recordSet = new RecordSet(); + + protected final Logger logger = Util.getLogger(); + /** *

consumer-mapper

**/ protected final ConsumerMapper consumerMapper = Util.getMapper(ConsumerMapper.class); + + /** + *

获取下一个人员id

+ * @author xuanran.wang + * @dateTime 2023/01/03 10:50 + * @return next id + **/ + protected synchronized String getNextHrmId(){ + recordSet.executeProc("HrmResourceMaxId_Get", ""); + recordSet.next(); + //新增的部门id + return Util.null2String(recordSet.getInt(1)); + } + } diff --git a/src/main/java/weaver/xuanran/wang/shyl/mq/service/impl/OrgServiceImpl.java b/src/main/java/weaver/xuanran/wang/shyl/mq/service/impl/OrgServiceImpl.java index 86212be..5a715b1 100644 --- a/src/main/java/weaver/xuanran/wang/shyl/mq/service/impl/OrgServiceImpl.java +++ b/src/main/java/weaver/xuanran/wang/shyl/mq/service/impl/OrgServiceImpl.java @@ -1,9 +1,22 @@ package weaver.xuanran.wang.shyl.mq.service.impl; +import aiyh.utils.Util; +import aiyh.utils.excention.CustomerException; +import com.alibaba.fastjson.JSONObject; +import org.apache.commons.lang3.StringUtils; import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus; +import weaver.conn.RecordSet; +import weaver.general.TimeUtil; +import weaver.hrm.company.DepartmentComInfo; +import weaver.interfaces.hrm.HrmServiceManager; +import weaver.matrix.MatrixUtil; import weaver.xuanran.wang.shyl.mq.entity.MQMessage; +import weaver.xuanran.wang.shyl.mq.entity.Org; import weaver.xuanran.wang.shyl.mq.service.CusInfoActionService; +import java.util.ArrayList; +import java.util.List; + /** *

* @@ -11,18 +24,151 @@ import weaver.xuanran.wang.shyl.mq.service.CusInfoActionService; * @Date 2022/12/30 15:05 */ public class OrgServiceImpl extends CusInfoActionService { + /** + *

部门创建

+ * @author xuanran.wang + * @dateTime 2023/1/3 14:05 + * @param message mq消息 + * @return 成功/重试 + **/ @Override public ConsumeConcurrentlyStatus cusCreateAction(MQMessage message) { - return null; + try { + String content = message.getContent(); + Org org = JSONObject.parseObject(content, Org.class); + char separator = weaver.general.Util.getSeparator(); + // 分部id + String subId = ""; + RecordSet insertRs = new RecordSet(); + if(StringUtils.isBlank(subId)){ + throw new CustomerException("SubCompany can not be empey!"); + } + //使用存储过程新增分部 + String para = org.getOrgName() + separator + org.getOrgName() + separator + + "" + separator + "" + separator + subId + separator + org.getSortIndex() + separator + ""; + insertRs.executeProc("HrmDepartment_Insert", para); + if (insertRs.next()) { + int depId = insertRs.getInt(1); + updateDepartmentInfo(String.valueOf(depId), subId, org); + } + return ConsumeConcurrentlyStatus.CONSUME_SUCCESS; + }catch (Exception e){ + throw new CustomerException(Util.logStr("orgCreateAction error : {}", e.getMessage())); + } } + /** + *

部门删除

+ * @author xuanran.wang + * @dateTime 2023/1/3 13:59 + * @param message mq消息 + * @return 成功/重试 + **/ @Override public ConsumeConcurrentlyStatus cusDeleteAction(MQMessage message) { - return null; + try { + String content = message.getContent(); + Org org = JSONObject.parseObject(content, Org.class); + String id = org.getId(); + if(StringUtils.isBlank(id)){ + throw new CustomerException("userInfo id can not be empty!"); + } + boolean success = consumerMapper.deleteDepartmentByOutKey(id); + if (!success) { + throw new CustomerException(Util.logStr("update user status error!")); + } + return ConsumeConcurrentlyStatus.CONSUME_SUCCESS; + }catch (Exception e){ + throw new CustomerException(Util.logStr("orgDeleteAction execute error : [{}]!", e.getMessage())); + } } @Override public ConsumeConcurrentlyStatus cusUpdateAction(MQMessage message) { + try { + String content = message.getContent(); + Org org = JSONObject.parseObject(content, Org.class); + String outKey = org.getId(); + // 分部待明确 + String subId = ""; + String depId = consumerMapper.getDepIdByOutKey(outKey); + if(StringUtils.isBlank(depId)){ + throw new CustomerException(Util.logStr("The department information data obtained by foreign key is empty!")); + } + updateDepartmentInfo(depId, subId, org); + return ConsumeConcurrentlyStatus.CONSUME_SUCCESS; + }catch (Exception e){ + throw new CustomerException(Util.logStr("orgUpdateAction error : {}", e.getMessage())); + } + } + + public void updateDepartmentInfo(String depId, String subId, Org org){ + String insertSQL = "update hrmdepartment set created = ?, creater = ?, modified = ?, modifier = ?," + + " departmentcode = ?, tlevel = ?, showorder = ?, canceled = ?,departmentmark = ?, " + + " departmentname = ?, supdepid = ?, subcompanyid1 = ?, outkey = ? where id = ?"; + RecordSet updateRs = new RecordSet(); + List params = initDepartParam(String.valueOf(depId), subId, org); + if (!updateRs.executeUpdate(insertSQL, params)) { + throw new CustomerException(Util.logStr("insert HrmDepartment error sql : {}, params : {}", insertSQL, JSONObject.toJSONString(params))); + } + DepartmentComInfo dci = new DepartmentComInfo(); + //清除全部部门缓存 + dci.removeCompanyCache(); + //新增单个部门缓存 + HrmServiceManager hrmServiceManager = new HrmServiceManager(); + hrmServiceManager.SynInstantDepartment(String.valueOf(depId), "2"); + //同步分部数据到矩阵 + MatrixUtil.updateDepartmentData("" + depId); + } + + /** + *

封装部门更新/插入参数集合

+ * @author xuanran.wang + * @dateTime 2023/1/3 13:34 + * @param depId oa部门id + * @param org 部门 + * @return 更新/插入参数 + **/ + private List initDepartParam(String depId, String subId, Org org){ + List params = new ArrayList<>(); + String currentTime = TimeUtil.getCurrentTimeString(); + // 创建时间 + params.add(currentTime); + // 创建人 + params.add("1"); + // 修改时间 + params.add(currentTime); + // 修改人 + params.add("1"); + // 部门编码 + params.add(org.getOrgCode()); + // 层级结构 + params.add(org.getSortIndex()); + // 显示顺序 + params.add(org.getSortIndex()); + // 是否封存 + params.add("0"); + // 部门标识 + params.add(org.getOrgName()); + // 部门名称 + params.add(org.getOrgName()); + String parentId = org.getParentId(); + // 父级部门id + String supDepId = ""; + if(StringUtils.isNotBlank(parentId)){ + supDepId = consumerMapper.getDepIdByOutKey(parentId); + } + params.add(supDepId); + // 分部 + params.add(subId); + // out key + params.add(org.getId()); + params.add(depId); + return params; + } + + @Override + public ConsumeConcurrentlyStatus cusPassWordAction(MQMessage message) { return null; } } diff --git a/src/main/java/weaver/xuanran/wang/shyl/mq/service/impl/PassWordServiceImpl.java b/src/main/java/weaver/xuanran/wang/shyl/mq/service/impl/PassWordServiceImpl.java new file mode 100644 index 0000000..6130288 --- /dev/null +++ b/src/main/java/weaver/xuanran/wang/shyl/mq/service/impl/PassWordServiceImpl.java @@ -0,0 +1,52 @@ +package weaver.xuanran.wang.shyl.mq.service.impl; + +import aiyh.utils.Util; +import aiyh.utils.excention.CustomerException; +import com.alibaba.fastjson.JSONObject; +import org.apache.commons.lang3.StringUtils; +import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus; +import weaver.xuanran.wang.shyl.mq.entity.MQMessage; +import weaver.xuanran.wang.shyl.mq.entity.ModifyPassWord; +import weaver.xuanran.wang.shyl.mq.service.CusInfoActionService; + +/** + *

密码修改业务方法

+ * + * @author xuanran.wang + * @date 2023/1/3 16:07 + */ +public class PassWordServiceImpl extends CusInfoActionService { + @Override + public ConsumeConcurrentlyStatus cusCreateAction(MQMessage message) { + return null; + } + + @Override + public ConsumeConcurrentlyStatus cusDeleteAction(MQMessage message) { + return null; + } + + @Override + public ConsumeConcurrentlyStatus cusPassWordAction(MQMessage message) { + try { + String content = message.getContent(); + ModifyPassWord passWord = JSONObject.parseObject(content, ModifyPassWord.class); + String outKey = passWord.getId(); + String hrmId = consumerMapper.getHrmIdByOutKey(outKey); + if(StringUtils.isBlank(hrmId)){ + throw new CustomerException(Util.logStr("the userId is {} , no personnel information found in oa!", hrmId)); + } + if (!consumerMapper.updatePasswordById(hrmId, Util.getEncrypt(passWord.getPassword()))) { + throw new CustomerException("update user password error!"); + } + return ConsumeConcurrentlyStatus.CONSUME_SUCCESS; + } catch (Exception e) { + throw new CustomerException(Util.logStr("passWordAction execute error : [{}]!", e.getMessage())); + } + } + + @Override + public ConsumeConcurrentlyStatus cusUpdateAction(MQMessage message) { + return null; + } +} diff --git a/src/main/java/weaver/xuanran/wang/shyl/mq/service/impl/UserServiceImpl.java b/src/main/java/weaver/xuanran/wang/shyl/mq/service/impl/UserServiceImpl.java index 8beaee6..2078bae 100644 --- a/src/main/java/weaver/xuanran/wang/shyl/mq/service/impl/UserServiceImpl.java +++ b/src/main/java/weaver/xuanran/wang/shyl/mq/service/impl/UserServiceImpl.java @@ -3,12 +3,27 @@ package weaver.xuanran.wang.shyl.mq.service.impl; import aiyh.utils.Util; import aiyh.utils.excention.CustomerException; import com.alibaba.fastjson.JSONObject; +import com.weaver.general.TimeUtil; +import org.apache.commons.collections.MapUtils; +import org.apache.commons.lang3.StringUtils; import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus; +import weaver.conn.RecordSet; +import weaver.hrm.finance.SalaryManager; +import weaver.hrm.resource.ResourceComInfo; +import weaver.xiao.commons.utils.JsonResult; +import weaver.xuanran.wang.shyl.mq.constant.RocketMQConstant; import weaver.xuanran.wang.shyl.mq.entity.MQMessage; import weaver.xuanran.wang.shyl.mq.entity.UserInfo; import weaver.xuanran.wang.shyl.mq.mapper.ConsumerMapper; import weaver.xuanran.wang.shyl.mq.service.CusInfoActionService; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.List; +import java.util.Map; + +import static com.api.ecme.excel.HtmlLayoutOperate.user; + /** *

用户业务方法

* @@ -17,33 +32,206 @@ import weaver.xuanran.wang.shyl.mq.service.CusInfoActionService; */ public class UserServiceImpl extends CusInfoActionService { + /** + *

用户新增

+ * @author xuanran.wang + * @dateTime 2023/1/3 13:37 + * @param message mq消息 + * @return 成功/重试 + **/ @Override public ConsumeConcurrentlyStatus cusCreateAction(MQMessage message) { - String content = message.getContent(); - UserInfo userInfo = JSONObject.parseObject(content, UserInfo.class); - return null; + try { + String content = message.getContent(); + UserInfo userInfo = JSONObject.parseObject(content, UserInfo.class); + String userInfoDepartmentId = userInfo.getDepartmentId(); + // 部门id + if(StringUtils.isBlank(userInfoDepartmentId)){ + throw new CustomerException("userInfo userInfoDepartmentId can not be empty!"); + } + Map depInfoByOutKey = consumerMapper.getDepInfoByOutKey(userInfo.getDepartmentId()); + if (MapUtils.isEmpty(depInfoByOutKey)) { + // 通过外键获取部门信息数据为空 + throw new CustomerException("The department information data obtained by foreign key is empty!"); + } + String nextHrmId = getNextHrmId(); + List params = initHrmParam(nextHrmId, userInfo, depInfoByOutKey); + String departmentId = Util.null2DefaultStr(depInfoByOutKey.get("departmentId"), ""); + String subCompanyId = Util.null2DefaultStr(depInfoByOutKey.get("subCompanyId"), ""); + RecordSet insertRs = new RecordSet(); + //使用sql新增人员 + String insertSql = "insert into HrmResource(systemlanguage,workcode,departmentid,subcompanyid1," + + " status,createrid,createdate,lastmodid,lastmoddate,lastname,sex,loginid," + + " password,birthday,certificatenum,email, mobile,outkey,id) " + + " values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; + if (insertRs.executeUpdate(insertSql, params)) { + char separator = Util.getSeparator(); + Calendar todayCal = Calendar.getInstance(); + String today = Util.add0(todayCal.get(Calendar.YEAR), 4) + "-" + + Util.add0(todayCal.get(Calendar.MONTH) + 1, 2) + "-" + + Util.add0(todayCal.get(Calendar.DAY_OF_MONTH), 2); + String userPara = "" + 1 + separator + today; + insertRs.executeProc("HrmResource_CreateInfo", "" + nextHrmId + separator + userPara + separator + userPara); + ResourceComInfo resourceComInfo = new ResourceComInfo(); + resourceComInfo.addResourceInfoCache(nextHrmId); + SalaryManager salaryManager = new SalaryManager(); + salaryManager.initResourceSalary(nextHrmId); + String para1 = "" + nextHrmId + separator + "" + separator + departmentId + separator + subCompanyId + separator + "0" + separator + "0"; + insertRs.executeProc("HrmResource_Trigger_Insert", para1); + String sql_1 = ("insert into HrmInfoStatus (itemid,hrmid) values(1," + nextHrmId + ")"); + insertRs.execute(sql_1); + String sql_2 = ("insert into HrmInfoStatus (itemid,hrmid) values(2," + nextHrmId + ")"); + insertRs.execute(sql_2); + String sql_3 = ("insert into HrmInfoStatus (itemid,hrmid) values(3," + nextHrmId + ")"); + insertRs.execute(sql_3); + String sql_10 = ("insert into HrmInfoStatus (itemid,hrmid) values(10," + nextHrmId + ")"); + insertRs.execute(sql_10); + resourceComInfo.updateResourceInfoCache(nextHrmId); + return ConsumeConcurrentlyStatus.CONSUME_SUCCESS; + }else { + throw new CustomerException(Util.logStr("insert HrmResource error sql : {}, params : {}", insertSql, JSONObject.toJSONString(params))); + } + }catch (Exception e){ + throw new CustomerException(Util.logStr("hrmCreateAction error : {}", e.getMessage())); + } } + /** + *

用户删除

+ * @author xuanran.wang + * @dateTime 2023/1/3 13:38 + * @param message mq消息 + * @return 成功/重试 + **/ @Override public ConsumeConcurrentlyStatus cusDeleteAction(MQMessage message) { try { String content = message.getContent(); UserInfo userInfo = JSONObject.parseObject(content, UserInfo.class); String id = userInfo.getId(); + if(StringUtils.isBlank(id)){ + throw new CustomerException("userInfo id can not be empty!"); + } boolean success = consumerMapper.updateUserStatusByOutKey(id); - if(!success){ + if (!success) { throw new CustomerException(Util.logStr("update user status error!")); } return ConsumeConcurrentlyStatus.CONSUME_SUCCESS; - }catch (Exception e){ - throw new CustomerException(Util.logStr("cusDeleteAction execute error : [{}]!", e.getMessage())); + } catch (Exception e) { + throw new CustomerException(Util.logStr("hrmDeleteAction execute error : [{}]!", e.getMessage())); } } + /** + *

用户更新

+ * @author xuanran.wang + * @dateTime 2023/1/3 13:39 + * @param message mq消息 + * @return 成功/重试 + **/ @Override public ConsumeConcurrentlyStatus cusUpdateAction(MQMessage message) { - String content = message.getContent(); - UserInfo userInfo = JSONObject.parseObject(content, UserInfo.class); + try { + String content = message.getContent(); + UserInfo userInfo = JSONObject.parseObject(content, UserInfo.class); + String userInfoId = userInfo.getId(); + String userInfoDepartmentId = userInfo.getDepartmentId(); + // 接口人员id + if(StringUtils.isBlank(userInfoId)){ + throw new CustomerException("userInfo id can not be empty!"); + } + // 部门id + if(StringUtils.isBlank(userInfoDepartmentId)){ + throw new CustomerException("userInfo userInfoDepartmentId can not be empty!"); + } + // oa部门信息 + Map depInfoByOutKey = consumerMapper.getDepInfoByOutKey(userInfo.getDepartmentId()); + if (MapUtils.isEmpty(depInfoByOutKey)) { + // 通过外键获取部门信息数据为空 + throw new CustomerException("The department information data obtained by foreign key is empty!"); + } + // oa人员id + String hrmId = consumerMapper.getHrmIdByOutKey(userInfoId); + if(StringUtils.isBlank(hrmId)){ + throw new CustomerException(Util.logStr("userInfoId = [{}], No personnel information found in oa!", userInfoId)); + } + //使用sql新增人员 + String updateSql = "update HrmResource set systemlanguage = ?, workcode = ?, departmentid = ?, subcompanyid1 = ?," + + " status = ?,createrid = ?, createdate = ?, lastmodid = ? ,lastmoddate = ? ,lastname = ? ,sex = ?, loginid = ?, " + + " password = ?, birthday = ?,certificatenum = ?,email = ?, mobile = ? , outkey = ? where id = ? "; + List params = initHrmParam(hrmId, userInfo, depInfoByOutKey); + RecordSet updateRs = new RecordSet(); + if(!updateRs.executeUpdate(updateSql, params)){ + throw new CustomerException(Util.logStr("update HrmResource error sql : {}, params : {}", updateSql, JSONObject.toJSONString(params))); + } + ResourceComInfo resourceComInfo = new ResourceComInfo(); + // 清空缓存 + resourceComInfo.updateResourceInfoCache(hrmId); + return ConsumeConcurrentlyStatus.CONSUME_SUCCESS; + }catch (Exception e){ + throw new CustomerException(Util.logStr("hrmUpdateAction execute error : [{}]!", e.getMessage())); + } + } + + /** + *

封装人员更新/插入参数集合

+ * @author xuanran.wang + * @dateTime 2023/1/3 13:34 + * @param nextHrmId oa人员id + * @param userInfo mq人员对象 + * @param depInfoByOutKey 部门信息 + * @return 更新/插入参数 + **/ + private List initHrmParam(String nextHrmId, UserInfo userInfo, Map depInfoByOutKey){ + String password = Util.getEncrypt(RocketMQConstant.DEFAULT_PASSWORD); + String date = TimeUtil.getCurrentDateString(); + ArrayList params = new ArrayList<>(); + String userName = Util.null2DefaultStr(userInfo.getUserName(), ""); + String departmentId = Util.null2DefaultStr(depInfoByOutKey.get("departmentId"), ""); + String subCompanyId = Util.null2DefaultStr(depInfoByOutKey.get("subCompanyId"), ""); + // 语言 + params.add(7); + // 工号 + params.add(userName); + // 部门id + params.add(departmentId); + // 分部id + params.add(subCompanyId); + // 状态 + params.add(1); + // 创建人 + params.add(1); + // 创建日期 + params.add(date); + // 最后修改人 + params.add(1); + // 最后修改日期 + params.add(date); + // 人员名称 + params.add(Util.null2DefaultStr(userInfo.getDisplayName(), "")); + // 性别 如果没传就默认男 + params.add(RocketMQConstant.SEX_MAPPING.get(Util.null2DefaultStr(userInfo.getGender(), "1"))); + // 登陆名 + params.add(userName); + // 密码 + params.add(password); + // 生日 + params.add(Util.null2DefaultStr(userInfo.getBirthDate(), "")); + // 身份证号码 + params.add(Util.null2DefaultStr(userInfo.getIdCardNo(), "")); + // 邮箱 + params.add(Util.null2DefaultStr(userInfo.getEmail(), "")); + // 手机号 + params.add(Util.null2DefaultStr(userInfo.getMobile(), "")); + // 用户out key + params.add(Util.null2DefaultStr(userInfo.getId(),"")); + // oaId + params.add(nextHrmId); + return params; + } + + @Override + public ConsumeConcurrentlyStatus cusPassWordAction(MQMessage message) { return null; } } diff --git a/src/main/java/weaver/xuanran/wang/shyl/mq/util/RocketUtil.java b/src/main/java/weaver/xuanran/wang/shyl/mq/util/RocketUtil.java index a3af6cc..a168ece 100644 --- a/src/main/java/weaver/xuanran/wang/shyl/mq/util/RocketUtil.java +++ b/src/main/java/weaver/xuanran/wang/shyl/mq/util/RocketUtil.java @@ -71,23 +71,36 @@ public class RocketUtil { MQMessage mqMessage = null; try { msgBody = new String(messageExt.getBody(), StandardCharsets.UTF_8); + if(StringUtils.isBlank(msgBody)){ + throw new CustomerException("MQ msgBody is empty!"); + } mqMessage = JSONObject.parseObject(msgBody, MQMessage.class); + // 业务主体 + String content = Util.null2DefaultStr(mqMessage.getContent(),""); + if(StringUtils.isBlank(content)){ + throw new CustomerException(Util.logStr("the messageId : {}, content is empty!", Util.null2DefaultStr(mqMessage.getId(), ""))); + } + log.info(Util.logStr("MQMessage : {} ", mqMessage)); + // 业务类型 + String actionType = mqMessage.getActionType(); + switch (actionType){ + case RocketMQConstant.CREATE_ACTION:{ + return cusInfoActionService.cusCreateAction(mqMessage); + } + case RocketMQConstant.UPDATE_ACTION:{ + return cusInfoActionService.cusUpdateAction(mqMessage); + } + case RocketMQConstant.DELETE_ACTION:{ + return cusInfoActionService.cusDeleteAction(mqMessage); + } + case RocketMQConstant.PASSWORD_ACTION:{ + return cusInfoActionService.cusPassWordAction(mqMessage); + } + default: throw new CustomerException(Util.logStr("current actionType : [{}] is not supported!", actionType)); + } }catch (Exception e){ throw new CustomerException(Util.logStr("parse msgBody to Message error current msgBody is {}, the error is {}", msg, e.getMessage())); } - String actionType = mqMessage.getActionType(); - switch (actionType){ - case RocketMQConstant.CREATE_ACTION:{ - return cusInfoActionService.cusCreateAction(mqMessage); - } - case RocketMQConstant.UPDATE_ACTION:{ - return cusInfoActionService.cusUpdateAction(mqMessage); - } - case RocketMQConstant.DELETE_ACTION:{ - return cusInfoActionService.cusDeleteAction(mqMessage); - } - default: throw new CustomerException(Util.logStr("current actionType : [{}] is not supported!", actionType)); - } }else { log.error("the msgList is empty!"); } diff --git a/src/test/resources/ application.properties b/src/test/resources/ application.properties new file mode 100644 index 0000000..e69de29 From 4823cfe1a89434db5dcd2a34fd310a245c797f4c Mon Sep 17 00:00:00 2001 From: "weilin.zhu" Date: Thu, 5 Jan 2023 12:13:32 +0800 Subject: [PATCH 30/33] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E8=AF=B7=E6=B1=82form?= =?UTF-8?q?=E8=A1=A8=E5=8D=95=E6=8F=90=E4=BA=A4=E6=97=B6=EF=BC=8C=E5=8F=82?= =?UTF-8?q?=E6=95=B0=E5=80=BC=E8=A2=AB=E5=8F=8C=E5=BC=95=E5=8F=B7=E6=8B=AC?= =?UTF-8?q?=E4=BA=86=E8=B5=B7=E6=9D=A5=E7=9A=84BUG?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 开发文档.md | 1 + 快速入门开发.md | 90 ++++++++++++++++++++++++++++++++++++++----------- 2 files changed, 72 insertions(+), 19 deletions(-) diff --git a/开发文档.md b/开发文档.md index e73dc47..0b85264 100644 --- a/开发文档.md +++ b/开发文档.md @@ -34,5 +34,6 @@ + [建模开发文档](https://e-cloudstore.com/doc.html?appId=e783a1d75a784d9b97fbd40fdf569f7d) + [支持ecode复写的组件版本信息整理](https://e-cloudstore.com/doc.html?appId=f353923a8d2d42948235e7bbbd5f8912) + [ecode常见问题](https://e-cloudstore.com/doc.html?appId=25fb364617c44ca3aa007581db3e4269) ++ [ecode权限说明](https://e-cloudstore.com/doc.html?appId=e6f85c66d5514aa2aa9242a0cea303d7) + [前端开发规范](https://e-cloudstore.com/doc.html?appId=36f4cc525d7444ee9291e6dfaeb0a632) + [e9组件库](https://cloudstore.e-cology.cn/#/pc/doc/common-index) \ No newline at end of file diff --git a/快速入门开发.md b/快速入门开发.md index 9bf7848..3dff54b 100644 --- a/快速入门开发.md +++ b/快速入门开发.md @@ -46,14 +46,14 @@ public interface Action { ``` -常量 | 值 | 说明 ----|---|--- -SUCCESS | "1" | 成功标识,继续流程提交或执行下一个附加操作 -FAILURE_AND_CONTINUE | "0" | 失败标识,阻断流程提交 +| 常量 | 值 | 说明 | +|----------------------|-----|-----------------------| +| SUCCESS | "1" | 成功标识,继续流程提交或执行下一个附加操作 | +| FAILURE_AND_CONTINUE | "0" | 失败标识,阻断流程提交 | -方法 | 说明 ----|--- -String execute(RequestInfo request); | action实现逻辑,执行时调用此方法 +| 方法 | 说明 | +|--------------------------------------|---------------------| +| String execute(RequestInfo request); | action实现逻辑,执行时调用此方法 | 实现示例 @@ -148,7 +148,7 @@ public String execute(RequestInfo info){ int formid=RequestManager.getFormid(); //是否为单据 int isbill=RequestManager.getIsbill(); - //获取数据库主表名 + //获取数据库主表名 (低版本中 该值有可能获取到的值为空) String tableName=isbill==1?"workflow_form":RequestManager.getBillTableName(); return Action.SUCCESS; } @@ -236,7 +236,7 @@ public class SQLExecuteActionDemo implements Action { rs.executeQuery("select amount from formtable_main_16 where requestid = ?",requestId); //获取金额字段的值 if(rs.next()){ - amount=rs.getFloat(1); + amount=rs.getFloat(1); } /*************2.直接查询数据库获取表单值***************/ @@ -244,20 +244,20 @@ public class SQLExecuteActionDemo implements Action { Map mainDatas=new HashMap<>(); Property[]properties=request.getMainTableInfo().getProperty(); for(Property propertie:properties){ - mainDatas.put(propertie.getName(),propertie.getValue()); + mainDatas.put(propertie.getName(),propertie.getValue()); } amount=Util.getFloatValue(Util.null2String(mainDatas.get("amount"))); //金额字段值大于10000,阻断流程提交 if(amount>10000){ - RequestManager requestManager=request.getRequestManager(); - requestManager.setMessagecontent("不允许提交金额大于10000的流程"); - return FAILURE_AND_CONTINUE; + RequestManager requestManager=request.getRequestManager(); + requestManager.setMessagecontent("不允许提交金额大于10000的流程"); + return FAILURE_AND_CONTINUE; } return SUCCESS; - } +} ``` 4、强制收回触发action回滚 @@ -270,12 +270,12 @@ public String execute(RequestInfo request){ //对应节点强制收回,则回滚数据 if(request.getRequestManager().getNodeid()==123){ - RecordSet rs=new RecordSet(); - rs.executeUpdate("delete from uf_fix_log where requestid = ?",requestId); + RecordSet rs=new RecordSet(); + rs.executeUpdate("delete from uf_fix_log where requestid = ?",requestId); } return SUCCESS; - } +} ``` @@ -438,14 +438,66 @@ public class OperatorActionTest implements OperatorAction { 7、流程提交失败,调用action回滚逻辑(E9+2006KB支持) 8、节点附加操作执行失败问题的简单排查 +> 查看日志文件 /ecology/log/integration/integration_流程提交日期.log 文件中根据requestid进行搜索,会有详细的接口后附加操作的相关日志。 ### 第一个定时任务 -> 维护人员: +> 维护人员:weilin.zhu +> 必须继承weaver.interfaces.schedule.BaseCronJob类,实现execute() 方法。 + +``` java +import weaver.interfaces.schedule.BaseCronJob; + +/** + *

第一个计划任务

+ */ +public class FirstTask extends BaseCronJob { + + /** + * 自定义参数 (必须有getter、setter方法)否则无法取到配置值 + */ + private String cusParam = ""; + + /** + * 重写父类方法 + */ + @Override + public void execute() { + //具体的业务逻辑 + } + + public String getCusParam() { + return cusParam; + } + + public void setCusParam(String cusParam) { + this.cusParam = cusParam; + } +} + +``` ### 第一个restful接口 -> 维护人员: +> 维护人员:weilin.zhu + +> 1、API接口必须写在 com.api /om.cloudstore 文件夹下,这样才能被扫描到。若系统有统一待办的非标功能,放在weaver.rest目录下也是可以的。 +> +> 2、但是这里我们这边要求大家放到 com.api 目录下,我们编写的接口,请求地址前面默认会加上/api。例:@Path("/getUserInfo"),请求地址应为/api/getUserInfo +> +> 3、若编写的api供外部系统调用,必须将api的请求地址放在配置文件的白名单中,否则异构系统无法直接调用。 + +> 关于API白名单说明: +> +> 配置文件:ecology/WEB-INF/prop/weaver_session_filter.properties +> +> 配置说明:在unchecksessionurl=后面添加自定义接口请求地址 + + +> 示例代码: +```java + +``` ### 如何操作数据库 From 4bbe6a2df8628226524618046118b72f09e5ec8c Mon Sep 17 00:00:00 2001 From: "weilin.zhu" Date: Thu, 5 Jan 2023 12:14:38 +0800 Subject: [PATCH 31/33] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E8=AF=B7=E6=B1=82form?= =?UTF-8?q?=E8=A1=A8=E5=8D=95=E6=8F=90=E4=BA=A4=E6=97=B6=EF=BC=8C=E5=8F=82?= =?UTF-8?q?=E6=95=B0=E5=80=BC=E8=A2=AB=E5=8F=8C=E5=BC=95=E5=8F=B7=E6=8B=AC?= =?UTF-8?q?=E4=BA=86=E8=B5=B7=E6=9D=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../aiyh/utils/httpUtil/util/HttpUtils.java | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/src/main/java/aiyh/utils/httpUtil/util/HttpUtils.java b/src/main/java/aiyh/utils/httpUtil/util/HttpUtils.java index bf4d92b..6967ec7 100644 --- a/src/main/java/aiyh/utils/httpUtil/util/HttpUtils.java +++ b/src/main/java/aiyh/utils/httpUtil/util/HttpUtils.java @@ -1003,14 +1003,20 @@ public class HttpUtils { if (Strings.isNullOrEmpty(contentType)) { List nvps = new ArrayList<>(); for (Map.Entry entry : params.entrySet()) { - nvps.add(new BasicNameValuePair(entry.getKey(), JSON.toJSONString(entry.getValue()))); + //nvps.add(new BasicNameValuePair(entry.getKey(), JSON.toJSONString(entry.getValue()))); + + //修复请求form表单提交时,参数值被双引号括了起来 + nvps.add(new BasicNameValuePair(entry.getKey(), Util.null2String(entry.getValue()))); } httpPost.setHeader("Content-Type", HttpArgsType.DEFAULT_CONTENT_TYPE); httpPost.setEntity(new UrlEncodedFormEntity(nvps)); } else if (contentType.toUpperCase().startsWith(HttpArgsType.X_WWW_FORM_URLENCODED.toUpperCase())) { List nvps = new ArrayList<>(); for (Map.Entry entry : params.entrySet()) { - nvps.add(new BasicNameValuePair(entry.getKey(), JSON.toJSONString(entry.getValue()))); + //nvps.add(new BasicNameValuePair(entry.getKey(), JSON.toJSONString(entry.getValue()))); + + //修复请求form表单提交时,参数值被双引号括了起来 + nvps.add(new BasicNameValuePair(entry.getKey(), Util.null2String(entry.getValue()))); } httpPost.setEntity(new UrlEncodedFormEntity(nvps)); // } else if (contentType.toUpperCase().startsWith(HttpArgsType.APPLICATION_JSON.toUpperCase())) { @@ -1187,14 +1193,18 @@ public class HttpUtils { if (Strings.isNullOrEmpty(contentType)) { List nvps = new ArrayList<>(); for (Map.Entry entry : paramsMap.entrySet()) { - nvps.add(new BasicNameValuePair(entry.getKey(), JSON.toJSONString(entry.getValue()))); + //nvps.add(new BasicNameValuePair(entry.getKey(), JSON.toJSONString(entry.getValue()))); + //修复请求form表单提交时,参数值被双引号括了起来 + nvps.add(new BasicNameValuePair(entry.getKey(), Util.null2String(entry.getValue()))); } httpPut.setHeader("Content-Type", HttpArgsType.DEFAULT_CONTENT_TYPE); httpPut.setEntity(new UrlEncodedFormEntity(nvps)); } else if (contentType.toUpperCase().startsWith(HttpArgsType.X_WWW_FORM_URLENCODED.toUpperCase())) { List nvps = new ArrayList<>(); for (Map.Entry entry : paramsMap.entrySet()) { - nvps.add(new BasicNameValuePair(entry.getKey(), JSON.toJSONString(entry.getValue()))); + //nvps.add(new BasicNameValuePair(entry.getKey(), JSON.toJSONString(entry.getValue()))); + //修复请求form表单提交时,参数值被双引号括了起来 + nvps.add(new BasicNameValuePair(entry.getKey(), Util.null2String(entry.getValue()))); } httpPut.setEntity(new UrlEncodedFormEntity(nvps)); } else if (contentType.toUpperCase().startsWith(HttpArgsType.APPLICATION_JSON.toUpperCase())) { From 557afeaa25b842e4e0e09fbf15cb27ab19c33629 Mon Sep 17 00:00:00 2001 From: "xuanran.wang" <3055088966@qq.com> Date: Thu, 12 Jan 2023 16:47:02 +0800 Subject: [PATCH 32/33] =?UTF-8?q?2023-01-12=20=E6=96=BD=E7=BD=97=E5=BE=B7?= =?UTF-8?q?=E4=BB=A3=E7=A0=81=E6=B5=8B=E8=AF=95=E6=8F=90=E4=BA=A4=E4=B8=8E?= =?UTF-8?q?mq=E9=83=A8=E5=88=86=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controller/CheckUserController.java | 19 +--- .../checkuser/service/CheckUserService.java | 3 +- .../controller/DownLoadFileController.java | 7 ++ .../mapper/DownLoadFileMapper.java | 33 ------- .../service/DownLoadFileService.java | 29 +++--- .../xuanran/wang/common/util/CommonUtil.java | 18 ++++ .../schroeder/action/PushSealTaskAction.java | 14 +-- .../action/SalesforceEndpointAction.java | 20 ++-- .../PushSealTaskSealValue.java | 96 ++++++++++++++++++- .../schroeder/mapper/SchroederMapper.java | 8 +- .../service/SchroederQRCodeService.java | 54 +++++++++-- ...ner.java => RocketMQConsumerListener.java} | 7 +- .../xuanran/wang/shyl/mq/RocketMQFactory.java | 78 ++++++++++++++- .../wang/shyl/mq/action/ProducerAction.java | 31 ++++++ .../shyl/mq/constant/RocketMQConstant.java | 1 + .../wang/shyl/mq/consumer/OrgConsumer.java | 8 +- .../shyl/mq/consumer/PassWordConsumer.java | 8 +- .../shyl/mq/consumer/UserInfoConsumer.java | 4 +- .../wang/shyl/mq/service/ProducerService.java | 42 ++++++++ .../shyl/mq/service/impl/OrgServiceImpl.java | 18 +++- .../xuanran/wang/shyl/mq/util/RocketUtil.java | 49 +++++++++- .../download_file/DownLoadFileTest.java | 14 --- 22 files changed, 423 insertions(+), 138 deletions(-) delete mode 100644 src/main/java/com/api/xuanran/wang/schroeder/download_file/mapper/DownLoadFileMapper.java rename src/main/java/weaver/xuanran/wang/shyl/mq/{RocketMQListener.java => RocketMQConsumerListener.java} (92%) create mode 100644 src/main/java/weaver/xuanran/wang/shyl/mq/action/ProducerAction.java create mode 100644 src/main/java/weaver/xuanran/wang/shyl/mq/service/ProducerService.java diff --git a/src/main/java/com/api/xuanran/wang/ambofo/checkuser/controller/CheckUserController.java b/src/main/java/com/api/xuanran/wang/ambofo/checkuser/controller/CheckUserController.java index 5adc100..d33caa7 100644 --- a/src/main/java/com/api/xuanran/wang/ambofo/checkuser/controller/CheckUserController.java +++ b/src/main/java/com/api/xuanran/wang/ambofo/checkuser/controller/CheckUserController.java @@ -32,23 +32,8 @@ public class CheckUserController { String checkContent = request.getParameter("checkContent"); try { CheckUserService checkUserService = new CheckUserService(); - return ApiResult.success(checkUserService.checkADHasUser(checkContent),"ok"); - }catch (Exception e){ - String error = Util.logStr("AD查询接口发生异常:{}", e.getMessage()); - log.error(error); - log.error(Util.getErrString(e)); - return ApiResult.error(500, error); - } - } - - @Path("logUser") - @GET - @Produces(MediaType.TEXT_PLAIN) - public String logUser(@Context HttpServletRequest request, @Context HttpServletResponse response) { - try { - CheckUserService checkUserService = new CheckUserService(); - checkUserService.logAllUser(); - return ApiResult.successNoData(); + boolean has = checkUserService.checkADHasUser(checkContent); + return ApiResult.success(has,"ok"); }catch (Exception e){ String error = Util.logStr("AD查询接口发生异常:{}", e.getMessage()); log.error(error); diff --git a/src/main/java/com/api/xuanran/wang/ambofo/checkuser/service/CheckUserService.java b/src/main/java/com/api/xuanran/wang/ambofo/checkuser/service/CheckUserService.java index e2b72c2..1ced546 100644 --- a/src/main/java/com/api/xuanran/wang/ambofo/checkuser/service/CheckUserService.java +++ b/src/main/java/com/api/xuanran/wang/ambofo/checkuser/service/CheckUserService.java @@ -65,7 +65,8 @@ public class CheckUserService { // 根据设置的域节点、过滤器类和搜索控制器搜索LDAP得到结果 NamingEnumeration answer = ldapContext.search(searchBase, searchFilter, searchControl); boolean has = answer.hasMoreElements(); - while (answer.hasMoreElements()) { + log.info("has " + has); + if(has){ SearchResult sr = (SearchResult) answer.next(); String dn = sr.getName(); log.info("dn " + dn); diff --git a/src/main/java/com/api/xuanran/wang/schroeder/download_file/controller/DownLoadFileController.java b/src/main/java/com/api/xuanran/wang/schroeder/download_file/controller/DownLoadFileController.java index 1d09cfc..bd06044 100644 --- a/src/main/java/com/api/xuanran/wang/schroeder/download_file/controller/DownLoadFileController.java +++ b/src/main/java/com/api/xuanran/wang/schroeder/download_file/controller/DownLoadFileController.java @@ -1,9 +1,13 @@ package com.api.xuanran.wang.schroeder.download_file.controller; import aiyh.utils.Util; +import aiyh.utils.excention.CustomerException; +import com.alibaba.fastjson.JSONObject; import com.api.xuanran.wang.schroeder.download_file.service.DownLoadFileService; import org.apache.commons.io.IOUtils; +import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; +import weaver.docs.docs.DocInfo; import weaver.file.ImageFileManager; import javax.servlet.http.HttpServletRequest; @@ -43,6 +47,9 @@ public class DownLoadFileController { Map fileInfo = downLoadFileService.getFileInfo(docId); String fileName = Util.null2String(fileInfo.get("fileName")); int imageFileId = Util.getIntValue(Util.null2DefaultStr(fileInfo.get("imageFileId"),""), -1); + if(StringUtils.isBlank(fileName) || imageFileId < 0){ + throw new CustomerException(Util.logStr("文件信息部分字段查询为空!当前查询结果map:[{}]", JSONObject.toJSONString(fileInfo))); + } InputStream is = ImageFileManager.getInputStreamById(imageFileId); byte[] bytes = IOUtils.toByteArray(is); StreamingOutput output = outputStream ->{ diff --git a/src/main/java/com/api/xuanran/wang/schroeder/download_file/mapper/DownLoadFileMapper.java b/src/main/java/com/api/xuanran/wang/schroeder/download_file/mapper/DownLoadFileMapper.java deleted file mode 100644 index 6223c91..0000000 --- a/src/main/java/com/api/xuanran/wang/schroeder/download_file/mapper/DownLoadFileMapper.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.api.xuanran.wang.schroeder.download_file.mapper; - -import aiyh.utils.annotation.recordset.ParamMapper; -import aiyh.utils.annotation.recordset.Select; -import aiyh.utils.annotation.recordset.SqlMapper; - -import java.util.Map; - -/** - *

文件下载mapper

- * - * @Author xuanran.wang - * @Date 2022/12/7 10:58 - */ -@SqlMapper -public interface DownLoadFileMapper { - - /** - *

根据docId查询附件信息

- * @author xuanran.wang - * @dateTime 2022/12/7 11:01 - * @param docId docId - * @return 文件imageField以及文件名 - **/ - @Select("select t3.imagefileid imageFileId,t3.imagefilename fileName,t3.filerealpath filePath " + - "from DocDetail t1 " + - "left join DocImageFile t2 " + - "on t2.docid = t1.id " + - "left join ImageFile t3 " + - "on t3.imagefileid = t2.imagefileid " + - "where t1.id = #{docId}") - Map selectDocInfoByDocId(@ParamMapper("docId") String docId); -} diff --git a/src/main/java/com/api/xuanran/wang/schroeder/download_file/service/DownLoadFileService.java b/src/main/java/com/api/xuanran/wang/schroeder/download_file/service/DownLoadFileService.java index 49f5ef6..9e83c02 100644 --- a/src/main/java/com/api/xuanran/wang/schroeder/download_file/service/DownLoadFileService.java +++ b/src/main/java/com/api/xuanran/wang/schroeder/download_file/service/DownLoadFileService.java @@ -2,11 +2,11 @@ package com.api.xuanran.wang.schroeder.download_file.service; import aiyh.utils.Util; import aiyh.utils.excention.CustomerException; -import com.alibaba.fastjson.JSONObject; -import com.api.xuanran.wang.schroeder.download_file.mapper.DownLoadFileMapper; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.StringUtils; import weaver.conn.RecordSet; + +import java.util.HashMap; import java.util.Map; /** @@ -24,7 +24,6 @@ public class DownLoadFileService { *

查询文件记录sql

**/ private static final String SELECT_DOC_LOG_SQL = "select 1 from " + DOC_LOG_TABLE_NAME + " where docId = ? and enable = 0"; - private final DownLoadFileMapper downLoadFileMapper = Util.getMapper(DownLoadFileMapper.class); /** *

根据docId获取文件信息

@@ -33,23 +32,29 @@ public class DownLoadFileService { * @param docId docId **/ public Map getFileInfo(String docId) { + RecordSet rs = new RecordSet(); if(StringUtils.isBlank(docId)) { throw new CustomerException(Util.logStr("下载文件失败, 请求路径中不包含指定的docId!当前请求docId:{}", docId)); } - RecordSet rs = new RecordSet(); if (!rs.executeQuery(SELECT_DOC_LOG_SQL, docId) || !rs.next()) { throw new CustomerException("下载文件失败, 请确认文件记录表中是否存在docId = [ " + docId + " ]的文件!"); } - Map fileInfoMap = downLoadFileMapper.selectDocInfoByDocId(docId); - if(MapUtils.isEmpty(fileInfoMap)){ - throw new CustomerException("执行查询文件信息sql失败!"); + String sql = " select t3.imagefileid imageFileId,t3.imagefilename fileName " + + " from DocDetail t1 " + + " left join DocImageFile t2 " + + " on t2.docid = t1.id " + + " left join ImageFile t3 " + + " on t3.imagefileid = t2.imagefileid " + + " where t1.id = ?"; + HashMap res = new HashMap<>(); + if (rs.executeQuery(sql, docId) && rs.next()) { + res.put("imageFileId", rs.getString("imageFileId")); + res.put("fileName", rs.getString("fileName")); } - String fileName = Util.null2DefaultStr(fileInfoMap.get("fileName"),""); - int imageFileId = Util.getIntValue(Util.null2DefaultStr(fileInfoMap.get("imageFileId"),""), -1); - if(StringUtils.isBlank(fileName) ||imageFileId < 0){ - throw new CustomerException(Util.logStr("文件信息部分字段查询为空!当前查询结果map:[{}]", JSONObject.toJSONString(fileInfoMap))); + if(MapUtils.isEmpty(res)){ + throw new CustomerException(Util.logStr("执行查询文件信息sql失败! 当前sql : {}", sql)); } - return fileInfoMap; + return res; } diff --git a/src/main/java/weaver/xuanran/wang/common/util/CommonUtil.java b/src/main/java/weaver/xuanran/wang/common/util/CommonUtil.java index 0a037d3..ef493ae 100644 --- a/src/main/java/weaver/xuanran/wang/common/util/CommonUtil.java +++ b/src/main/java/weaver/xuanran/wang/common/util/CommonUtil.java @@ -12,6 +12,8 @@ import org.apache.log4j.Logger; import weaver.conn.RecordSet; import weaver.formmode.data.ModeDataApproval; import weaver.hrm.User; +import weaver.xiao.commons.config.entity.RequestMappingConfig; +import weaver.xiao.commons.config.service.DealWithMapping; import weaver.xuanran.wang.common.annocation.CusDateFormat; import weaver.xuanran.wang.common.annocation.ParamNotNull; import weaver.xuanran.wang.common.mapper.CommonMapper; @@ -594,6 +596,22 @@ public class CommonUtil { return commonMapper.getModelNameByModelId(String.valueOf(modelId)); } + /** + *

将建模配置表中的自定义数据条件进行拼接

+ * @author xuanran.wang + * @dateTime 2023/1/4 15:10 + * @param requestMappingConfig 建模配置对象 + * @param tableName 表名 + * @return 添加建模配置表自定义数据条件只会的sql + **/ + public static String getSelectSql( RequestMappingConfig requestMappingConfig, String tableName){ + String cusWhere = Util.null2DefaultStr(requestMappingConfig.getCusWhereSql(), ""); + if (StringUtils.isNotBlank(cusWhere)) { + cusWhere = " and " + DealWithMapping.sbc2dbcCase(cusWhere); // 全角转半角 + } + return "select * from " + tableName + " where requestid = ? " + cusWhere; + } + } diff --git a/src/main/java/weaver/xuanran/wang/schroeder/action/PushSealTaskAction.java b/src/main/java/weaver/xuanran/wang/schroeder/action/PushSealTaskAction.java index ca81f9e..4464b7b 100644 --- a/src/main/java/weaver/xuanran/wang/schroeder/action/PushSealTaskAction.java +++ b/src/main/java/weaver/xuanran/wang/schroeder/action/PushSealTaskAction.java @@ -4,6 +4,8 @@ import aiyh.utils.Util; import aiyh.utils.action.SafeCusBaseAction; import aiyh.utils.annotation.RequiredMark; import aiyh.utils.excention.CustomerException; // 自定义异常类 create 2022/3/9 2:20 PM +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.JSONPObject; import org.apache.commons.lang3.StringUtils; import weaver.conn.RecordSet; import weaver.conn.RecordSetTrans; @@ -119,20 +121,18 @@ public class PushSealTaskAction extends SafeCusBaseAction { // 基础的action delSql = "delete from " + detailTable + " where mainid = ? "; } try{ - // 获取明细表数据 - List> detailList = schroederQRCodeService.getDetailList(detailTable, mainId); - List docIds = detailList.stream() - .map(item -> Util.null2DefaultStr(item.get(fileField), "")) - .filter(StringUtils::isNotBlank).collect(Collectors.toList()); + List detailFileId = schroederQRCodeService.getDetailFileId(fileField, detailTable, mainId); + log.info(Util.logStr("明细docId集合 : {}", JSONObject.toJSONString(detailFileId))); List> docLogParamList = new ArrayList<>(); - for (String docId : docIds) { + for (String docId : detailFileId) { LinkedHashMap map = new LinkedHashMap<>(); map.put("docId", docId); map.put("enable", 0); docLogParamList.add(map); } + log.info(Util.logStr("docLogParamList集合 : {}", JSONObject.toJSONString(docLogParamList))); // 将docLog数据写入建模 - docLogModelIdList = CusInfoToOAUtil.executeBatch(Util.getIntValue(docLogModelId, -1), docLogParamList, "select id from #{tableName} where docId = ?", docIds); + docLogModelIdList = CusInfoToOAUtil.executeBatch(Util.getIntValue(docLogModelId, -1), docLogParamList); // requestLog写入建模 LinkedHashMap map = new LinkedHashMap<>(); int count = schroederQRCodeService.getTaskIdByRequestId(requestId); diff --git a/src/main/java/weaver/xuanran/wang/schroeder/action/SalesforceEndpointAction.java b/src/main/java/weaver/xuanran/wang/schroeder/action/SalesforceEndpointAction.java index 2bc8c97..ada21ba 100644 --- a/src/main/java/weaver/xuanran/wang/schroeder/action/SalesforceEndpointAction.java +++ b/src/main/java/weaver/xuanran/wang/schroeder/action/SalesforceEndpointAction.java @@ -1,10 +1,7 @@ package weaver.xuanran.wang.schroeder.action; import aiyh.utils.Util; -import aiyh.utils.action.SafeCusBaseAction; -import aiyh.utils.annotation.RequiredMark; -import aiyh.utils.excention.CustomerException; -import weaver.hrm.User; +import weaver.interfaces.workflow.action.Action; import weaver.soa.workflow.request.RequestInfo; import weaver.xuanran.wang.schroeder.service.SchroederQRCodeService; @@ -14,32 +11,35 @@ import weaver.xuanran.wang.schroeder.service.SchroederQRCodeService; * @Author xuanran.wang * @Date 2022/12/23 10:49 */ -public class SalesforceEndpointAction extends SafeCusBaseAction { +public class SalesforceEndpointAction implements Action { /** *

建模配置唯一标识

**/ - @RequiredMark private String onlyMark; /** *

响应成功状态码

**/ - @RequiredMark private String successCode; /** *

请求方式

**/ - @RequiredMark private String type; private final SchroederQRCodeService schroederQRCodeService = new SchroederQRCodeService(); + @Override - public void doSubmit(String requestId, String billTable, int workflowId, User user, RequestInfo requestInfo) { + public String execute(RequestInfo requestInfo) { try { + String billTable = requestInfo.getRequestManager().getBillTableName(); + String requestId = requestInfo.getRequestid(); schroederQRCodeService.pushSealTask(onlyMark, billTable, requestId,type, successCode,"",""); + return Action.SUCCESS; }catch (Exception e){ - throw new CustomerException(Util.logStr("执行提交方法异常:{}", e.getMessage())); // + requestInfo.getRequestManager().setMessageid(String.valueOf(System.currentTimeMillis())); + requestInfo.getRequestManager().setMessagecontent(Util.logStr("执行提交方法异常:{}", e.getMessage())); + return Action.FAILURE_AND_CONTINUE; } } } diff --git a/src/main/java/weaver/xuanran/wang/schroeder/cus_field_value/PushSealTaskSealValue.java b/src/main/java/weaver/xuanran/wang/schroeder/cus_field_value/PushSealTaskSealValue.java index eb4605c..83c29da 100644 --- a/src/main/java/weaver/xuanran/wang/schroeder/cus_field_value/PushSealTaskSealValue.java +++ b/src/main/java/weaver/xuanran/wang/schroeder/cus_field_value/PushSealTaskSealValue.java @@ -6,12 +6,12 @@ import com.alibaba.fastjson.JSONObject; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; +import weaver.conn.ConnStatementDataSource; import weaver.conn.RecordSet; import weaver.xiao.commons.config.interfacies.CusInterfaceGetValue; // 自定义获取参数值 -import weaver.zwl.common.ToolUtil; // 常用工具方法-公用类 +import java.sql.SQLException; import java.util.*; -import java.util.stream.Collectors; /** *

@@ -20,7 +20,6 @@ import java.util.stream.Collectors; * @Date 2022/12/2 16:10 */ public class PushSealTaskSealValue implements CusInterfaceGetValue { // 自定义获取参数值 - private final ToolUtil toolUtil = new ToolUtil(); // 常用工具方法-公用类 构造方法 private final Logger logger = Util.getLogger(); // 获取日志对象 @@ -46,11 +45,19 @@ public class PushSealTaskSealValue implements CusInterfaceGetValue { // 自定 int detailId = -1; if(MapUtils.isNotEmpty(detailMap)){ detailId = Util.getIntValue(String.valueOf(detailMap.get("id")), -1); + if(detailId < 0){ + detailId = Util.getIntValue(String.valueOf(detailMap.get("ID")), -1); + } } + String requestId = String.valueOf(mainMap.get("requestid")); + if(StringUtils.isBlank(requestId)){ + requestId = String.valueOf(mainMap.get("REQUESTID")); + } + logger.info(Util.logStr("requestId : {}, detailId : {}", requestId, detailId)); for (String val : currentValue.split(",")) { // 印章类型转换执行自定义sql - String inSealVal = Util.null2DefaultStr(toolUtil.getValueByChangeRule(sealSnCusSql, val, String.valueOf(mainMap.get("requestid")), detailId),""); // 用数据库值,根据规则转换,获取其最终结果 - String inSealNumVal = Util.null2DefaultStr(toolUtil.getValueByChangeRule(sealNumCusSql, val, String.valueOf(mainMap.get("requestid")), detailId),""); // 用数据库值,根据规则转换,获取其最终结果 + String inSealVal = Util.null2DefaultStr(getValueByChangeRule(sealSnCusSql, val, requestId, detailId,""),""); // 用数据库值,根据规则转换,获取其最终结果 + String inSealNumVal = Util.null2DefaultStr(getValueByChangeRule(sealNumCusSql, val, requestId, detailId,""),""); // 用数据库值,根据规则转换,获取其最终结果 HashMap map = new HashMap<>(); map.put(sealSnField, inSealVal); map.put(sealNumField, inSealNumVal); @@ -59,6 +66,85 @@ public class PushSealTaskSealValue implements CusInterfaceGetValue { // 自定 return list; } + /** + * 用数据库值,根据规则转换,获取其最终结果 + * @param cus_sql 自定义转换的SQL + * @param value 参数值 + * @param requestid 流程请求ID + * @param detailKeyvalue 明细表主键值 + * @pram datasourceid 外部数据源ID + * @return + */ + public String getValueByChangeRule(String cus_sql,String value,String requestid,int detailKeyvalue,String datasourceid){ + String endValue = ""; + + cus_sql = cus_sql.replace(" ", " "); + + cus_sql = cus_sql.replace("{?dt.id}", String.valueOf(detailKeyvalue)); + + //参数进行替换 + String sqlString = cus_sql.replace("{?requestid}", requestid); + + sqlString = sqlString.replace("?", value); + + sqlString = ToDBC(sqlString); + logger.info(Util.logStr("查询sql : {} ", sqlString)); + try { + if(datasourceid != null && !"".equals(datasourceid)){ + ConnStatementDataSource csds = new ConnStatementDataSource(datasourceid); + + csds.setStatementSql(sqlString); + + csds.executeQuery(); + + if(csds.next()){ + endValue = weaver.general.Util.null2String(csds.getString(1)); + } + + csds.close(); + }else{ + + RecordSet rs = new RecordSet(); + if(rs.executeQuery(sqlString)){ + if (rs.next()) { + endValue = weaver.general.Util.null2String(rs.getString(1)); + logger.info(Util.logStr("执行自定义sql 返回结果 : {}", endValue)); + }else { + logger.error("当前查询没有查询结果!"); + } + }else { + logger.error("当前sql查询失败!"); + } + } + } catch (SQLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + return endValue; + } + + /** + * 全角转半角 + * @param input + * @return + */ + public String ToDBC(String input) { + char c[] = input.toCharArray(); + for (int i = 0; i < c.length; i++) { + if (c[i] == '\u3000') { + c[i] = ' '; + } else if (c[i] > '\uFF00' && c[i] < '\uFF5F') { + c[i] = (char) (c[i] - 65248); + } + } + String returnString = new String(c); + return returnString; + } + public boolean checkBlank(String ... args){ return Arrays.stream(args).anyMatch(StringUtils::isBlank); } diff --git a/src/main/java/weaver/xuanran/wang/schroeder/mapper/SchroederMapper.java b/src/main/java/weaver/xuanran/wang/schroeder/mapper/SchroederMapper.java index 9e53859..8fda5f3 100644 --- a/src/main/java/weaver/xuanran/wang/schroeder/mapper/SchroederMapper.java +++ b/src/main/java/weaver/xuanran/wang/schroeder/mapper/SchroederMapper.java @@ -39,9 +39,9 @@ public interface SchroederMapper { * @return 明细表数据集合 **/ @Select("select $t{fileField} from $t{tableName} where mainid = #{mainId}") - List> selectSealFileList(@ParamMapper("fileField") String fileField, - @ParamMapper("tableName") String tableName, - @ParamMapper("mainId") String mainId); + List selectSealFileList(@ParamMapper("fileField") String fileField, + @ParamMapper("tableName") String tableName, + @ParamMapper("mainId") String mainId); /** *

得到任务Id

* @author xuanran.wang @@ -56,6 +56,6 @@ public interface SchroederMapper { Integer selectTaskId(@ParamMapper("cusRequestId") String cusRequestId); @Select("select * from $t{tableName} where mainid = #{mainId}") - List> detailList(@ParamMapper("tableName") String tableName, + List> detailList(@ParamMapper("tableName") String tableName, @ParamMapper("mainId") String mainId); } diff --git a/src/main/java/weaver/xuanran/wang/schroeder/service/SchroederQRCodeService.java b/src/main/java/weaver/xuanran/wang/schroeder/service/SchroederQRCodeService.java index 8d1f67a..79cf853 100644 --- a/src/main/java/weaver/xuanran/wang/schroeder/service/SchroederQRCodeService.java +++ b/src/main/java/weaver/xuanran/wang/schroeder/service/SchroederQRCodeService.java @@ -5,6 +5,7 @@ import aiyh.utils.excention.CustomerException; // 自定义异常类 create 20 import aiyh.utils.httpUtil.ResponeVo; import aiyh.utils.httpUtil.util.HttpUtils; import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; import com.fasterxml.jackson.core.JsonProcessingException; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; @@ -188,22 +189,31 @@ public class SchroederQRCodeService { **/ public void changeRequestMap(Map requestParam, String billTable, String mainId, String filePeopleType) { List> files = (List>) requestParam.get("file"); - List> detail1List = schroederMapper.selectSealTaskInfoList(billTable, mainId); - if (CollectionUtils.isEmpty(detail1List) || CollectionUtils.isEmpty(files)) { + if (CollectionUtils.isEmpty(files)) { return; } - // 遍历明细数据 - for (Map detailItem : detail1List) { + RecordSet detailRs = new RecordSet(); + String sql = "select yywj,qfzzl,qfzcs from " + billTable + " where mainid = ? and sfjgqfz = 0"; + if(!detailRs.executeQuery(sql, mainId)){ + throw new CustomerException(Util.logStr("查询明细数据sql执行失败!sql : {}, mainId : {}", sql, mainId)); + } + // 貌似有bug 把mapper改成原生recordSet + while (detailRs.next()) { // 用印文件 - String sealFile = Util.null2String(detailItem.get("yywj")); + String sealFile = Util.null2String(detailRs.getString("yywj")); + if(StringUtils.isBlank(sealFile)){ + sealFile = Util.null2String(detailRs.getString("YYWJ")); + } // 从生成的请求参数map中开始匹配 + String finalSealFile = sealFile; List> filterFiles = files.stream() .filter(item -> { String filePath = Util.null2DefaultStr(item.get("fileUrlPath"), ""); String docId = Util.null2DefaultStr(filePath.substring(filePath.lastIndexOf("=") + 1), ""); - return sealFile.equals(docId); + return finalSealFile.equals(docId); }) .collect(Collectors.toList()); + log.info(Util.logStr("filterFiles : {} ", JSONObject.toJSONString(finalSealFile))); if (CollectionUtils.isNotEmpty(filterFiles)) { // 只有一个能匹配 Map o = filterFiles.get(0); @@ -211,8 +221,19 @@ public class SchroederQRCodeService { // 印章集合 List> sealList = new ArrayList<>(); HashMap seal = new HashMap<>(); - seal.put("sealSn", Util.null2DefaultStr(detailItem.get("qfzzl"), "")); - seal.put("sealNum", Util.null2DefaultStr(detailItem.get("qfzcs"), "0")); + // 骑缝章总类 + String qfzzl = Util.null2DefaultStr(detailRs.getString("qfzzl"),""); + if(StringUtils.isBlank(qfzzl)){ + qfzzl = Util.null2DefaultStr(detailRs.getString("QFZZL"),""); + } + log.info(Util.logStr("骑缝章总类 : {}", qfzzl)); + seal.put("sealSn", qfzzl); + String qfzcs = Util.null2DefaultStr(detailRs.getString("qfzcs"),""); + if(StringUtils.isBlank(qfzcs)){ + qfzcs = Util.null2DefaultStr(detailRs.getString("QFZCS"),""); + } + log.info(Util.logStr("骑缝章次数 : {}", qfzcs)); + seal.put("sealNum", Util.null2DefaultStr(qfzcs, "0")); sealList.add(seal); tempMap.put("seal", sealList); tempMap.put("filePeopleType", filePeopleType); @@ -242,10 +263,25 @@ public class SchroederQRCodeService { * @author xuanran.wang * @dateTime 2022/12/21 18:03 **/ - public List> getDetailList(String tableName, String mainId) { + public List> getDetailList(String tableName, String mainId) { return schroederMapper.detailList(tableName, mainId); } + + /** + *

获取明细1文件数据id

+ * + * @param fileField 用印文件字段名 + * @param tableName 明细表名 + * @param mainId 主id + * @return 明细表数据 + * @author xuanran.wang + * @dateTime 2022/12/21 18:03 + **/ + public List getDetailFileId(String fileField,String tableName, String mainId) { + return schroederMapper.selectSealFileList(fileField,tableName, mainId); + } + } diff --git a/src/main/java/weaver/xuanran/wang/shyl/mq/RocketMQListener.java b/src/main/java/weaver/xuanran/wang/shyl/mq/RocketMQConsumerListener.java similarity index 92% rename from src/main/java/weaver/xuanran/wang/shyl/mq/RocketMQListener.java rename to src/main/java/weaver/xuanran/wang/shyl/mq/RocketMQConsumerListener.java index b72f25c..366a1b1 100644 --- a/src/main/java/weaver/xuanran/wang/shyl/mq/RocketMQListener.java +++ b/src/main/java/weaver/xuanran/wang/shyl/mq/RocketMQConsumerListener.java @@ -8,7 +8,6 @@ import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; -import java.util.Map; /** *

上海团校RocketMQListener

@@ -16,12 +15,12 @@ import java.util.Map; * @Author xuanran.wang * @Date 2022/12/29 12:25 */ -public abstract class RocketMQListener extends HttpServlet { +public abstract class RocketMQConsumerListener extends HttpServlet { private static final Logger log = Util.getLogger(); private String configName; - public RocketMQListener() { + public RocketMQConsumerListener() { } - public RocketMQListener(String configName) { + public RocketMQConsumerListener(String configName) { this.configName = configName; } @Override diff --git a/src/main/java/weaver/xuanran/wang/shyl/mq/RocketMQFactory.java b/src/main/java/weaver/xuanran/wang/shyl/mq/RocketMQFactory.java index 1153f0f..ee9bee2 100644 --- a/src/main/java/weaver/xuanran/wang/shyl/mq/RocketMQFactory.java +++ b/src/main/java/weaver/xuanran/wang/shyl/mq/RocketMQFactory.java @@ -4,6 +4,8 @@ import aiyh.utils.Util; import aiyh.utils.excention.CustomerException; import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer; import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently; +import org.apache.rocketmq.client.exception.MQClientException; +import org.apache.rocketmq.client.producer.DefaultMQProducer; import org.apache.rocketmq.common.consumer.ConsumeFromWhere; import org.apache.rocketmq.common.protocol.heartbeat.MessageModel; import weaver.xuanran.wang.shyl.mq.constant.RocketMQConstant; @@ -11,6 +13,7 @@ import weaver.xuanran.wang.shyl.mq.util.RocketUtil; import java.util.HashMap; import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; /** *

rocketMQ工厂

@@ -19,14 +22,28 @@ import java.util.Map; * @Date 2022/12/29 14:21 */ public class RocketMQFactory { + + /** + *

配置文件本地存储对象

+ **/ public static Map> CONFIG_MAPS = new HashMap<>(16); + + /** + *

生产者map

+ **/ + private static Map PRODUCER_MAP = new ConcurrentHashMap<>(16); + + /** + *

根据配置文件生成消费者对象

+ * @author xuanran.wang + * @dateTime 2023/1/4 12:55 + * @param configName 配置文件名称 + * @param messageListenerConcurrently 消息监听处理业务方法 + * @return 消费者 + **/ public static DefaultMQPushConsumer getMQPushConsumer(String configName, MessageListenerConcurrently messageListenerConcurrently){ try { - Map configMap = new HashMap<>(); - if(!CONFIG_MAPS.containsKey(configName)){ - configMap = RocketUtil.initMQConfigMap(configName); - CONFIG_MAPS.put(configName, configMap); - } + Map configMap = getConfigMapByName(configName); // 最大重试次数 int maxReconsumeTimes = Util.getIntValue(Util.null2String(configMap.get("MaxReconsumeTimes")), RocketMQConstant.DEFAULT_MAX_RECONSUME_TIMES); // 声明一个消费者consumer,需要传入一个组 weaver-consumer @@ -49,4 +66,55 @@ public class RocketMQFactory { } } + /** + *

根据配置文件获取生产者对象

+ * @author xuanran.wang + * @dateTime 2023/1/4 12:59 + * @param configName 配置文件名称 + * @return 生产者对象 + **/ + public static DefaultMQProducer getMQProducer(String configName){ + DefaultMQProducer defaultMQProducer = null; + if(PRODUCER_MAP.containsKey(configName)){ + return PRODUCER_MAP.get(configName); + }else { + synchronized (RocketMQFactory.class){ + if(PRODUCER_MAP.containsKey(configName)){ + return PRODUCER_MAP.get(configName); + }else { + Map configMap = getConfigMapByName(configName); + defaultMQProducer = new DefaultMQProducer(); + // 发送消息最大超时时间 默认60000 + int sendMsgTimeOut = Util.getIntValue(Util.null2String(configMap.get("sendMsgTimeOut")), RocketMQConstant.PRODUCER_SEND_MSG_TIME_OUT); + defaultMQProducer.setSendMsgTimeout(sendMsgTimeOut); + try { + defaultMQProducer.start(); + }catch (MQClientException e){ + throw new CustomerException("producer start error!"); + } + // mq地址 + defaultMQProducer.setNamesrvAddr(Util.null2String(configMap.get("NameServer"))); + PRODUCER_MAP.put(configName, defaultMQProducer); + } + } + } + return defaultMQProducer; + } + + /** + *

通过配置文件名称获取配置map

+ * @author xuanran.wang + * @dateTime 2023/1/4 13:18 + * @param configName 配置文件名称 + * @return 配置文件map + **/ + private synchronized static Map getConfigMapByName(String configName){ + Map configMap = new HashMap<>(); + if(!CONFIG_MAPS.containsKey(configName)){ + configMap = RocketUtil.initMQConfigMap(configName); + CONFIG_MAPS.put(configName, configMap); + } + return configMap; + } + } diff --git a/src/main/java/weaver/xuanran/wang/shyl/mq/action/ProducerAction.java b/src/main/java/weaver/xuanran/wang/shyl/mq/action/ProducerAction.java new file mode 100644 index 0000000..f117afd --- /dev/null +++ b/src/main/java/weaver/xuanran/wang/shyl/mq/action/ProducerAction.java @@ -0,0 +1,31 @@ +package weaver.xuanran.wang.shyl.mq.action; + +import aiyh.utils.action.SafeCusBaseAction; +import aiyh.utils.annotation.RequiredMark; +import weaver.hrm.User; +import weaver.soa.workflow.request.RequestInfo; + +/** + *

生产者action 将流程数据发送到mq中

+ * + * @author xuanran.wang + * @date 2023/1/4 14:47 + */ +public class ProducerAction extends SafeCusBaseAction { + + /** + *

mq配置文件名称

+ **/ + @RequiredMark + private String MQConfigName; + /** + *

配置文件唯一标识

+ **/ + @RequiredMark + private String onlyMark; + + @Override + public void doSubmit(String requestId, String billTable, int workflowId, User user, RequestInfo requestInfo) { + + } +} diff --git a/src/main/java/weaver/xuanran/wang/shyl/mq/constant/RocketMQConstant.java b/src/main/java/weaver/xuanran/wang/shyl/mq/constant/RocketMQConstant.java index d015a63..db980e2 100644 --- a/src/main/java/weaver/xuanran/wang/shyl/mq/constant/RocketMQConstant.java +++ b/src/main/java/weaver/xuanran/wang/shyl/mq/constant/RocketMQConstant.java @@ -25,6 +25,7 @@ public class RocketMQConstant { public static final String ID_TYPE_STU_CARD = "4"; public static final String ID_TYPE_SOLDIER_CARD = "5"; public static final String DEFAULT_PASSWORD = "1"; + public static final int PRODUCER_SEND_MSG_TIME_OUT = 60000; public static Map SEX_MAPPING = new HashMap<>(); diff --git a/src/main/java/weaver/xuanran/wang/shyl/mq/consumer/OrgConsumer.java b/src/main/java/weaver/xuanran/wang/shyl/mq/consumer/OrgConsumer.java index 2633780..b5c11a1 100644 --- a/src/main/java/weaver/xuanran/wang/shyl/mq/consumer/OrgConsumer.java +++ b/src/main/java/weaver/xuanran/wang/shyl/mq/consumer/OrgConsumer.java @@ -1,19 +1,15 @@ package weaver.xuanran.wang.shyl.mq.consumer; import aiyh.utils.Util; -import com.alibaba.fastjson.JSONObject; import org.apache.log4j.Logger; import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext; -import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus; import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently; import org.apache.rocketmq.common.message.MessageExt; -import weaver.xuanran.wang.shyl.mq.RocketMQFactory; -import weaver.xuanran.wang.shyl.mq.RocketMQListener; +import weaver.xuanran.wang.shyl.mq.RocketMQConsumerListener; import weaver.xuanran.wang.shyl.mq.service.impl.OrgServiceImpl; import weaver.xuanran.wang.shyl.mq.util.RocketUtil; import java.util.List; -import java.util.Map; /** *

部门队列消费者

@@ -21,7 +17,7 @@ import java.util.Map; * @Author xuanran.wang * @Date 2022/12/29 14:35 */ -public class OrgConsumer extends RocketMQListener { +public class OrgConsumer extends RocketMQConsumerListener { private static final Logger log = Util.getLogger(); private static final String CONFIG_NAME = "OrgConsumer"; diff --git a/src/main/java/weaver/xuanran/wang/shyl/mq/consumer/PassWordConsumer.java b/src/main/java/weaver/xuanran/wang/shyl/mq/consumer/PassWordConsumer.java index e45de99..f400e56 100644 --- a/src/main/java/weaver/xuanran/wang/shyl/mq/consumer/PassWordConsumer.java +++ b/src/main/java/weaver/xuanran/wang/shyl/mq/consumer/PassWordConsumer.java @@ -1,19 +1,15 @@ package weaver.xuanran.wang.shyl.mq.consumer; import aiyh.utils.Util; -import com.alibaba.fastjson.JSONObject; import org.apache.log4j.Logger; import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext; -import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus; import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently; import org.apache.rocketmq.common.message.MessageExt; -import weaver.xuanran.wang.shyl.mq.RocketMQFactory; -import weaver.xuanran.wang.shyl.mq.RocketMQListener; +import weaver.xuanran.wang.shyl.mq.RocketMQConsumerListener; import weaver.xuanran.wang.shyl.mq.service.impl.PassWordServiceImpl; import weaver.xuanran.wang.shyl.mq.util.RocketUtil; import java.util.List; -import java.util.Map; /** *

密码修改队列消费者

@@ -21,7 +17,7 @@ import java.util.Map; * @Author xuanran.wang * @Date 2022/12/29 14:35 */ -public class PassWordConsumer extends RocketMQListener { +public class PassWordConsumer extends RocketMQConsumerListener { private static final Logger log = Util.getLogger(); public static final String CONFIG_NAME = "PassWordConsumer"; diff --git a/src/main/java/weaver/xuanran/wang/shyl/mq/consumer/UserInfoConsumer.java b/src/main/java/weaver/xuanran/wang/shyl/mq/consumer/UserInfoConsumer.java index 708c069..f87a276 100644 --- a/src/main/java/weaver/xuanran/wang/shyl/mq/consumer/UserInfoConsumer.java +++ b/src/main/java/weaver/xuanran/wang/shyl/mq/consumer/UserInfoConsumer.java @@ -5,7 +5,7 @@ import org.apache.log4j.Logger; import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext; import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently; import org.apache.rocketmq.common.message.MessageExt; -import weaver.xuanran.wang.shyl.mq.RocketMQListener; +import weaver.xuanran.wang.shyl.mq.RocketMQConsumerListener; import weaver.xuanran.wang.shyl.mq.service.impl.UserServiceImpl; import weaver.xuanran.wang.shyl.mq.util.RocketUtil; @@ -17,7 +17,7 @@ import java.util.List; * @Author xuanran.wang * @Date 2022/12/29 14:35 */ -public class UserInfoConsumer extends RocketMQListener { +public class UserInfoConsumer extends RocketMQConsumerListener { private static final Logger log = Util.getLogger(); public static final String CONFIG_NAME = "UserInfoConsumer"; diff --git a/src/main/java/weaver/xuanran/wang/shyl/mq/service/ProducerService.java b/src/main/java/weaver/xuanran/wang/shyl/mq/service/ProducerService.java new file mode 100644 index 0000000..fb9580f --- /dev/null +++ b/src/main/java/weaver/xuanran/wang/shyl/mq/service/ProducerService.java @@ -0,0 +1,42 @@ +package weaver.xuanran.wang.shyl.mq.service; + +import aiyh.utils.Util; +import aiyh.utils.excention.CustomerException; +import com.alibaba.fastjson.JSONObject; +import org.apache.commons.collections.MapUtils; +import org.apache.commons.lang3.StringUtils; +import weaver.conn.RecordSet; +import weaver.xiao.commons.config.entity.RequestMappingConfig; +import weaver.xiao.commons.config.service.DealWithMapping; +import weaver.xuanran.wang.common.util.CommonUtil; +import weaver.xuanran.wang.shyl.mq.util.RocketUtil; + +import java.util.HashMap; +import java.util.Map; + +/** + *

生产者业务方法

+ * + * @author xuanran.wang + * @date 2023/1/4 14:54 + */ +public class ProducerService { + + private final DealWithMapping dealWithMapping = new DealWithMapping(); + + public void pushWorkFlowToMQ(String configName, String onlyMark, String requestId, String tableName){ + RequestMappingConfig requestMappingConfig = dealWithMapping.treeDealWithUniqueCode(onlyMark); + String selectMainSql = CommonUtil.getSelectSql(requestMappingConfig, tableName); + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(selectMainSql, requestId); + Map requestParam = new HashMap<>(); + if (recordSet.next()) { + dealWithMapping.setMainTable(tableName); + requestParam = dealWithMapping.getRequestParam(recordSet, requestMappingConfig); + } + if(MapUtils.isEmpty(requestParam)){ + throw new CustomerException("convert workflow information to json error!"); + } + RocketUtil.producerSendMsg(configName, JSONObject.toJSONString(requestParam)); + } +} diff --git a/src/main/java/weaver/xuanran/wang/shyl/mq/service/impl/OrgServiceImpl.java b/src/main/java/weaver/xuanran/wang/shyl/mq/service/impl/OrgServiceImpl.java index 5a715b1..c944603 100644 --- a/src/main/java/weaver/xuanran/wang/shyl/mq/service/impl/OrgServiceImpl.java +++ b/src/main/java/weaver/xuanran/wang/shyl/mq/service/impl/OrgServiceImpl.java @@ -24,6 +24,7 @@ import java.util.List; * @Date 2022/12/30 15:05 */ public class OrgServiceImpl extends CusInfoActionService { + /** *

部门创建

* @author xuanran.wang @@ -41,7 +42,7 @@ public class OrgServiceImpl extends CusInfoActionService { String subId = ""; RecordSet insertRs = new RecordSet(); if(StringUtils.isBlank(subId)){ - throw new CustomerException("SubCompany can not be empey!"); + throw new CustomerException("SubCompany can not be empty!"); } //使用存储过程新增分部 String para = org.getOrgName() + separator + org.getOrgName() + separator + @@ -83,6 +84,13 @@ public class OrgServiceImpl extends CusInfoActionService { } } + /** + *

部门更新

+ * @author xuanran.wang + * @dateTime 2023/1/4 14:44 + * @param message mq消息 + * @return 成功/重试 + **/ @Override public ConsumeConcurrentlyStatus cusUpdateAction(MQMessage message) { try { @@ -102,6 +110,14 @@ public class OrgServiceImpl extends CusInfoActionService { } } + /** + *

更新部门信息

+ * @author xuanran.wang + * @dateTime 2023/1/4 14:45 + * @param depId 部门id + * @param subId 分部id + * @param org 部门对象 + **/ public void updateDepartmentInfo(String depId, String subId, Org org){ String insertSQL = "update hrmdepartment set created = ?, creater = ?, modified = ?, modifier = ?," + " departmentcode = ?, tlevel = ?, showorder = ?, canceled = ?,departmentmark = ?, " + diff --git a/src/main/java/weaver/xuanran/wang/shyl/mq/util/RocketUtil.java b/src/main/java/weaver/xuanran/wang/shyl/mq/util/RocketUtil.java index a168ece..d1782fe 100644 --- a/src/main/java/weaver/xuanran/wang/shyl/mq/util/RocketUtil.java +++ b/src/main/java/weaver/xuanran/wang/shyl/mq/util/RocketUtil.java @@ -9,7 +9,15 @@ import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext; import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus; +import org.apache.rocketmq.client.exception.MQBrokerException; +import org.apache.rocketmq.client.exception.MQClientException; +import org.apache.rocketmq.client.producer.DefaultMQProducer; +import org.apache.rocketmq.client.producer.SendResult; +import org.apache.rocketmq.client.producer.SendStatus; +import org.apache.rocketmq.common.message.Message; import org.apache.rocketmq.common.message.MessageExt; +import org.apache.rocketmq.remoting.common.RemotingHelper; +import org.apache.rocketmq.remoting.exception.RemotingException; import weaver.xuanran.wang.shyl.mq.constant.RocketMQConstant; import weaver.xuanran.wang.shyl.mq.RocketMQFactory; import weaver.xuanran.wang.shyl.mq.entity.MQMessage; @@ -67,8 +75,8 @@ public class RocketUtil { try { if (CollectionUtils.isNotEmpty(msg)) { MessageExt messageExt = msg.get(0); - String msgBody = ""; - MQMessage mqMessage = null; + String msgBody; + MQMessage mqMessage; try { msgBody = new String(messageExt.getBody(), StandardCharsets.UTF_8); if(StringUtils.isBlank(msgBody)){ @@ -107,6 +115,7 @@ public class RocketUtil { } catch (Exception e) { // 如果重试达到最大还是异常那么先返回成功 oa将错误日志记录到日志中 if (msg.get(0).getReconsumeTimes() == maxReconsumeTimes) { + //TODO return ConsumeConcurrentlyStatus.CONSUME_SUCCESS; } else { return ConsumeConcurrentlyStatus.RECONSUME_LATER; @@ -114,4 +123,40 @@ public class RocketUtil { } return ConsumeConcurrentlyStatus.CONSUME_SUCCESS; } + + /** + *

向mq中发送消息

+ * @author xuanran.wang + * @dateTime 2023/1/4 14:30 + * @param configName 配置文件名称 + * @param msg 消息主体 + **/ + public static void producerSendMsg(String configName, String msg) { + // 先从本地缓存中获取生产者对象 + DefaultMQProducer producer = RocketMQFactory.getMQProducer(configName); + // 获取配置信息 + Map configMap = RocketMQFactory.CONFIG_MAPS.get(configName); + // 队列名 + String topic = Util.null2DefaultStr(configMap.get("Topic"),""); + // tag + String tag = Util.null2DefaultStr(configMap.get("Tag"),""); + Message message; + try { + message = new Message(topic, tag, msg.getBytes(RemotingHelper.DEFAULT_CHARSET)); + }catch (Exception e){ + throw new CustomerException(Util.logStr("init message error : {} !", e.getMessage())); + } + SendResult result; + try { + result = producer.send(message); + } catch (MQClientException | RemotingException | MQBrokerException | InterruptedException e) { + throw new CustomerException(Util.logStr("producer send message error!", e.getMessage())); + } + SendStatus sendStatus = result.getSendStatus(); + // 如果成功 + if(SendStatus.SEND_OK.equals(sendStatus)){ + log.error(Util.logStr("producer send message call back status is not ok! the message is {}, the status is {}.", msg, sendStatus)); + } + } + } diff --git a/src/test/java/xuanran/wang/schroeder/download_file/DownLoadFileTest.java b/src/test/java/xuanran/wang/schroeder/download_file/DownLoadFileTest.java index a3e0bf2..359ac05 100644 --- a/src/test/java/xuanran/wang/schroeder/download_file/DownLoadFileTest.java +++ b/src/test/java/xuanran/wang/schroeder/download_file/DownLoadFileTest.java @@ -4,7 +4,6 @@ import aiyh.utils.Util; import aiyh.utils.sqlUtil.sqlResult.impl.PrepSqlResultImpl; import basetest.BaseTest; import com.alibaba.fastjson.JSONObject; -import com.api.xuanran.wang.schroeder.download_file.mapper.DownLoadFileMapper; import com.icbc.api.internal.apache.http.impl.cookie.S; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; @@ -32,19 +31,6 @@ import java.util.stream.Collectors; * @Date 2022/12/7 11:58 */ public class DownLoadFileTest extends BaseTest { - private final DownLoadFileMapper downLoadFileMapper = Util.getMapper(DownLoadFileMapper.class); - - @Test - public void testSelectFileInfo() throws IOException { - Map fileInfo = downLoadFileMapper.selectDocInfoByDocId("95"); - log.info("map " + fileInfo); - String fileName = Util.null2String(fileInfo.get("fileName")); - int imageFileId = Util.getIntValue(Util.null2DefaultStr(fileInfo.get("imageFileId"),""), -1); - log.info("imageFileId " + imageFileId); - InputStream is = ImageFileManager.getInputStreamById(imageFileId); - log.info(null == is); - } - @Test public void testImageFileInputSteam(){ From 87771e942615ad53d97f2c0327b787807d7a8e68 Mon Sep 17 00:00:00 2001 From: "youHong.ai" <774495953@qq.com> Date: Thu, 2 Feb 2023 10:26:35 +0800 Subject: [PATCH 33/33] =?UTF-8?q?=E4=BF=9D=E6=97=B6=E6=8D=B7=E5=AE=9A?= =?UTF-8?q?=E6=97=B6=E4=BB=BB=E5=8A=A1=EF=BC=8C=E5=89=8D=E7=AB=AF=E4=BB=A3?= =?UTF-8?q?=E7=A0=81=EF=BC=8Cutil=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 4 +- javascript/common/dev.js | 19 +++++ .../fentian/ecode/workflow_controller.js | 29 ++++++- .../youhong.ai/pcn/workflow_code_block.js | 65 ++++++++++++++-- src/main/java/aiyh/utils/Util.java | 59 ++++++++++++-- .../aiyh/utils/action/CusBaseCronJob.java | 8 +- .../action/SafeCusActionProcessInterface.java | 37 +++++++++ .../aiyh/utils/httpUtil/util/HttpUtils.java | 13 +++- .../utils/recordset/RsThreadLocalManager.java | 2 +- .../DefaultQueryYearController.java | 49 ++++++++++++ .../mapper/DefaultQueryYearMapper.java | 29 +++++++ .../service/DefaultQueryYearService.java | 33 ++++++++ ...egisterRoleMemberByHasUnderingCronJob.java | 64 ++++++++++++++++ ...rRoleMemberByHasUnderingCronJobMapper.java | 23 ++++++ .../RegisterRoleMemberCronJob.java | 76 +++++++++++++++++++ .../mapper/RegisterRoleMemberMapper.java | 31 ++++++++ src/test/java/youhong/ai/pcn/RolesTest.java | 61 +++++++++++++++ 17 files changed, 578 insertions(+), 24 deletions(-) create mode 100644 src/main/java/aiyh/utils/action/SafeCusActionProcessInterface.java create mode 100644 src/main/java/com/api/youhong/ai/pcn/mode/apadefaultyear/controller/DefaultQueryYearController.java create mode 100644 src/main/java/com/api/youhong/ai/pcn/mode/apadefaultyear/mapper/DefaultQueryYearMapper.java create mode 100644 src/main/java/com/api/youhong/ai/pcn/mode/apadefaultyear/service/DefaultQueryYearService.java create mode 100644 src/main/java/weaver/youhong/ai/pcn/schedule/addrolebyhasundering/RegisterRoleMemberByHasUnderingCronJob.java create mode 100644 src/main/java/weaver/youhong/ai/pcn/schedule/addrolebyhasundering/mapper/RegisterRoleMemberByHasUnderingCronJobMapper.java create mode 100644 src/main/java/weaver/youhong/ai/pcn/schedule/addrolemember/RegisterRoleMemberCronJob.java create mode 100644 src/main/java/weaver/youhong/ai/pcn/schedule/addrolemember/mapper/RegisterRoleMemberMapper.java create mode 100644 src/test/java/youhong/ai/pcn/RolesTest.java diff --git a/.gitignore b/.gitignore index a85a048..d767065 100644 --- a/.gitignore +++ b/.gitignore @@ -23,7 +23,6 @@ log # should NOT be excluded as they contain compiler settings and other important # information for Eclipse / Flash Builder. -/target/ /log/ .DS_Store /src/main/resources/WEB-INF/prop/weaver.properties @@ -44,6 +43,7 @@ src/main/resources/WEB-INF/sqllog/ java.io.tempdir/ ecology-9-dev.iml src/test/resources/font - +src/main/resources/WEB-INF/vm/outFile +target/ diff --git a/javascript/common/dev.js b/javascript/common/dev.js index 0ceb3ed..4fc86d7 100644 --- a/javascript/common/dev.js +++ b/javascript/common/dev.js @@ -75,6 +75,12 @@ WfForm.bindFieldChangeEvent = function (fieldMarkStr, funobj = (obj, id, value) // }); } +WfForm.bindDetailFieldChangeEvent = function (fieldMarkStr, funobj = (id, rowIndex, value) => { +}) { + +} + + WfForm.controlBtnDisabled = function (isDisabled) { // isDisabled boolean 是 true:按钮全部置灰不可操作,false:恢复按钮可操作状态 // function subimtForm(params){ @@ -133,6 +139,16 @@ WfForm.changeFieldValue = function (fieldMark, valueInfo) { // }); } +/** + * 获取流览框显示值 + * fieldMark String 是 字段标示,格式field${字段ID}_${明细行号} + * splitChar String 否 分隔符,默认以逗号分隔 + * @param fieldMark + * @param splitChar + */ +WfForm.getBrowserShowName = function (fieldMark, splitChar) { +} + /* ******************* 建模表开发依赖 ******************* */ @@ -151,3 +167,6 @@ ModeList.dataLoadAfter = function (data) { }; + + + diff --git a/javascript/youhong.ai/fentian/ecode/workflow_controller.js b/javascript/youhong.ai/fentian/ecode/workflow_controller.js index 3205701..84bd6f7 100644 --- a/javascript/youhong.ai/fentian/ecode/workflow_controller.js +++ b/javascript/youhong.ai/fentian/ecode/workflow_controller.js @@ -20,6 +20,18 @@ class ConfigWorkflowTitle { || item.type === RulesType.SELECT_VALUE || item.type === RulesType.RADIO_VALUE).forEach(item => filedArr.push(item.fieldName)) this.addListenerEvent(filedArr) + this.addListenerSubmitEvent() + } + + + /** + * 监听提交流程动作 + */ + addListenerSubmitEvent = () => { + Utils.registerAction(WfForm.OPER_SAVE + "," + WfForm.OPER_SUBMIT, callback => { + this.changeWorkflowTitle() + callback() + }) } /** @@ -78,6 +90,12 @@ class RulesType { let year = date.getFullYear(); let month = date.getMonth() + 1; let day = date.getDay(); + if (month < 10) { + month = '0' + month + } + if (day < 10) { + day = '0' + day + } return year + "-" + month + "-" + day } } @@ -101,13 +119,13 @@ class RulesType { // 当前月份 static CURRENT_MONTH = { value: 7, - run: () => new Date().getMonth() + 1 + run: () => new Date().getMonth() + 1 < 10 ? new Date().getMonth() + 1 : '0' + new Date().getMonth() + 1 } // 当前天数 static CURRENT_DAY = { value: 8, - run: () => new Date().getDay() + run: () => new Date().getDay() < 10 ? new Date().getDay() : '0' + new Date().getDay() } // 当前小时 @@ -145,6 +163,13 @@ class RulesType { return result.join("") } } + static BROWSER_SHOW_NAME = { + value: 14, + run: item => { + let fieldId = Utils.convertNameObjToId(item.fieldName) + return WfForm.getBrowserShowName(fieldId) + } + } } diff --git a/javascript/youhong.ai/pcn/workflow_code_block.js b/javascript/youhong.ai/pcn/workflow_code_block.js index 74e8d70..e4daf23 100644 --- a/javascript/youhong.ai/pcn/workflow_code_block.js +++ b/javascript/youhong.ai/pcn/workflow_code_block.js @@ -208,7 +208,7 @@ window.workflowCus = Object.assign(window.workflowCus ? window.workflowCus : {}, getLevelByScore: async function (config) { let scoreFiled = config.scoreFiled let score = Utils.getFiledValueByName(scoreFiled); - if(score == 0 || score == ''){ + if (score == 0 || score == '') { return } let result = await Utils.api({ @@ -232,16 +232,69 @@ $(() => { levelField: "level1" } try { - setTimeout(()=>{ - WfForm.bindFieldChangeEvent(Utils.convertNameObjToId(config.scoreFiled),()=>{ - console.log("asdfasdfasdfsadfasdf") + setTimeout(() => { + WfForm.bindFieldChangeEvent(Utils.convertNameObjToId(config.scoreFiled), () => { window.workflowCus.getLevelByScore(config) }) window.workflowCus.getLevelByScore(config) - },100) - }catch (err){ + }, 100) + } catch (err) { console.log(err) } }) /* ******************* apa流程通过apa分数字段带出level字段eng ******************* */ + + +/* ******************* apa(employee)流程明细分数控制 ******************* */ +function addChangeEventListener(configItem) { + let fieldIds = Utils.convertNameToIdUtil([{ + fieldName: configItem.selfEvaluationScore, + table: configItem.table + }, { + fieldName: configItem.leaderScore, + table: configItem.table + }]) + WfForm.bindDetailFieldChangeEvent(fieldIds, (id, rowIndex, value) => { + if (value == '') { + return + } + if (value >= 1 && value <= 5) { + if (value % 0.5 !== 0) { + showHint(id + "_" + rowIndex) + } + } else { + showHint(id + "_" + rowIndex) + } + }) +} + +function showHint(id) { + WfForm.showMessage(`Evaluate your target completion by selecting a score. +The scores are of 0.5 break-down. + 5 - Outstanding + 4 - Exceeds Expectations + 3 - Meets Expectations + 2 - Needs Improvement + 1 - Unsatisfactory`, 2, 10) + setTimeout(() => { + WfForm.changeFieldValue(id, {value: ""}) + }, 100) +} + +$(() => { + let employeeDetailConfig = [{ + table: 'detail_1', + selfEvaluationScore: 'zp', + leaderScore: 'ldpf' + }, { + table: 'detail_2', + selfEvaluationScore: 'zp', + leaderScore: 'ldpf' + }] + employeeDetailConfig.forEach(item => { + addChangeEventListener(item) + }) +}) + +/* ******************* apa(employee)流程明细分数控制end ******************* */ \ No newline at end of file diff --git a/src/main/java/aiyh/utils/Util.java b/src/main/java/aiyh/utils/Util.java index ed2e2e6..2508486 100644 --- a/src/main/java/aiyh/utils/Util.java +++ b/src/main/java/aiyh/utils/Util.java @@ -1,6 +1,7 @@ package aiyh.utils; import aiyh.utils.action.CusBaseAction; +import aiyh.utils.action.SafeCusActionProcessInterface; import aiyh.utils.annotation.*; import aiyh.utils.annotation.recordset.SqlMapper; import aiyh.utils.entity.*; @@ -45,6 +46,8 @@ import weaver.soa.workflow.request.RequestInfo; import weaver.soa.workflow.request.RequestService; import weaver.systeminfo.SystemEnv; import weaver.workflow.request.RequestManager; +import weaver.workflow.workflow.WorkflowBillComInfo; +import weaver.workflow.workflow.WorkflowComInfo; import weaver.workflow.workflow.WorkflowVersion; import javax.servlet.http.HttpServletRequest; @@ -54,10 +57,7 @@ import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.io.*; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; +import java.lang.reflect.*; import java.math.BigDecimal; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; @@ -95,6 +95,7 @@ public class Util extends weaver.general.Util { public static final String UF_CUS_DEV_CONFIG = "uf_cus_dev_config"; private static final UtilService utilService = new UtilService(); private static final RecordsetUtil recordsetUtil = new RecordsetUtil(); + private static final RecordsetUtil recordsetTransUtil = new RecordsetUtil(); private static final UtilMapper mapper = recordsetUtil.getMapper(UtilMapper.class); private static final Map otherLog = new HashMap<>(8); static ToolUtil toolUtil = new ToolUtil(); @@ -1989,7 +1990,7 @@ public class Util extends weaver.general.Util { * @author youHong.ai ****************************************** */ public static T getTransMapper(Class t) { - return recordsetUtil.getMapper(t, false); + return recordsetTransUtil.getMapper(t, false); } /** @@ -2007,7 +2008,7 @@ public class Util extends weaver.general.Util { if (t.getAnnotation(SqlMapper.class) == null) { throw new BindingException("can not find SqlMapper annotation!"); } - return recordsetUtil.getRsManager().commit(t.getName()); + return recordsetTransUtil.getRsManager().commit(t.getName()); } /** @@ -2025,7 +2026,7 @@ public class Util extends weaver.general.Util { if (t.getAnnotation(SqlMapper.class) == null) { throw new BindingException("can not find SqlMapper annotation!"); } - return recordsetUtil.getRsManager().rollback(t.getName()); + return recordsetTransUtil.getRsManager().rollback(t.getName()); } /** @@ -3537,4 +3538,48 @@ public class Util extends weaver.general.Util { } return pathParamMap; } + + public static Object executeActionProcess(String process, RequestInfo requestInfo) { + if (StringUtils.isNullOrEmpty(process)) { + return null; + } + RequestManager requestManager = requestInfo.getRequestManager(); + String billTable = requestManager.getBillTableName(); + String requestId = requestInfo.getRequestid(); + User user = requestInfo.getRequestManager().getUser(); + int workflowId = requestManager.getWorkflowid(); + // 操作类型 submit - 提交 reject - 退回 等 + String src = requestManager.getSrc(); + if ("".equals(billTable)) { + WorkflowComInfo workflowComInfo = new WorkflowComInfo(); + String formId = workflowComInfo.getFormId(String.valueOf(workflowId)); + WorkflowBillComInfo workflowBillComInfo = new WorkflowBillComInfo(); + billTable = workflowBillComInfo.getTablename(formId); + } + Class clazz = SafeCusActionProcessInterface.class; + Class aClass; + try { + aClass = Class.forName(process); + } catch (ClassNotFoundException e) { + throw new IllegalArgumentException("未能找到自定义接口:" + process); + } + if (!clazz.isAssignableFrom(aClass)) { + throw new IllegalArgumentException("自定义接口:" + process + " 不是" + + clazz.getName() + "的子类或实现类!"); + } + Constructor constructor; + try { + constructor = aClass.getConstructor(); + } catch (NoSuchMethodException e) { + throw new IllegalArgumentException(process + "没有空参构造方法,无法获取构造方法对象!"); + } + SafeCusActionProcessInterface o; + try { + o = (SafeCusActionProcessInterface) constructor.newInstance(); + } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) { + throw new IllegalArgumentException("无法构造" + process + "对象!"); + } + Map pathParam = Util.parseCusInterfacePathParam(process); + return o.execute(pathParam, requestId, billTable, workflowId, user, requestInfo); + } } diff --git a/src/main/java/aiyh/utils/action/CusBaseCronJob.java b/src/main/java/aiyh/utils/action/CusBaseCronJob.java index 654f78d..2ac99a4 100644 --- a/src/main/java/aiyh/utils/action/CusBaseCronJob.java +++ b/src/main/java/aiyh/utils/action/CusBaseCronJob.java @@ -16,7 +16,7 @@ import weaver.interfaces.schedule.BaseCronJob; public abstract class CusBaseCronJob extends BaseCronJob { - Logger log = Util.getLogger(); + protected Logger log = Util.getLogger(); @Override @@ -39,8 +39,7 @@ public abstract class CusBaseCronJob extends BaseCronJob { * 2022/12/4 13:59 * ****************************************** * - * @author youHong.ai - * ****************************************** + * @author youHong.ai ****************************************** */ public abstract void runCode(); @@ -51,8 +50,7 @@ public abstract class CusBaseCronJob extends BaseCronJob { * ****************************************** * * @param e 异常类 - * @author youHong.ai - * ****************************************** + * @author youHong.ai ****************************************** */ public void exceptionCallback(Throwable e) { log.error("execute cronJon failure! error detail msg \n" + Util.getErrString(e)); diff --git a/src/main/java/aiyh/utils/action/SafeCusActionProcessInterface.java b/src/main/java/aiyh/utils/action/SafeCusActionProcessInterface.java new file mode 100644 index 0000000..c2a490b --- /dev/null +++ b/src/main/java/aiyh/utils/action/SafeCusActionProcessInterface.java @@ -0,0 +1,37 @@ +package aiyh.utils.action; + +import weaver.hrm.User; +import weaver.soa.workflow.request.RequestInfo; + +import java.util.Map; + +/** + *

流程自定义前置后置处理方法

+ * + *

create: 2023-01-10 13:19

+ * + * @author youHong.ai + */ + +@FunctionalInterface + +public interface SafeCusActionProcessInterface { + + /** + *

execute 流程action处理方法

+ * 2023/1/10 13:21 + * ************************************************************ + * + * @param pathParams 路径参数 + * @param requestId 流程请求id + * @param billTable 流程主表表名 + * @param workflowId 流程workflowId + * @param user 流程当前操作人 + * @param requestInfo action参数 + * @return Object 返回值 + * @author youHong.ai ****************************************** + */ + + Object execute(Map pathParams, String requestId, String billTable, int workflowId, + User user, RequestInfo requestInfo); +} diff --git a/src/main/java/aiyh/utils/httpUtil/util/HttpUtils.java b/src/main/java/aiyh/utils/httpUtil/util/HttpUtils.java index bf4d92b..ff116e4 100644 --- a/src/main/java/aiyh/utils/httpUtil/util/HttpUtils.java +++ b/src/main/java/aiyh/utils/httpUtil/util/HttpUtils.java @@ -281,8 +281,8 @@ public class HttpUtils { public ResponeVo apiGet(String url, Map params, Map headers) throws IOException { Map paramsMap = paramsHandle(params); - String getUrl = urlHandle(url, paramsMap); Map headerMap = headersHandle(headers); + String getUrl = urlHandle(url, paramsMap); CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); HttpGet httpGet = new HttpGet(getUrl.trim()); for (Map.Entry entry : headerMap.entrySet()) { @@ -409,6 +409,13 @@ public class HttpUtils { return baseRequest(httpConnection, httpPost); } + public ResponeVo apiPost(String url, List params, Map headers) throws IOException { + CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); + Map headerMap = headersHandle(headers); + HttpPost httpPost = handleHttpPost(url, headerMap, params); + return baseRequest(httpConnection, httpPost); + } + public ResponeVo apiPostObject(String url, Object params, Map headers) throws IOException { CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); Map headerMap = headersHandle(headers); @@ -1031,6 +1038,10 @@ public class HttpUtils { return handleHttpPostObject(url, headerMap, paramsMap); } + private HttpPost handleHttpPost(String url, Map headerMap, List params) throws UnsupportedEncodingException { + return handleHttpPostObject(url, headerMap, params); + } + /** *

上传文件

* diff --git a/src/main/java/aiyh/utils/recordset/RsThreadLocalManager.java b/src/main/java/aiyh/utils/recordset/RsThreadLocalManager.java index 5950668..e67da90 100644 --- a/src/main/java/aiyh/utils/recordset/RsThreadLocalManager.java +++ b/src/main/java/aiyh/utils/recordset/RsThreadLocalManager.java @@ -22,7 +22,7 @@ import java.util.concurrent.TimeUnit; public class RsThreadLocalManager { - private final ConcurrentHashMap> rsMap = new ConcurrentHashMap<>(); + private static final ConcurrentHashMap> rsMap = new ConcurrentHashMap<>(); private final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); diff --git a/src/main/java/com/api/youhong/ai/pcn/mode/apadefaultyear/controller/DefaultQueryYearController.java b/src/main/java/com/api/youhong/ai/pcn/mode/apadefaultyear/controller/DefaultQueryYearController.java new file mode 100644 index 0000000..77700d5 --- /dev/null +++ b/src/main/java/com/api/youhong/ai/pcn/mode/apadefaultyear/controller/DefaultQueryYearController.java @@ -0,0 +1,49 @@ +package com.api.youhong.ai.pcn.mode.apadefaultyear.controller; + +import aiyh.utils.ApiResult; +import aiyh.utils.Util; +import com.api.youhong.ai.pcn.mode.apadefaultyear.service.DefaultQueryYearService; +import org.apache.log4j.Logger; + +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; + +/** + *

查询默认的apa年份过滤默认年

+ * + *

create: 2023-01-05 14:54

+ * + * @author youHong.ai + */ + +@Path("ayh/mode/default-year") +public class DefaultQueryYearController { + + private final Logger log = Util.getLogger(); + + private final DefaultQueryYearService service = new DefaultQueryYearService(); + + /** + *

getYear 获取默认的搜索年份

+ * 2023/1/5 15:09 + * ************************************************************ + * + * @return String 年份响应数据 + * @author youHong.ai ****************************************** + */ + @Path("/get-year") + @GET + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) + public String getYear() { + try { + return ApiResult.success(service.getYear()); + } catch (Exception e) { + log.error("get default year error! exception msg is: \n" + Util.getErrString(e)); + return ApiResult.error(e.getMessage()); + } + } +} diff --git a/src/main/java/com/api/youhong/ai/pcn/mode/apadefaultyear/mapper/DefaultQueryYearMapper.java b/src/main/java/com/api/youhong/ai/pcn/mode/apadefaultyear/mapper/DefaultQueryYearMapper.java new file mode 100644 index 0000000..71adbd5 --- /dev/null +++ b/src/main/java/com/api/youhong/ai/pcn/mode/apadefaultyear/mapper/DefaultQueryYearMapper.java @@ -0,0 +1,29 @@ +package com.api.youhong.ai.pcn.mode.apadefaultyear.mapper; + +import aiyh.utils.annotation.recordset.Select; +import aiyh.utils.annotation.recordset.SqlMapper; + +/** + *

查询数据库数据

+ * + *

create: 2023-01-05 15:04

+ * + * @author youHong.ai + */ + +@SqlMapper +public interface DefaultQueryYearMapper { + + + /** + *

selectYearById 通过数据ID查询对应年份

+ * 2023/1/5 15:08 + * ************************************************************ + * + * @param id 数据id + * @return String 对应年份 + * @author youHong.ai ****************************************** + */ + @Select("select nf from uf_hrfunction where id = #{id}") + String selectYearById(Integer id); +} diff --git a/src/main/java/com/api/youhong/ai/pcn/mode/apadefaultyear/service/DefaultQueryYearService.java b/src/main/java/com/api/youhong/ai/pcn/mode/apadefaultyear/service/DefaultQueryYearService.java new file mode 100644 index 0000000..eacef05 --- /dev/null +++ b/src/main/java/com/api/youhong/ai/pcn/mode/apadefaultyear/service/DefaultQueryYearService.java @@ -0,0 +1,33 @@ +package com.api.youhong.ai.pcn.mode.apadefaultyear.service; + +import aiyh.utils.Util; +import cn.hutool.core.lang.Assert; +import com.api.youhong.ai.pcn.mode.apadefaultyear.mapper.DefaultQueryYearMapper; + +/** + *

获取年份

+ * + *

create: 2023-01-05 15:02

+ * + * @author youHong.ai + */ + +public class DefaultQueryYearService { + + + private final DefaultQueryYearMapper mapper = Util.getMapper(DefaultQueryYearMapper.class); + + /** + *

getYear 查询默认搜索年份

+ * 2023/1/5 15:06 + * ************************************************************ + * + * @return String 默认搜索年份 + * @author youHong.ai ****************************************** + */ + public String getYear() { + String year = mapper.selectYearById(1); + Assert.notBlank(year, "query year is null or blank!"); + return year; + } +} diff --git a/src/main/java/weaver/youhong/ai/pcn/schedule/addrolebyhasundering/RegisterRoleMemberByHasUnderingCronJob.java b/src/main/java/weaver/youhong/ai/pcn/schedule/addrolebyhasundering/RegisterRoleMemberByHasUnderingCronJob.java new file mode 100644 index 0000000..29cf61c --- /dev/null +++ b/src/main/java/weaver/youhong/ai/pcn/schedule/addrolebyhasundering/RegisterRoleMemberByHasUnderingCronJob.java @@ -0,0 +1,64 @@ +package weaver.youhong.ai.pcn.schedule.addrolebyhasundering; + +import aiyh.utils.Util; +import aiyh.utils.action.CusBaseCronJob; +import aiyh.utils.annotation.ActionDefaultTestValue; +import aiyh.utils.annotation.ActionDesc; +import aiyh.utils.annotation.PrintParamMark; +import aiyh.utils.annotation.RequiredMark; +import com.alibaba.fastjson.JSON; +import com.engine.common.util.ServiceUtil; +import com.engine.hrm.service.impl.RolesMembersServiceImpl; +import lombok.Getter; +import lombok.Setter; +import weaver.hrm.User; +import weaver.youhong.ai.pcn.schedule.addrolebyhasundering.mapper.RegisterRoleMemberByHasUnderingCronJobMapper; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +/** + *

将有下属的用户添加到指定的角色

+ * + *

create: 2023-01-10 15:20

+ * + * @author youHong.ai + */ +@ActionDesc(author = "youHong.ai", value = "将有下属的用户添加到指定的角色") +@Getter +@Setter +public class RegisterRoleMemberByHasUnderingCronJob extends CusBaseCronJob { + + private final RegisterRoleMemberByHasUnderingCronJobMapper mapper = Util.getMapper(RegisterRoleMemberByHasUnderingCronJobMapper.class); + + @RequiredMark("角色id") + @PrintParamMark + @ActionDefaultTestValue("2") + private String roleId; + + @Override + public void runCode() { + List resourcesIds = mapper.selectResources(); + if (Objects.isNull(resourcesIds) || resourcesIds.isEmpty()) { + log.info(Util.logStr("can not query resourceIds")); + return; + } + User user = new User(1); + RolesMembersServiceImpl service = ServiceUtil.getService(RolesMembersServiceImpl.class, user); + Map map = new HashMap<>(); + map.put("roleId", roleId); + map.put("resourcetype", 1); + map.put("resourceid", Util.intJoin(resourcesIds, ",")); + map.put("rolelevel", 2); + map.put("cmd", "addRolesMembers"); + Map result = service.saveRolesMembers(map, user); + String status = Util.null2String(result.get("status")); + if (!"1".equals(status)) { + log.error(Util.logStr("add roles members fail!, service params is [{}],service return result is [{}]", + JSON.toJSONString(map), + JSON.toJSONString(result))); + } + } +} diff --git a/src/main/java/weaver/youhong/ai/pcn/schedule/addrolebyhasundering/mapper/RegisterRoleMemberByHasUnderingCronJobMapper.java b/src/main/java/weaver/youhong/ai/pcn/schedule/addrolebyhasundering/mapper/RegisterRoleMemberByHasUnderingCronJobMapper.java new file mode 100644 index 0000000..3fc041d --- /dev/null +++ b/src/main/java/weaver/youhong/ai/pcn/schedule/addrolebyhasundering/mapper/RegisterRoleMemberByHasUnderingCronJobMapper.java @@ -0,0 +1,23 @@ +package weaver.youhong.ai.pcn.schedule.addrolebyhasundering.mapper; + +import aiyh.utils.annotation.recordset.Select; +import aiyh.utils.annotation.recordset.SqlMapper; + +import java.util.List; + +/** + *

添加人力资源人员到角色成员中

+ * + *

create: 2023-01-04 15:07

+ * + * @author youHong.ai + */ + +@SqlMapper +public interface RegisterRoleMemberByHasUnderingCronJobMapper { + + + @Select("select MANAGERID " + + "from hrmresource where MANAGERID <> 0 and MANAGERID is not null group by MANAGERID") + List selectResources(); +} diff --git a/src/main/java/weaver/youhong/ai/pcn/schedule/addrolemember/RegisterRoleMemberCronJob.java b/src/main/java/weaver/youhong/ai/pcn/schedule/addrolemember/RegisterRoleMemberCronJob.java new file mode 100644 index 0000000..1cecb99 --- /dev/null +++ b/src/main/java/weaver/youhong/ai/pcn/schedule/addrolemember/RegisterRoleMemberCronJob.java @@ -0,0 +1,76 @@ +package weaver.youhong.ai.pcn.schedule.addrolemember; + +import aiyh.utils.Util; +import aiyh.utils.action.CusBaseCronJob; +import aiyh.utils.annotation.ActionDefaultTestValue; +import aiyh.utils.annotation.ActionDesc; +import aiyh.utils.annotation.PrintParamMark; +import aiyh.utils.annotation.RequiredMark; +import com.alibaba.fastjson.JSON; +import com.engine.common.util.ServiceUtil; +import com.engine.hrm.service.impl.RolesMembersServiceImpl; +import lombok.Getter; +import lombok.Setter; +import weaver.hrm.User; +import weaver.youhong.ai.pcn.schedule.addrolemember.mapper.RegisterRoleMemberMapper; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +/** + *

添加指定条件的人力资源人员到角色成员中

+ * + *

create: 2023-01-04 14:58

+ * + * @author youHong.ai + */ + +@ActionDesc(author = "youHong.ai", value = "添加指定条件的人力资源人员到角色成员中") +@Getter +@Setter +public class RegisterRoleMemberCronJob extends CusBaseCronJob { + + private final RegisterRoleMemberMapper mapper = Util.getMapper(RegisterRoleMemberMapper.class); + + @RequiredMark("职级字段的字段名称") + @PrintParamMark + @ActionDefaultTestValue("field3") + private String rankField; + + @RequiredMark("角色id") + @PrintParamMark + @ActionDefaultTestValue("2") + private String roleId; + + @RequiredMark("对应职级id,多个id用','分割,如7,8") + @PrintParamMark + @ActionDefaultTestValue("7,8") + private String rankIds; + + @Override + public void runCode() { + List resourcesIds = mapper.selectResources(rankField, rankIds); + if (Objects.isNull(resourcesIds) || resourcesIds.isEmpty()) { + log.info(Util.logStr("can not query resourceIds by [{}] in [{}]", rankField, rankIds)); + return; + } + User user = new User(1); + RolesMembersServiceImpl service = ServiceUtil.getService(RolesMembersServiceImpl.class, user); + Map map = new HashMap<>(); + map.put("roleId", roleId); + map.put("resourcetype", 1); + map.put("resourceid", Util.intJoin(resourcesIds, ",")); + map.put("rolelevel", 2); + map.put("cmd", "addRolesMembers"); + Map result = service.saveRolesMembers(map, user); + String status = Util.null2String(result.get("status")); + if (!"1".equals(status)) { + log.error(Util.logStr("add roles members fail!, service params is [{}],service return result is [{}]", + JSON.toJSONString(map), + JSON.toJSONString(result))); + } + } + +} diff --git a/src/main/java/weaver/youhong/ai/pcn/schedule/addrolemember/mapper/RegisterRoleMemberMapper.java b/src/main/java/weaver/youhong/ai/pcn/schedule/addrolemember/mapper/RegisterRoleMemberMapper.java new file mode 100644 index 0000000..3056fe0 --- /dev/null +++ b/src/main/java/weaver/youhong/ai/pcn/schedule/addrolemember/mapper/RegisterRoleMemberMapper.java @@ -0,0 +1,31 @@ +package weaver.youhong.ai.pcn.schedule.addrolemember.mapper; + +import aiyh.utils.annotation.recordset.ParamMapper; +import aiyh.utils.annotation.recordset.Select; +import aiyh.utils.annotation.recordset.SqlMapper; + +import java.util.List; + +/** + *

添加人力资源人员到角色成员中

+ * + *

create: 2023-01-04 15:07

+ * + * @author youHong.ai + */ + +@SqlMapper +public interface RegisterRoleMemberMapper { + + @Select( + "select hrm.id\n " + + "from hrmresource hrm \n " + + " inner join cus_fielddata cus \n " + + " on cus.ID = hrm.ID \n " + + " and cus.SCOPEID = 1 \n " + + " and cus.SCOPE = 'HrmCustomFieldByInfoType' \n" + + " and cus.$t{rankField} in ($t{rankIds})" + ) + List selectResources(@ParamMapper("rankField") String rankField, + @ParamMapper("rankIds") String rankIds); +} diff --git a/src/test/java/youhong/ai/pcn/RolesTest.java b/src/test/java/youhong/ai/pcn/RolesTest.java new file mode 100644 index 0000000..fc2716b --- /dev/null +++ b/src/test/java/youhong/ai/pcn/RolesTest.java @@ -0,0 +1,61 @@ +package youhong.ai.pcn; + +import aiyh.utils.GenerateFileUtil; +import aiyh.utils.Util; +import basetest.BaseTest; +import com.engine.common.util.ServiceUtil; +import com.engine.hrm.service.impl.RolesMembersServiceImpl; +import org.junit.Test; +import weaver.hrm.User; +import weaver.youhong.ai.pcn.schedule.addrolebyhasundering.RegisterRoleMemberByHasUnderingCronJob; +import weaver.youhong.ai.pcn.schedule.addrolemember.RegisterRoleMemberCronJob; + +import java.util.HashMap; +import java.util.Map; + +/** + *

+ * + *

create: 2023-01-04 13:38

+ * + * @author youHong.ai + */ + +public class RolesTest extends BaseTest { + + + @Test + public void test() { + User user = new User(1); + RolesMembersServiceImpl service = ServiceUtil.getService(RolesMembersServiceImpl.class, user); + Map map = new HashMap<>(); + map.put("roleId", 2); + map.put("resourcetype", 1); + map.put("resourceid", 90); + map.put("rolelevel", 2); + map.put("cmd", "addRolesMembers"); + Map stringObjectMap = service.saveRolesMembers(map, user); + System.out.println(stringObjectMap); + /* String sql = " INSERT INTO HrmRoleMembers ( roleid ,resourceid ,rolelevel ,resourcetype ,alllevel ," + + " seclevelfrom ,seclevelto ,subdepid ,jobtitlelevel) " + + " VALUES ( " + roleId + ", " + arrObjIds[i] + " , '" + rolelevel + "', '" + resourcetype + "', " + + " " + (alllevel.length() == 0 ? "null" : alllevel) + "," + + (seclevelfrom.length() == 0 ? "null" : seclevelfrom) + "," + + " " + (seclevelto.length() == 0 ? "null" : seclevelto) + ", " + + (subdepid.length() == 0 ? "null" : "'" + subdepid + "'") + "," + + (jobtitlelevel.length() == 0 ? "null" : jobtitlelevel) + ")";*/ + } + + + @Test + public void testCronJob() { + Util.cronJobTest(RegisterRoleMemberCronJob.class); + } + + + @Test + public void generateDoc() { + GenerateFileUtil.createCronJobDocument(RegisterRoleMemberByHasUnderingCronJob.class); + } + +}