diff --git a/javascript/xuanran.wang/bme/js/BuildContractApply.js b/javascript/xuanran.wang/bme/js/BuildContractApply.js new file mode 100644 index 0000000..723ec25 --- /dev/null +++ b/javascript/xuanran.wang/bme/js/BuildContractApply.js @@ -0,0 +1,61 @@ +/** + * 柏美 施工合同申请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 DETAIL_MAX_SIZE = 5; +// 款项类型预计对应日期取值 +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 + } + 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(`${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 new file mode 100644 index 0000000..4aae9d3 --- /dev/null +++ b/javascript/xuanran.wang/bme/js/Common.js @@ -0,0 +1,175 @@ +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); + } +} + +/** + * 改变明细表字段只读 + * @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 new file mode 100644 index 0000000..4303665 --- /dev/null +++ b/javascript/xuanran.wang/bme/js/PurchaseContractApply.js @@ -0,0 +1,60 @@ +/** + * 柏美 采购合同申请js + * @author xuanran.wang + */ +// 明细表 +const detailTable = "detail_3"; +// 主表订单编号字段 +const mainProjectId = WfForm.convertFieldNameToId("ddh1"); +// 主表合同签订日期 +const contractSignDateId = WfForm.convertFieldNameToId("htqdrq"); +// 主表订单申请日期 +const mainPOApplyId = WfForm.convertFieldNameToId("rkdsqrq"); +// 明细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(mainPOApplyId)}); + }, + 4: (index)=>{ + WfForm.changeFieldValue(`${detailTempDateField}_${index}`,{value : WfForm.getFieldValue(mainPOApplyId)}); + } +} +$(()=>{ + init(); +}); + +function init(){ + + let obj = { + 'detailPaymentTypeId':detailPaymentTypeId, + 'detailTempDateId': detailTempDateField, + 'around': detailAroundId, + 'detailComPayDateId': detailComPayDateId, + 'dayId': detailDayId, + 'computeDatePayType': computeDatePayType, + 'paymentTypeGetValue': paymentTypeGetValue + } + changeDetailFieldReadOnly(detailTable, detailComPayDateId, detailPaymentTypeId, computeDatePayType) + // 主表字段发生变化 + 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..2836a58 --- /dev/null +++ b/javascript/xuanran.wang/bme/js/SaleContractApply.js @@ -0,0 +1,62 @@ +/** + * 柏美 销售合同申请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 + } + changeDetailFieldReadOnly(detailTable, detail2ComPayDateId, detail2PaymentTypeId, computeDatePayType) + // 主表字段发生变化 + 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 + + org.apache.rocketmq + rocketmq-client + 4.4.0 + + + + diff --git a/src/main/java/aiyh/utils/httpUtil/util/HttpUtils.java b/src/main/java/aiyh/utils/httpUtil/util/HttpUtils.java index ff116e4..36c94ea 100644 --- a/src/main/java/aiyh/utils/httpUtil/util/HttpUtils.java +++ b/src/main/java/aiyh/utils/httpUtil/util/HttpUtils.java @@ -1010,14 +1010,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())) { @@ -1198,14 +1204,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())) { 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 4a3c165..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 @@ -56,7 +56,7 @@ public class CheckUserService { String searchBase = Util.null2String(ADConfig.get("searchBase")); // LDAP搜索过滤器类 cn=*name*模糊查询 cn=name 精确查询 String searchFilter = "(objectClass="+type+")"; //查询域帐号 - String searchFilter = Util.null2String(ADConfig.get("queryField")) + "=" + checkInfo; + String searchFilter = "(" + Util.null2String(ADConfig.get("queryField")) + "=" + checkInfo + ")"; log.info("searchFilter : " + searchFilter); // 创建搜索控制器 SearchControls searchControl = new SearchControls(); @@ -64,8 +64,15 @@ public class CheckUserService { searchControl.setSearchScope(SearchControls.SUBTREE_SCOPE); // 根据设置的域节点、过滤器类和搜索控制器搜索LDAP得到结果 NamingEnumeration answer = ldapContext.search(searchBase, searchFilter, searchControl); + boolean has = answer.hasMoreElements(); + log.info("has " + has); + if(has){ + SearchResult sr = (SearchResult) answer.next(); + String dn = sr.getName(); + log.info("dn " + dn); + } // 初始化搜索结果数为0 - return answer.hasMoreElements(); + return has; } catch (NamingException e) { throw new CustomerException(Util.logStr("从AD搜索用户异常:[{}]",e.getMessage())); } finally { 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 626d929..1b7a56f 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 @@ -2,10 +2,20 @@ package com.api.xuanran.wang.saic_travel.model_create_workflow.controller; import aiyh.utils.ApiResult; import aiyh.utils.Util; +import aiyh.utils.excention.CustomerException; import com.alibaba.fastjson.JSONObject; +import com.api.xuanran.wang.saic_travel.model_create_workflow.service.CreateWorkFlowService; +import com.icbc.api.internal.apache.http.E; +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.formmode.data.ModeDataApproval; +import weaver.general.TimeUtil; import weaver.hrm.HrmUserVarify; import weaver.hrm.User; +import weaver.xuanran.wang.common.mapper.CommonMapper; import weaver.xuanran.wang.common.util.CommonUtil; // 工具类 import javax.servlet.http.HttpServletRequest; @@ -13,9 +23,7 @@ import javax.servlet.http.HttpServletResponse; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; +import java.util.*; import java.util.stream.Collectors; /** @@ -28,26 +36,75 @@ public class CusCreateWorkFlowController { private final Logger logger = Util.getLogger(); // 获取日志对象 + + + private final CreateWorkFlowService createWorkFlowService = new CreateWorkFlowService(); + + @Path("cusCreateWorkFlow") @POST @Produces(MediaType.TEXT_PLAIN) public String createWorkFlow(@Context HttpServletRequest request, @Context HttpServletResponse response) { - User logInUser = HrmUserVarify.getUser(request, response); - if(logInUser == null){ - return ApiResult.error(403,"请先登录!"); - } - 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 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/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/bme/action/ContractApplyComDateAction.java b/src/main/java/weaver/xuanran/wang/bme/action/ContractApplyComDateAction.java new file mode 100644 index 0000000..2739c08 --- /dev/null +++ b/src/main/java/weaver/xuanran/wang/bme/action/ContractApplyComDateAction.java @@ -0,0 +1,92 @@ +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) { + log.info(Util.logStr("--------------- requestId : {} Begin ---------------", requestId)); + RecordSetTrans rs = new RecordSetTrans(); + 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; + } + log.info(Util.logStr("更新合同明细表sql:{}, 参数:{}, {}", updateSql, checkDate, mainId)); + if(!rs.executeUpdate(updateSql, checkDate, mainId)){ + throw new CustomerException("更新合同sql错误!"); + } + rs.commit(); + }else{ + log.error(Util.logStr("查询施工合同关联项目sql暂未查到数据! sql {} ,{}", selectSql, requestId)); + } + }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..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; @@ -232,6 +234,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 +349,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 +541,77 @@ 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)); + } + + /** + *

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

+ * @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/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/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 new file mode 100644 index 0000000..6590154 --- /dev/null +++ b/src/main/java/weaver/xuanran/wang/epdi/datapush/eneity/DetailRequestConfig.java @@ -0,0 +1,27 @@ +package weaver.xuanran.wang.epdi.datapush.eneity; + + +import lombok.Data; + +import java.util.List; + +/** + *

配置表明细表实体类

+ * + * @Author xuanran.wang + * @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 workFlowField; + 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 new file mode 100644 index 0000000..fc9b565 --- /dev/null +++ b/src/main/java/weaver/xuanran/wang/epdi/datapush/eneity/MainRequestConfig.java @@ -0,0 +1,24 @@ +package weaver.xuanran.wang.epdi.datapush.eneity; + + +import lombok.Data; + +import java.util.List; + +/** + *

配置表主表实体类

+ * + * @Author xuanran.wang + * @Date 2022/12/23 16:20 + */ +@Data +public class MainRequestConfig { + private String id; + private String uniqueCode; + private String workflow; + private String requestUrl; + private String cusSql; + private String enable; + 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/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..4464b7b 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,25 @@ 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 com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.JSONPObject; 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 +29,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 +53,160 @@ 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 detailFileId = schroederQRCodeService.getDetailFileId(fileField, detailTable, mainId); + log.info(Util.logStr("明细docId集合 : {}", JSONObject.toJSONString(detailFileId))); + List> docLogParamList = new ArrayList<>(); + 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); + // 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..ada21ba --- /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 weaver.interfaces.workflow.action.Action; +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 implements Action { + + /** + *

建模配置唯一标识

+ **/ + private String onlyMark; + /** + *

响应成功状态码

+ **/ + private String successCode; + /** + *

请求方式

+ **/ + private String type; + + private final SchroederQRCodeService schroederQRCodeService = new SchroederQRCodeService(); + + + @Override + 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){ + 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/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..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,14 +20,12 @@ 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(); // 获取日志对象 @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 +37,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(); @@ -48,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); @@ -61,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 1812c4c..8fda5f3 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; @@ -38,8 +39,23 @@ 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 + * @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..79cf853 100644 --- a/src/main/java/weaver/xuanran/wang/schroeder/service/SchroederQRCodeService.java +++ b/src/main/java/weaver/xuanran/wang/schroeder/service/SchroederQRCodeService.java @@ -7,27 +7,20 @@ 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 +31,6 @@ import java.util.stream.Collectors; */ public class SchroederQRCodeService { private static final int SUCCESS_CODE = 200; - /** - *

成功状态码

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

接口响应信息

**/ @@ -54,119 +43,245 @@ 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(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("filePath"), ""); - String docId = Util.null2DefaultStr(filePath.substring(filePath.lastIndexOf("=") + 1),""); - return sealFile.equals(docId); + String filePath = Util.null2DefaultStr(item.get("fileUrlPath"), ""); + String docId = Util.null2DefaultStr(filePath.substring(filePath.lastIndexOf("=") + 1), ""); + return finalSealFile.equals(docId); }) .collect(Collectors.toList()); - if(CollectionUtils.isNotEmpty(filterFiles)){ + log.info(Util.logStr("filterFiles : {} ", JSONObject.toJSONString(finalSealFile))); + 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); + // 骑缝章总类 + 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); 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); + } + + + /** + *

获取明细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/RocketMQConsumerListener.java b/src/main/java/weaver/xuanran/wang/shyl/mq/RocketMQConsumerListener.java new file mode 100644 index 0000000..366a1b1 --- /dev/null +++ b/src/main/java/weaver/xuanran/wang/shyl/mq/RocketMQConsumerListener.java @@ -0,0 +1,67 @@ +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; + +/** + *

上海团校RocketMQListener

+ * + * @Author xuanran.wang + * @Date 2022/12/29 12:25 + */ +public abstract class RocketMQConsumerListener extends HttpServlet { + private static final Logger log = Util.getLogger(); + private String configName; + public RocketMQConsumerListener() { + } + public RocketMQConsumerListener(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/RocketMQFactory.java b/src/main/java/weaver/xuanran/wang/shyl/mq/RocketMQFactory.java new file mode 100644 index 0000000..ee9bee2 --- /dev/null +++ b/src/main/java/weaver/xuanran/wang/shyl/mq/RocketMQFactory.java @@ -0,0 +1,120 @@ +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.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; +import weaver.xuanran.wang.shyl.mq.util.RocketUtil; + +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + *

rocketMQ工厂

+ * + * @Author xuanran.wang + * @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 = getConfigMapByName(configName); + // 最大重试次数 + 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())); + } + } + + /** + *

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

+ * @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 new file mode 100644 index 0000000..db980e2 --- /dev/null +++ b/src/main/java/weaver/xuanran/wang/shyl/mq/constant/RocketMQConstant.java @@ -0,0 +1,35 @@ +package weaver.xuanran.wang.shyl.mq.constant; + +import java.util.HashMap; +import java.util.Map; + +/** + *

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; + 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 final int PRODUCER_SEND_MSG_TIME_OUT = 60000; + + 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 new file mode 100644 index 0000000..b5c11a1 --- /dev/null +++ b/src/main/java/weaver/xuanran/wang/shyl/mq/consumer/OrgConsumer.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.RocketMQConsumerListener; +import weaver.xuanran.wang.shyl.mq.service.impl.OrgServiceImpl; +import weaver.xuanran.wang.shyl.mq.util.RocketUtil; + +import java.util.List; + +/** + *

部门队列消费者

+ * + * @Author xuanran.wang + * @Date 2022/12/29 14:35 + */ +public class OrgConsumer extends RocketMQConsumerListener { + + 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); + } + + @Override + public MessageListenerConcurrently service() { + 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 new file mode 100644 index 0000000..f400e56 --- /dev/null +++ b/src/main/java/weaver/xuanran/wang/shyl/mq/consumer/PassWordConsumer.java @@ -0,0 +1,36 @@ +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.RocketMQConsumerListener; +import weaver.xuanran.wang.shyl.mq.service.impl.PassWordServiceImpl; +import weaver.xuanran.wang.shyl.mq.util.RocketUtil; + +import java.util.List; + +/** + *

密码修改队列消费者

+ * + * @Author xuanran.wang + * @Date 2022/12/29 14:35 + */ +public class PassWordConsumer extends RocketMQConsumerListener { + + private static final Logger log = Util.getLogger(); + public static final String CONFIG_NAME = "PassWordConsumer"; + + public PassWordConsumer(){ + super(CONFIG_NAME); + } + + private final PassWordServiceImpl passWordService = new PassWordServiceImpl(); + + @Override + public MessageListenerConcurrently service() { + 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 new file mode 100644 index 0000000..f87a276 --- /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.RocketMQConsumerListener; +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 RocketMQConsumerListener { + 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..f147608 --- /dev/null +++ b/src/main/java/weaver/xuanran/wang/shyl/mq/entity/ModifyPassWord.java @@ -0,0 +1,46 @@ +package weaver.xuanran.wang.shyl.mq.entity; + +import lombok.Data; + +/** + *

密码修改

+ * + * @Author xuanran.wang + * @Date 2022/12/30 13:59 + */ +@Data +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..e3f87d7 --- /dev/null +++ b/src/main/java/weaver/xuanran/wang/shyl/mq/mapper/ConsumerMapper.java @@ -0,0 +1,75 @@ +package weaver.xuanran.wang.shyl.mq.mapper; + +import aiyh.utils.annotation.recordset.ParamMapper; +import aiyh.utils.annotation.recordset.Update; + +import java.util.Map; + +/** + *

消费者mapper

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

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

+ * @author xuanran.wang + * @dateTime 2022/12/30 14:33 + * @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); + + /** + *

通过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 new file mode 100644 index 0000000..d9727a5 --- /dev/null +++ b/src/main/java/weaver/xuanran/wang/shyl/mq/service/CusInfoActionService.java @@ -0,0 +1,41 @@ +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; + +/** + *

抽象类

+ * + * @Author xuanran.wang + * @Date 2022/12/30 13:04 + */ +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/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 new file mode 100644 index 0000000..c944603 --- /dev/null +++ b/src/main/java/weaver/xuanran/wang/shyl/mq/service/impl/OrgServiceImpl.java @@ -0,0 +1,190 @@ +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; + +/** + *

+ * + * @Author xuanran.wang + * @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) { + 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 empty!"); + } + //使用存储过程新增分部 + 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) { + 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())); + } + } + + /** + *

部门更新

+ * @author xuanran.wang + * @dateTime 2023/1/4 14:44 + * @param message mq消息 + * @return 成功/重试 + **/ + @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())); + } + } + + /** + *

更新部门信息

+ * @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 = ?, " + + " 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 new file mode 100644 index 0000000..2078bae --- /dev/null +++ b/src/main/java/weaver/xuanran/wang/shyl/mq/service/impl/UserServiceImpl.java @@ -0,0 +1,237 @@ +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; + +/** + *

用户业务方法

+ * + * @Author xuanran.wang + * @Date 2022/12/30 13:04 + */ +public class UserServiceImpl extends CusInfoActionService { + + /** + *

用户新增

+ * @author xuanran.wang + * @dateTime 2023/1/3 13:37 + * @param message mq消息 + * @return 成功/重试 + **/ + @Override + public ConsumeConcurrentlyStatus cusCreateAction(MQMessage message) { + 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) { + throw new CustomerException(Util.logStr("update user status error!")); + } + return ConsumeConcurrentlyStatus.CONSUME_SUCCESS; + } 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) { + 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/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..d1782fe --- /dev/null +++ b/src/main/java/weaver/xuanran/wang/shyl/mq/util/RocketUtil.java @@ -0,0 +1,162 @@ +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.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; +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; + 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())); + } + }else { + log.error("the msgList is empty!"); + } + } catch (Exception e) { + // 如果重试达到最大还是异常那么先返回成功 oa将错误日志记录到日志中 + if (msg.get(0).getReconsumeTimes() == maxReconsumeTimes) { + //TODO + return ConsumeConcurrentlyStatus.CONSUME_SUCCESS; + } else { + return ConsumeConcurrentlyStatus.RECONSUME_LATER; + } + } + 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/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/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)); + + } +} 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..359ac05 100644 --- a/src/test/java/xuanran/wang/schroeder/download_file/DownLoadFileTest.java +++ b/src/test/java/xuanran/wang/schroeder/download_file/DownLoadFileTest.java @@ -1,9 +1,9 @@ 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; import com.icbc.api.internal.apache.http.impl.cookie.S; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; @@ -31,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(){ @@ -154,4 +141,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; diff --git a/src/test/resources/ application.properties b/src/test/resources/ application.properties new file mode 100644 index 0000000..e69de29 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 + +``` ### 如何操作数据库