From 154bd530467cae82aa321ed4ac8c5f2981821db6 Mon Sep 17 00:00:00 2001 From: wangxuanran <3055088966@qq.com> Date: Fri, 14 Jul 2023 14:50:48 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../xuanran.wang/ajx/ChildWorkFlowSplit.js | 26 + .../ey/zhang/ImportExtValidateTemplate.java | 342 +++++++++ .../ey/zhang/ImportNtoOValidateTemplate.java | 307 ++++++++ .../ey/zhangm/didi/annotation/DaoField.java | 20 + .../zhangm/didi/annotation/DaoTableField.java | 18 + .../zhangm/didi/entity/DidiInvoiceOrder.java | 55 ++ .../ey/zhangm/didi/entity/DidiOrder.java | 543 +++++++++++++ .../zhangm/didi/entity/DidiQualification.java | 109 +++ .../ey/zhangm/didi/entity/DidiTitle.java | 68 ++ .../ey/zhangm/didi/entity/RequestLog.java | 119 +++ .../ey/zhangm/didi/entity/Result.java | 111 +++ .../seconddev/ey/zhangm/didi/util/BUtils.java | 80 ++ .../ey/zhangm/didi/util/DaoUtils.java | 514 +++++++++++++ .../ey/zhangm/didi/util/DateUtils.java | 354 +++++++++ .../ey/zhangm/didi/util/StringUtils.java | 291 +++++++ .../ey/zhangm/util/EYSeconddevUtil.java | 721 ++++++++++++++++++ .../data_async/util/EyDataAsyncTokenUtil.java | 13 +- .../xuanran/wang/http_test/test/TestMain.java | 12 +- .../rest_test/AbstractCusRestTemplate.java | 188 +++++ .../wang/rest_test/CusRestTemplate.java | 100 +-- .../wang/rest_test/impl/CusGetRequest.java | 25 + .../wang/rest_test/impl/CusPostRequest.java | 24 + .../interfaces/CusApiRequestInterface.java | 19 + .../pojo/CusRestTemplateResponse.java | 50 ++ 24 files changed, 3995 insertions(+), 114 deletions(-) create mode 100644 javascript/xuanran.wang/ajx/ChildWorkFlowSplit.js create mode 100644 src/main/java/weaver/formmode/interfaces/impl/ey/zhang/ImportExtValidateTemplate.java create mode 100644 src/main/java/weaver/formmode/interfaces/impl/ey/zhang/ImportNtoOValidateTemplate.java create mode 100644 src/main/java/weaver/seconddev/ey/zhangm/didi/annotation/DaoField.java create mode 100644 src/main/java/weaver/seconddev/ey/zhangm/didi/annotation/DaoTableField.java create mode 100644 src/main/java/weaver/seconddev/ey/zhangm/didi/entity/DidiInvoiceOrder.java create mode 100644 src/main/java/weaver/seconddev/ey/zhangm/didi/entity/DidiOrder.java create mode 100644 src/main/java/weaver/seconddev/ey/zhangm/didi/entity/DidiQualification.java create mode 100644 src/main/java/weaver/seconddev/ey/zhangm/didi/entity/DidiTitle.java create mode 100644 src/main/java/weaver/seconddev/ey/zhangm/didi/entity/RequestLog.java create mode 100644 src/main/java/weaver/seconddev/ey/zhangm/didi/entity/Result.java create mode 100644 src/main/java/weaver/seconddev/ey/zhangm/didi/util/BUtils.java create mode 100644 src/main/java/weaver/seconddev/ey/zhangm/didi/util/DaoUtils.java create mode 100644 src/main/java/weaver/seconddev/ey/zhangm/didi/util/DateUtils.java create mode 100644 src/main/java/weaver/seconddev/ey/zhangm/didi/util/StringUtils.java create mode 100644 src/main/java/weaver/seconddev/ey/zhangm/util/EYSeconddevUtil.java create mode 100644 src/test/java/xuanran/wang/rest_test/AbstractCusRestTemplate.java create mode 100644 src/test/java/xuanran/wang/rest_test/impl/CusGetRequest.java create mode 100644 src/test/java/xuanran/wang/rest_test/impl/CusPostRequest.java create mode 100644 src/test/java/xuanran/wang/rest_test/interfaces/CusApiRequestInterface.java create mode 100644 src/test/java/xuanran/wang/rest_test/pojo/CusRestTemplateResponse.java diff --git a/javascript/xuanran.wang/ajx/ChildWorkFlowSplit.js b/javascript/xuanran.wang/ajx/ChildWorkFlowSplit.js new file mode 100644 index 0000000..53183d7 --- /dev/null +++ b/javascript/xuanran.wang/ajx/ChildWorkFlowSplit.js @@ -0,0 +1,26 @@ +$(()=>{ + const config = { + // 子流程主表帐套号字段名 + zth:'zth', + filterConfig:{ + // 子流程明细表帐套号字段名 + zthm:'zthm', + // 子流程明细表索引 + detailNo: 1 + } + } + const mainZth = WfForm.convertFieldNameToId(config.zth); + const detailTable = "detail_" + config.filterConfig.detailNo; + const detailZth = WfForm.convertFieldNameToId(config.filterConfig.zthm, detailTable); + let rowArr = WfForm.getDetailAllRowIndexStr(detailTable).split(","); + let mainZthVal = WfForm.getFieldValue(mainZth); + for(let i=0; i < rowArr.length; i++){ + let rowIndex = rowArr[i]; + if(rowIndex !== ""){ + let fieldValue = WfForm.getFieldValue(`${detailZth}_${rowIndex}`); + if(mainZthVal !== fieldValue){ + $(`#oTable${+config.filterConfig.detailNo - 1} tr[data-rowindex='${rowIndex}']`).css("display","none") + } + } + } +}) diff --git a/src/main/java/weaver/formmode/interfaces/impl/ey/zhang/ImportExtValidateTemplate.java b/src/main/java/weaver/formmode/interfaces/impl/ey/zhang/ImportExtValidateTemplate.java new file mode 100644 index 0000000..81b2124 --- /dev/null +++ b/src/main/java/weaver/formmode/interfaces/impl/ey/zhang/ImportExtValidateTemplate.java @@ -0,0 +1,342 @@ +package weaver.formmode.interfaces.impl.ey.zhang; + +import com.alibaba.fastjson.JSON; +import org.apache.commons.lang.StringUtils; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.Workbook; +import weaver.conn.RecordSet; +import weaver.file.ExcelParseForPOI; +import weaver.formmode.interfaces.ImportPreInterfaceForPOIAction; +import weaver.general.BaseBean; +import weaver.general.Util; +import weaver.hrm.User; +import weaver.seconddev.ey.zhangm.didi.util.DaoUtils; +import weaver.seconddev.ey.zhangm.util.EYSeconddevUtil; + +import java.util.HashMap; +import java.util.Map; +import java.util.regex.Pattern; + + +/** + * @Description + * @Author miao.zhang + * @Version V1.0.0 + * @Since 1.0 + * @Date 6/22/23 + */ +public class ImportExtValidateTemplate implements ImportPreInterfaceForPOIAction { + + @Override + public String checkImportData(Map param, User user, ExcelParseForPOI excelParse) { + + EYSeconddevUtil eySeconddevUtil = new EYSeconddevUtil(); + String ssids="ey_clentid_col,budget_version_col,plan_source_col,ey_bucode_col,ey_oucode_col,ey_mucode_col,ey_smucode_col,ey_engagementname_col,ey_ep_col,ey_em_col,ey_pfma_col,"; + ssids=ssids+"ey_local_service_code_col,ey_mercury_code_col,ey_pycode_col,ey_pacelink_col,ey_oppr_code_col,ey_blocking_level_col,opencheckcustom,"; + ssids=ssids+"opencheckbudget,opencheckcodeblock,opencheckgpn,opencheckengagementname,opencheckpycode,opencheckcodeblockByBcp,openchecklocalservicecode,"; + ssids=ssids+"opencheckconfidential,opencheckopprCode,opencheckmercury,opencheckblocklevel"; + Map ey_params_map =eySeconddevUtil.getSystemParamValues(ssids); + + int ey_clentid_col = Util.getIntValue(ey_params_map.get("ey_clentid_col")); + int budget_version_col = Util.getIntValue(ey_params_map.get("budget_version_col")); + int plan_source_col = Util.getIntValue(ey_params_map.get("plan_source_col")); + int ey_bucode_col = Util.getIntValue(ey_params_map.get("ey_bucode_col")); + int ey_oucode_col = Util.getIntValue(ey_params_map.get("ey_oucode_col")); + int ey_mucode_col = Util.getIntValue(ey_params_map.get("ey_mucode_col")); + int ey_smucode_col = Util.getIntValue(ey_params_map.get("ey_smucode_col")); + int ey_engagementname_col = Util.getIntValue(ey_params_map.get("ey_engagementname_col")); + int ey_ep_col = Util.getIntValue(ey_params_map.get("ey_ep_col")); + int ey_em_col = Util.getIntValue(ey_params_map.get("ey_em_col")); + int ey_pfma_col = Util.getIntValue(ey_params_map.get("ey_pfma_col")); + int ey_local_service_code_col = Util.getIntValue(ey_params_map.get("ey_local_service_code_col")); + int ey_mercury_code_col = Util.getIntValue(ey_params_map.get("ey_mercury_code_col")); + int ey_pycode_col = Util.getIntValue(ey_params_map.get("ey_pycode_col")); + int ey_pacelink_col = Util.getIntValue(ey_params_map.get("ey_pacelink_col")); + int ey_oppr_code_col = Util.getIntValue(ey_params_map.get("ey_oppr_code_col")); + int ey_blocking_level_col = Util.getIntValue(ey_params_map.get("ey_blocking_level_col")); + String opencheckcustom = Util.null2String(ey_params_map.get("opencheckcustom")); + String opencheckbudget = Util.null2String(ey_params_map.get("opencheckbudget")); + String opencheckcodeblock = Util.null2String(ey_params_map.get("opencheckcodeblock")); + String opencheckgpn = Util.null2String(ey_params_map.get("opencheckgpn")); + String opencheckengagementname = Util.null2String(ey_params_map.get("opencheckengagementname")); + String opencheckpycode = Util.null2String(ey_params_map.get("opencheckpycode")); + String opencheckcodeblockByBcp = Util.null2String(ey_params_map.get("opencheckcodeblockByBcp")); + String openchecklocalservicecode = Util.null2String(ey_params_map.get("openchecklocalservicecode")); + String opencheckconfidential = Util.null2String(ey_params_map.get("opencheckconfidential")); + String opencheckopprCode =Util.null2String(ey_params_map.get("opencheckopprCode")); + String opencheckmercury =Util.null2String(ey_params_map.get("opencheckmercury")); + String opencheckblocklevel =Util.null2String(ey_params_map.get("opencheckblocklevel")); + + new BaseBean().writeLog("opencheckcustom==>" + opencheckcustom+",opencheckbudget==>"+opencheckbudget+",opencheckcodeblock==>"+opencheckcodeblock); + new BaseBean().writeLog("opencheckgpn==>" + opencheckgpn+",opencheckengagementname==>"+opencheckengagementname+",opencheckpycode==>"+opencheckpycode); + new BaseBean().writeLog("opencheckcodeblockByBcp==>" + opencheckcodeblockByBcp+",openchecklocalservicecode==>"+openchecklocalservicecode+",opencheckconfidential==>"+opencheckconfidential); + new BaseBean().writeLog("opencheckopprCode==>" + opencheckopprCode+",opencheckmercury==>"+opencheckmercury); + + + // 获取模块ID + Integer modeId = Util.getIntValue(param.get("modeid").toString()); + //表单id + Integer formId = Util.getIntValue(param.get("formid").toString()); + // 获取当前登录人员ID + Integer userId = user.getUID(); + String sheetname = "1"; + //获取第 sheetindex 个sheet的第row行第col列的单元格的值 (下标都是从1开始) + //String value = excelParse.getValue("1", 2, 2); + Workbook wb = excelParse.getWb(); + Sheet sheet = wb.getSheetAt(Util.getIntValue(sheetname) - 1); + StringBuilder error = new StringBuilder(); + Pattern DATE_PATTERN = Pattern.compile("^\\d{4}-\\d{2}$"); + if (sheet != null) { + int rowSum = sheet.getPhysicalNumberOfRows(); + new BaseBean().writeLog("rowSum==>" + rowSum); + int current_row = 0; + for (int i = 2; i <= rowSum; i++) { + current_row = i - 1; + String client_id = Util.null2String(excelParse.getValue("1", i, ey_clentid_col)); + String budget_version_id = Util.null2String(excelParse.getValue("1", i, budget_version_col)); + String bucode = Util.null2String(excelParse.getValue("1", i, ey_bucode_col)); + String oucode = Util.null2String(excelParse.getValue("1", i, ey_oucode_col)); + String mucode = Util.null2String(excelParse.getValue("1", i, ey_mucode_col)); + String plan_source = Util.null2String(excelParse.getValue("1", i, plan_source_col)); + String smucode = Util.null2String(excelParse.getValue("1", i, ey_smucode_col)); + String engagement_name = Util.null2String(excelParse.getValue("1", i, ey_engagementname_col)).trim(); + String ep = Util.null2String(excelParse.getValue("1", i, ey_ep_col)); + String em = Util.null2String(excelParse.getValue("1", i, ey_em_col)); + String pfma = Util.null2String(excelParse.getValue("1", i, ey_pfma_col)); + String pycode = Util.null2String(excelParse.getValue("1", i, ey_pycode_col)).trim(); + String blocking_level= Util.null2String(excelParse.getValue("1", i, ey_blocking_level_col)).trim(); + new BaseBean().writeLog("pycode==>"+pycode); + + + String pace_link = Util.null2String(excelParse.getValue("1", i, ey_pacelink_col)).trim(); + String local_service_code =Util.null2String(excelParse.getValue("1", i, ey_local_service_code_col)).trim(); + String opprCode =Util.null2String(excelParse.getValue("1", i, ey_oppr_code_col)).trim(); + String mercury_code =Util.null2String(excelParse.getValue("1", i, ey_mercury_code_col)).trim(); + String countryregioncode =Util.null2String(DaoUtils.querySingleVal("select countryregioncode from uf_Codeblockjcdab where bucode=? and oucode=? and mucode=? and smucode=?",bucode, oucode, mucode, smucode)); + String local_global_service_code =DaoUtils.querySingleVal("select global_service_code from uf_service_code where Servicecode=?",local_service_code); + new BaseBean().writeLog("====1、mercury_code===="+mercury_code ); + String mercury_global_service_code =DaoUtils.querySingleVal("select global_service_code from uf_msc_gsc where mercury_service_code=?",mercury_code); + + //1、Excel模版 BU 、OU、MU、SMU校验:是否存在对应codeblock Done + if (opencheckcodeblock.equals("1")) { + new BaseBean().writeLog("====1、opencheckcodeblock.start====" ); + RecordSet recordSet = DaoUtils.executeQuery("select " + + " count(1) as rowcount " + + " from uf_Codeblockjcdab where bucode=? and oucode=? and mucode=? and smucode=?", bucode, oucode, mucode, smucode); + if (recordSet.next()) { + int rowcount = recordSet.getInt("rowcount"); + if (rowcount > 1) { + error.append("数据验证失败:第一个sheet第" + current_row + "行数据的,请确认codeblock是否唯一!").append("
"); + } else if (rowcount == 0) { + error.append("数据验证失败:第一个sheet第" + current_row + "行数据的,未匹配到对应codeblock数据!").append("
"); + } + } + + new BaseBean().writeLog("====1、opencheckcodeblock.end====" ); + } + + //2、Excel模版 BU 、OU、MU、SMU校验:调用业务核心接口 Done + if (opencheckcodeblockByBcp.equals("1")) { + new BaseBean().writeLog("====2、opencheckcodeblockByBcp.start====" ); + boolean flag =eySeconddevUtil.getLegalEffective(bucode,oucode,mucode,smucode); + new BaseBean().writeLog("getLegalEffective===>"+flag); + if(!flag){ + error.append("数据验证失败:第一个sheet第" + current_row + "行数据的,请确认Bu,Ou,Mu,Smu有效性! ").append("
"); + } + new BaseBean().writeLog("====2、opencheckcodeblockByBcp.end====" ); + } + + //3、Excel模版商机校验:国家编号不是MNG,商机id必填 Done + if (opencheckopprCode.equals("1") ) { + new BaseBean().writeLog("====3、opencheckopprCode.start====" ); + new BaseBean().writeLog("====3、countryregioncode===="+countryregioncode ); + if(StringUtils.isNotBlank(countryregioncode)){ + if( !countryregioncode.equals("MNG") && opprCode.equals("")){ + error.append("数据验证失败:第一个sheet第" + current_row + "行数据的,商机id必填! ").append("
"); + } + } + + new BaseBean().writeLog("====3、opencheckopprCode.end====" ); + } + + //4、Excel模版Client_id校验 Done + if (opencheckcustom.equals("1")) { + new BaseBean().writeLog("====4、opencheckcustom.start====" ); + Map custominfo = eySeconddevUtil.getCustomInfo(client_id); + String code = Util.null2String((String)custominfo.get("code")); + new BaseBean().writeLog("getCustomInfo===>"+code); + if (!code.equals("100")) { + //return "数据验证失败:第一个sheet第"+current_row+"行数据的,请确认客户中心系统中已存在该客户!"; + error.append("数据验证失败:第一个sheet第" + current_row + "行数据的,请确认客户中心系统中已存在该客户! ") + .append("
"); + } + new BaseBean().writeLog("====4、opencheckcustom.end====" ); + } + + //5、Excel模版Client_id,商机id,PACE_ID(截取PACE_link) 校验项 :前置条件:国家编号不是MNG, + // 调用商机接口传入Client_id,商机id,PACE_ID 是否有效,有效返回IsConfidential Done + if (opencheckconfidential.equals("1")) { + new BaseBean().writeLog("====5、opencheckconfidential.start====" ); + String pace_id =""; + if(StringUtils.isNotBlank(pace_link)){ + int beginindex =pace_link.lastIndexOf("Assessment/")+11; + String endstr =pace_link.substring(beginindex,pace_link.length()); + int endindex = endstr.lastIndexOf("/"); + pace_id =pace_link.substring(beginindex,beginindex+endindex); + new BaseBean().writeLog("ModeExpandForExtCodeImport,pace_id==>"+pace_id); + } + Map result =eySeconddevUtil.getConfidentialInfo(opprCode,pace_id,client_id); + String errstr =Util.null2String(result.get("errorstr")); + if(StringUtils.isNotBlank(errstr)){ + error.append("数据验证失败:第一个sheet第" + current_row + "行数据,请确认"+errstr.substring(0,errstr.length()-1)+"等问题! ") + .append("
"); + } + new BaseBean().writeLog("====5、opencheckconfidential.end====" ); + } + + //6、Excel模版”PY_Code” 校验: PY code 历史上是否存在对应的.engagement_code Done + if (opencheckpycode.equals("1")) { + new BaseBean().writeLog("====6、opencheckpycode.start====" ); + new BaseBean().writeLog("====6、opencheckpycode.pycode===="+pycode ); + if(StringUtils.isNotBlank(pycode)){ + RecordSet rs2 = new RecordSet(); + rs2.executeQuery("select id from uf_xmjbxxjmbd where engagement_code=?", pycode); + if (!rs2.next()) { + error.append("数据验证失败:第一个sheet第" + current_row + "行数据的,该项目PY_CODE未关联! ").append("
"); + } + } + new BaseBean().writeLog("====6、opencheckpycode.end====" ); + } + + //7、Excel模版“本地服务编码”校验:uf_service_code.Servicecode 是否存在 Done + if (openchecklocalservicecode.equals("1")) { + new BaseBean().writeLog("====7、openchecklocalservicecode.start====" ); + RecordSet rs2 = new RecordSet(); + new BaseBean().writeLog("====7、openchecklocalservicecode.local_service_code====" +local_service_code); + rs2.executeQuery("select id from uf_service_code where Servicecode=? ",local_service_code); + if(!rs2.next()){ + error.append("数据验证失败:第一个sheet第" + current_row + "行数据的,请确认本地服务编码是否有效! ").append("
"); + } + new BaseBean().writeLog("====7、openchecklocalservicecode.end====" ); + } + + //8、Excel模版“计划编号”校验项 ,根据“计划来源”,调用CCT&MMT或者SmartHub接口是否存在 Done + if (opencheckbudget.equals("1")) { + new BaseBean().writeLog("==8、opencheckbudget。start=="); + Map budgetinfo = new HashMap (); + new BaseBean().writeLog("==plan_source=="+plan_source); + if(!(plan_source.equals("CCT") || plan_source.equals("MMT") || plan_source.equals("SmartHub") )){ + error.append("数据验证失败:第一个sheet第" + current_row + "行数据的,计划来源填写错误只允许填写CCT、MMT、SmartHub!").append("
"); + } + if (plan_source.equals("CCT") || plan_source.equals("MMT")) { + budgetinfo = eySeconddevUtil.getBudgetInfo("mmtplandetail", budget_version_id); + } else { + budgetinfo = eySeconddevUtil.getBudgetInfo("smarthubbudgetdetail", budget_version_id); + } + new BaseBean().writeLog("==budgetinfo=="+ JSON.toJSONString(budgetinfo)); + if (budgetinfo.isEmpty() || budgetinfo==null) { + error.append("数据验证失败:第一个sheet第" + current_row + "行数据的,请确认预算系统中是否存在该预算!").append("
"); + } + new BaseBean().writeLog("==8、opencheckbudget。end=="); + } + + //9、Excel模版GPN是否存在 Done + if (opencheckgpn.equals("1")) { + + new BaseBean().writeLog("==9、opencheckgpn。start=="); + new BaseBean().writeLog("em==>"+em); + new BaseBean().writeLog("ep==>"+ep); + new BaseBean().writeLog("pfma==>"+pfma); + + if (StringUtils.isNotBlank(ep)) { + RecordSet recordSet=new RecordSet(); + recordSet.executeQuery("select id from hrmresource where workcode=?",ep); + if(!recordSet.next()){ + error.append("数据验证失败:第一个sheet第" + current_row + "行数据的,请确认EP的GPN不存在系统中!").append("
"); + } + } + + if (StringUtils.isNotBlank(em)) { + RecordSet recordSet=new RecordSet(); + recordSet.executeQuery("select id from hrmresource where workcode=?",em); + if(!recordSet.next()){ + error.append("数据验证失败:第一个sheet第" + current_row + "行数据的,请确认EP的GPN不存在系统中!").append("
"); + } + } + + if (StringUtils.isNotBlank(pfma)) { + RecordSet recordSet=new RecordSet(); + recordSet.executeQuery("select id from hrmresource where workcode=?",pfma); + if(!recordSet.next()){ + error.append("数据验证失败:第一个sheet第" + current_row + "行数据的,请确认PFMA的GPN不存在系统中!").append("
"); + } + } + new BaseBean().writeLog("==9、opencheckgpn。end=="); + } + + //10、mercury_service_code校验 Done + if(opencheckmercury.equals("1")){ + new BaseBean().writeLog("==10、opencheckmercury。start=="); + new BaseBean().writeLog("====10、mercury_global_service_code===="+mercury_global_service_code ); + new BaseBean().writeLog("====10、local_global_service_code===="+local_global_service_code ); + if(!mercury_global_service_code.equals(local_global_service_code)){ + error.append("数据验证失败:第一个sheet第" + current_row + "行数据的,请确认MercuryCode与global_service_code不匹配!").append("
"); + } + new BaseBean().writeLog("==10、opencheckmercury。end=="); + } + + + //11、Excel的项目名称 Done + if (opencheckengagementname.equals("1")) { + new BaseBean().writeLog("==11、opencheckengagementname。start=="); + new BaseBean().writeLog("==11、opencheckengagementname。engagement_name=="+engagement_name); + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery("select " + + " servicelinecode, subservicelinecode " + + " from uf_Codeblockjcdab where bucode=? and oucode=? and mucode=? and smucode=?", bucode, oucode, mucode, smucode); + if(recordSet.next()){ + String servicelinecode =Util.null2String(recordSet.getString("servicelinecode")); + String subservicelinecode =Util.null2String(recordSet.getString("subservicelinecode")); + if(servicelinecode.equals("01") && subservicelinecode.equals("0101")){ //serviceline=01和subserviceline=0101时,触发项目名称校验 + //检验 :0~3位 必须是AUT 或者 INT + boolean flag = EYSeconddevUtil.vaildateImportEnagementName(engagement_name,local_global_service_code); + String datestr = engagement_name.substring(3, 10); + if(!flag){ + error.append("数据验证失败:第一个sheet第" + current_row + "行数据的,请确认前3位是否合规! ").append("
"); + }else if(!DATE_PATTERN.matcher(datestr).matches()){ //检验:4~10位 必须是YYYY-MM + error.append("数据验证失败:第一个sheet第" + current_row + "行数据的,请确认4到10位是否日期字段,如:2001-01! ").append("
"); + + } + } + } + new BaseBean().writeLog("==11、opencheckengagementname。end=="); + } + + //12、BlockLevel Done + if(opencheckblocklevel.equals("1")){ + new BaseBean().writeLog("==12、opencheckblocklevel.start=="); + if (StringUtils.isNotBlank(ep)) { + RecordSet recordSet=new RecordSet(); + recordSet.executeQuery("select id from uf_bl where engblocklevel =?",blocking_level); + if(!recordSet.next()){ + error.append("数据验证失败:第一个sheet第" + current_row + "行数据的,blocking_level填写有误请检查!").append("
"); + } + } + new BaseBean().writeLog("==12、opencheckblocklevel.end=="); + } + // 12、校验项目EP Rank + if (!"".equals(ep) && !eySeconddevUtil.validateEngagementRoleRank(ep,"1","0")) { + error.append("数据验证失败:第一个sheet第" + current_row + "行数据的,EP填写有误请检查!").append("
"); + } + // 13、校验项目EM Rank + if (!"".equals(em) && !eySeconddevUtil.validateEngagementRoleRank(em,"1","0")) { + error.append("数据验证失败:第一个sheet第" + current_row + "行数据的,EM填写有误请检查!").append("
"); + } + } + } + + String returnstr =error.toString(); + new BaseBean().writeLog("returnstr===>"+returnstr); + return returnstr; + } +} diff --git a/src/main/java/weaver/formmode/interfaces/impl/ey/zhang/ImportNtoOValidateTemplate.java b/src/main/java/weaver/formmode/interfaces/impl/ey/zhang/ImportNtoOValidateTemplate.java new file mode 100644 index 0000000..cf859ba --- /dev/null +++ b/src/main/java/weaver/formmode/interfaces/impl/ey/zhang/ImportNtoOValidateTemplate.java @@ -0,0 +1,307 @@ +package weaver.formmode.interfaces.impl.ey.zhang; + +import org.apache.commons.lang.StringUtils; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.Workbook; +import weaver.conn.RecordSet; +import weaver.file.ExcelParseForPOI; +import weaver.formmode.interfaces.ImportPreInterfaceForPOIAction; +import weaver.general.BaseBean; +import weaver.general.Util; +import weaver.hrm.User; +import weaver.seconddev.ey.zhangm.didi.util.DaoUtils; +import weaver.seconddev.ey.zhangm.util.EYSeconddevUtil; + +import java.util.HashMap; +import java.util.Map; +import java.util.regex.Pattern; + + +/** + * @Description + * @Author miao.zhang + * @Version V1.0.0 + * @Since 1.0 + * @Date 6/22/23 + */ +public class ImportNtoOValidateTemplate implements ImportPreInterfaceForPOIAction { + + + @Override + public String checkImportData(Map param, User user, ExcelParseForPOI excelParse) { + + EYSeconddevUtil eySeconddevUtil = new EYSeconddevUtil(); + + + String ssids="ey_nto_clentid_col,ey_nto_budget_version_col,ey_nto_bucode_col,ey_nto_oucode_col,ey_nto_mucode_col,ey_nto_smucode_col,ey_nto_engagementname_col,ey_nto_ep_col,ey_nto_em_col,ey_nto_pfma_col,"; + ssids=ssids+"ey_nto_engagementcode_col,ey_nto_mercurycode_col,ey_nto_pacelink_col,opencheckntooengagementstatus,"; + ssids=ssids+"opencheckntooservicecode,opencheckntooserviceline,opencheckntopycode,opencheckntoengagementname,opencheckntocustom,opencheckntocodeblock,opencheckntogpn,"; + ssids=ssids+"opencheckntobudget,opencheckntomercury,opencheckntopaceid"; + Map ey_params_map =eySeconddevUtil.getSystemParamValues(ssids); + + + int ey_clentid_col = Util.getIntValue(ey_params_map.get("ey_nto_clentid_col")); + int budget_version_col = Util.getIntValue(ey_params_map.get("ey_nto_budget_version_col")); + int ey_bucode_col = Util.getIntValue(ey_params_map.get("ey_nto_bucode_col")); + int ey_oucode_col = Util.getIntValue(ey_params_map.get("ey_nto_oucode_col")); + int ey_mucode_col = Util.getIntValue(ey_params_map.get("ey_nto_mucode_col")); + int ey_smucode_col = Util.getIntValue(ey_params_map.get("ey_nto_smucode_col")); + int ey_engagementname_col = Util.getIntValue(ey_params_map.get("ey_nto_engagementname_col")); + int ey_ep_col = Util.getIntValue(ey_params_map.get("ey_nto_ep_col")); + int ey_em_col = Util.getIntValue(ey_params_map.get("ey_nto_em_col")); + int ey_pfma_col = Util.getIntValue(ey_params_map.get("ey_nto_pfma_col")); + int ey_engagementcode_col = Util.getIntValue(ey_params_map.get("ey_nto_engagementcode_col")); + int ey_mercurycode_col = Util.getIntValue(ey_params_map.get("ey_nto_mercurycode_col")); + int ey_pacelink_col = Util.getIntValue(ey_params_map.get("ey_nto_pacelink_col")); + + String opencheckntooengagementstatus = Util.null2String(ey_params_map.get("opencheckntooengagementstatus")); + String opencheckntoservicecode = Util.null2String(ey_params_map.get("opencheckntooservicecode")); + String opencheckntoserviceline = Util.null2String(ey_params_map.get("opencheckntooserviceline")); + String opencheckntopycode = Util.null2String(ey_params_map.get("opencheckntopycode")); + String opencheckntoengagementname = Util.null2String(ey_params_map.get("opencheckntoengagementname")); + String opencheckntocustom = Util.null2String(ey_params_map.get("opencheckntocustom")); + String opencheckntocodeblock= Util.null2String(ey_params_map.get("opencheckntocodeblock")); + String opencheckntogpn= Util.null2String(ey_params_map.get("opencheckntogpn")); + String opencheckntobudget = Util.null2String(ey_params_map.get("opencheckntobudget")); + String opencheckntomercury= Util.null2String(ey_params_map.get("opencheckntomercury")); + String opencheckntopaceid = Util.null2String(ey_params_map.get("opencheckntopaceid")); + + new BaseBean().writeLog("opencheckntooengagementstatus==>" + opencheckntooengagementstatus+",opencheckntoservicecode==>"+opencheckntoservicecode+",opencheckntoserviceline==>"+opencheckntoserviceline); + new BaseBean().writeLog("opencheckntopycode==>" + opencheckntopycode+",opencheckntoengagementname==>"+opencheckntoengagementname+",opencheckntocustom==>"+opencheckntocustom); + new BaseBean().writeLog("opencheckntocodeblock==>" + opencheckntocodeblock+",opencheckntogpn==>"+opencheckntogpn+",opencheckntobudget==>"+opencheckntobudget); + new BaseBean().writeLog("opencheckntomercury==>" + opencheckntomercury+",opencheckntopaceid==>"+opencheckntopaceid); + + + // 获取模块ID + Integer modeId = Util.getIntValue(param.get("modeid").toString()); + //表单id + Integer formId = Util.getIntValue(param.get("formid").toString()); + // 获取当前登录人员ID + Integer userId = user.getUID(); + String sheetname = "1"; + //获取第 sheetindex 个sheet的第row行第col列的单元格的值 (下标都是从1开始) + //String value = excelParse.getValue("1", 2, 2); + Workbook wb = excelParse.getWb(); + Sheet sheet = wb.getSheetAt(Util.getIntValue(sheetname) - 1); + StringBuilder error = new StringBuilder(); + Pattern DATE_PATTERN = Pattern.compile("^\\d{4}-\\d{2}$"); + if (sheet != null) { + int rowSum = sheet.getPhysicalNumberOfRows(); + new BaseBean().writeLog("rowSum==>" + rowSum); + int current_row = 0; + for (int i = 2; i <= rowSum; i++) { + current_row = i - 1; + String client_id = Util.null2String(excelParse.getValue("1", i, ey_clentid_col)); + String budget_version_id = Util.null2String(excelParse.getValue("1", i, budget_version_col)); + String bucode = Util.null2String(excelParse.getValue("1", i, ey_bucode_col)); + String oucode = Util.null2String(excelParse.getValue("1", i, ey_oucode_col)); + String mucode = Util.null2String(excelParse.getValue("1", i, ey_mucode_col)); + String smucode = Util.null2String(excelParse.getValue("1", i, ey_smucode_col)); + String engagement_name = Util.null2String(excelParse.getValue("1", i, ey_engagementname_col)).trim(); + String ep = Util.null2String(excelParse.getValue("1", i, ey_ep_col)); + String em = Util.null2String(excelParse.getValue("1", i, ey_em_col)); + String pfma = Util.null2String(excelParse.getValue("1", i, ey_pfma_col)); + String engagement_code = Util.null2String(excelParse.getValue("1", i, ey_engagementcode_col)).trim(); + String mercury_code = Util.null2String(excelParse.getValue("1", i, ey_mercurycode_col)).trim(); + String pace_link = Util.null2String(excelParse.getValue("1", i, ey_pacelink_col)).trim(); + + RecordSet rs2 = new RecordSet(); + rs2.executeQuery("select engagement_status,local_service_code,global_service_code,service_line,sub_service_line,py_code from uf_xmjbxxjmbd where engagement_code=? ", engagement_code); + if(rs2.next()) { + String local_service_code = Util.null2String(rs2.getString("local_service_code")); + String service_line = Util.null2String(rs2.getString("service_line")); + String global_service_code = Util.null2String(rs2.getString("global_service_code")); + String sub_service_line = Util.null2String(rs2.getString("sub_service_line")); + String temp_py_code = Util.null2String(rs2.getString("py_code")); + String engagement_status = Util.null2String(rs2.getString("engagement_status")); + //String local_global_service_code =DaoUtils.querySingleVal("select global_service_code from uf_service_code where Servicecode=?",local_service_code); + String mercury_global_service_code = DaoUtils.querySingleVal("select global_service_code from uf_msc_gsc where mercury_service_code=?", mercury_code); + String old_pace_id = DaoUtils.querySingleVal("select pace_id from uf_xmjbxxjmbd where engagement_code=?", temp_py_code); + String py_engagement_name = DaoUtils.querySingleVal("select engagement_name from uf_xmjbxxjmbd where engagement_code=?", temp_py_code); + + //1、校验该项目编号在项目档案中的 通过engcode查询,项目状态为N + if (opencheckntooengagementstatus.equals("1")) { + new BaseBean().writeLog("====1、opencheckntooengagementstatus.start===="); + new BaseBean().writeLog("engagement_status==>" + engagement_status); + if (!engagement_status.equals("N")) { + error.append("数据验证失败:第一个sheet第" + current_row + "行数据的,原项目状态不为N! ").append("
"); + } + new BaseBean().writeLog("====1、opencheckntooengagementstatus.end===="); + } + + //2、校验GSC为031、035。通过engcode查询,GSC为GSC =031、GSC=035 ,local_serivce_code=03500 or local_serivce_code=03100 + if (opencheckntoservicecode.equals("1")) { + new BaseBean().writeLog("====2、opencheckntoservicecode.start===="); + new BaseBean().writeLog("local_service_code==>" + local_service_code); + if (!local_service_code.equals("03500") && !local_service_code.equals("03100")) { + error.append("数据验证失败:第一个sheet第" + current_row + "行数据的,原项目本地服务编码是03500或03100! ").append("
"); + } + new BaseBean().writeLog("====2、opencheckntoservicecode.end===="); + } + //3、原项目业务线必须是ASU! + if (opencheckntoserviceline.equals("1")) { + new BaseBean().writeLog("====3、opencheckntoserviceline.start===="); + new BaseBean().writeLog("====3、service_line====" + service_line); + new BaseBean().writeLog("====3、sub_service_line====" + sub_service_line); + if (!(service_line.equals("01") && sub_service_line.equals("0101"))) { + error.append("数据验证失败:第一个sheet第" + current_row + "行数据的,原项目业务线必须是ASU,子业务线是Audit! ").append("
"); + } + new BaseBean().writeLog("====3、opencheckntoserviceline.end===="); + } + + //4、校该项目编号在项目档案中关联的PY Code不能为空 + if (opencheckntopycode.equals("1")) { + new BaseBean().writeLog("====4、opencheckntopycode.start===="); + new BaseBean().writeLog("====4、opencheckntopycode.temp_py_code====" + temp_py_code); + if (temp_py_code.equals("")) { + error.append("数据验证失败:第一个sheet第" + current_row + "行数据的,项目原PY_CODE不能为空! ").append("
"); + } + new BaseBean().writeLog("====4、opencheckntopycode.end===="); + } + + //5、Excel的项目名称 Done + if (opencheckntoengagementname.equals("1")) { + new BaseBean().writeLog("====5、opencheckntoengagementname.start===="); + if (engagement_name.equals(py_engagement_name)) { + error.append("数据验证失败:第一个sheet第" + current_row + "行数据的,项目名称不合规,请确认项目名称是否重复或名称格式是否错误,正确格式如:AUD2023-01XXXXX! ").append("
"); + }else if(engagement_name.length()<=10){ + error.append("数据验证失败:第一个sheet第" + current_row + "行数据的,项目名称不合规,请确认项目名称是否重复或名称格式是否错误,正确格式如:AUD2023-01XXXXX! ").append("
"); + }else if (engagement_name.length()>10 ){ + String datestr = engagement_name.substring(3, 10); + //String perfix = engagement_name.substring(0, 3); + boolean flag = EYSeconddevUtil.vaildateImportEnagementName(engagement_name,global_service_code); + //检验:4~10位 必须是YYYY-MM + if (!DATE_PATTERN.matcher(datestr).matches()) { + error.append("数据验证失败:第一个sheet第" + current_row + "行数据的,项目名称不合规,请确认项目名称是否重复或名称格式是否错误,正确格式如:AUD2023-01XXXXX! ").append("
"); + }else if(!flag) { //检验 :0~3位 必须是AUT 或者 INT + error.append("数据验证失败:第一个sheet第" + current_row + "行数据的,项目名称不合规,请确认项目名称是否重复或名称格式是否错误,正确格式如:AUD2023-01XXXXX! ").append("
"); + } + }else if (engagement_name.length()<=10){ + error.append("数据验证失败:第一个sheet第" + current_row + "行数据的,项目名称不合规,请确认项目名称是否重复或名称格式是否错误,正确格式如:AUD2023-01XXXXX! ").append("
"); + } + + new BaseBean().writeLog("====5、opencheckntoengagementname.end===="); + } + + //6、客户信息 Done + if (opencheckntocustom.equals("1")) { + new BaseBean().writeLog("====6、opencheckntocustom.start===="); + Map custominfo = eySeconddevUtil.getCustomInfo(client_id); + String code = Util.null2String(custominfo.get("code")); + if (!code.equals("100")) { + //return "数据验证失败:第一个sheet第"+current_row+"行数据的,请确认客户中心系统中已存在该客户!"; + error.append("数据验证失败:第一个sheet第" + current_row + "行数据的,请确认客户中心系统中已存在该客户! ") + .append("
"); + } + new BaseBean().writeLog("====6、opencheckntocustom.end===="); + } + + //7、pace_id校验 + if (opencheckntopaceid.equals("1")) { + new BaseBean().writeLog("====7、opencheckntopaceid.start===="); + String pace_id = ""; + if (StringUtils.isNotBlank(pace_link)) { + int beginindex = pace_link.lastIndexOf("Assessment/") + 11; + String endstr = pace_link.substring(beginindex, pace_link.length()); + int endindex = endstr.lastIndexOf("/"); + pace_id = pace_link.substring(beginindex, beginindex + endindex); + new BaseBean().writeLog("ModeExpandForExtCodeImport,pace_id==>" + pace_id); + } + if (pace_id.equals(old_pace_id)) { + error.append("数据验证失败:第一个sheet第" + current_row + "行数据的,未创建新的PACE!").append("
"); + } + + new BaseBean().writeLog("====7、opencheckntopaceid.end===="); + } + + //8、CodeBlock信息 Done + if (opencheckntocodeblock.equals("1")) { + new BaseBean().writeLog("====8、opencheckntocodeblock.start===="); + RecordSet recordSet = DaoUtils.executeQuery("select " + + " id " + + " from uf_Codeblockjcdab where bucode=? and oucode=? and mucode=? and smucode=?", bucode, oucode, mucode, smucode); + if (!recordSet.next()) { + error.append("数据验证失败:第一个sheet第" + current_row + "行数据的,未匹配到对应codeblock数据!").append("
"); + } + new BaseBean().writeLog("====8、opencheckntocodeblock.end===="); + } + + //9、GPN是否存在 Done + if (opencheckntogpn.equals("1")) { + new BaseBean().writeLog("====9、opencheckntogpn.start===="); + new BaseBean().writeLog("em==>" + em); + new BaseBean().writeLog("ep==>" + ep); + new BaseBean().writeLog("pfma==>" + pfma); + + if (StringUtils.isNotBlank(ep)) { + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery("select id from hrmresource where workcode=?", ep); + if (!recordSet.next()) { + error.append("数据验证失败:第一个sheet第" + current_row + "行数据的,请确认EP的GPN不存在系统中!").append("
"); + } + } + + if (StringUtils.isNotBlank(em)) { + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery("select id from hrmresource where workcode=?", em); + if (!recordSet.next()) { + error.append("数据验证失败:第一个sheet第" + current_row + "行数据的,请确认EP的GPN不存在系统中!").append("
"); + } + } + + if (StringUtils.isNotBlank(pfma)) { + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery("select id from hrmresource where workcode=?", pfma); + if (!recordSet.next()) { + error.append("数据验证失败:第一个sheet第" + current_row + "行数据的,请确认PFMA的GPN不存在系统中!").append("
"); + } + } + new BaseBean().writeLog("====9、opencheckntogpn.end===="); + } + + // 10、SmartHub检查 + if (opencheckntobudget.equals("1")) { + new BaseBean().writeLog("====10、opencheckntobudget.start===="); + Map budgetinfo = new HashMap (); + budgetinfo = eySeconddevUtil.getBudgetInfo("smarthubbudgetdetail", budget_version_id); + //} + if (budgetinfo.size() == 0) { + error.append("数据验证失败:第一个sheet第" + current_row + "行数据的,请确认预算系统中已存在该预算!").append("
"); + } + new BaseBean().writeLog("====10、opencheckntobudget.end===="); + } + +// 11、mercury_service_code校验 Done + if (opencheckntomercury.equals("1")) { + new BaseBean().writeLog("====11、opencheckntomercury.start===="); + new BaseBean().writeLog("global_service_code==>" + global_service_code); + new BaseBean().writeLog("mercury_global_service_code==>" + mercury_global_service_code); + if (!(mercury_global_service_code.equals(global_service_code))) { + error.append("数据验证失败:第一个sheet第" + current_row + "行数据的,请确认Mercury Service Code与Global Service Code不匹配!").append("
"); + } + new BaseBean().writeLog("====11、opencheckntomercury.end===="); + } + + }else{ + error.append("数据验证失败:第一个sheet第" + current_row + "行数据的,请确认Engagement Code不存在!").append("
"); + + } + // 12、校验项目EP Rank + if (!"".equals(ep) && !eySeconddevUtil.validateEngagementRoleRank(ep,"1","0")) { + error.append("数据验证失败:第一个sheet第" + current_row + "行数据的,EP填写有误请检查!").append("
"); + } + // 13、校验项目EM Rank + if (!"".equals(em) && !eySeconddevUtil.validateEngagementRoleRank(em,"1","0")) { + error.append("数据验证失败:第一个sheet第" + current_row + "行数据的,EM填写有误请检查!").append("
"); + } + } + } + if (error.toString().equals("")) { + return ""; + } else { + return error.toString(); + } + + + } +} diff --git a/src/main/java/weaver/seconddev/ey/zhangm/didi/annotation/DaoField.java b/src/main/java/weaver/seconddev/ey/zhangm/didi/annotation/DaoField.java new file mode 100644 index 0000000..389e827 --- /dev/null +++ b/src/main/java/weaver/seconddev/ey/zhangm/didi/annotation/DaoField.java @@ -0,0 +1,20 @@ +package weaver.seconddev.ey.zhangm.didi.annotation; + +/** + * @Description + * @Author miao.zhang + * @Version V1.0.0 + * @Since 1.0 + * @Date 11/2/22 + */ +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + + +@Target({ElementType.FIELD}) +@Retention(RetentionPolicy.RUNTIME) +public @interface DaoField { + boolean value() default true; +} diff --git a/src/main/java/weaver/seconddev/ey/zhangm/didi/annotation/DaoTableField.java b/src/main/java/weaver/seconddev/ey/zhangm/didi/annotation/DaoTableField.java new file mode 100644 index 0000000..e710c47 --- /dev/null +++ b/src/main/java/weaver/seconddev/ey/zhangm/didi/annotation/DaoTableField.java @@ -0,0 +1,18 @@ +package weaver.seconddev.ey.zhangm.didi.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +/** + * @Description + * @Author miao.zhang + * @Version V1.0.0 + * @Since 1.0 + * @Date 11/2/22 + */ +@Target({ElementType.FIELD}) +@Retention(RetentionPolicy.RUNTIME) +public @interface DaoTableField { + String value() default ""; +} diff --git a/src/main/java/weaver/seconddev/ey/zhangm/didi/entity/DidiInvoiceOrder.java b/src/main/java/weaver/seconddev/ey/zhangm/didi/entity/DidiInvoiceOrder.java new file mode 100644 index 0000000..54d7bbf --- /dev/null +++ b/src/main/java/weaver/seconddev/ey/zhangm/didi/entity/DidiInvoiceOrder.java @@ -0,0 +1,55 @@ +package weaver.seconddev.ey.zhangm.didi.entity; + +import org.jetbrains.annotations.NotNull; + +/** + * @Description + * @Author miao.zhang + * @Version V1.0.0 + * @Since 1.0 + * @Date 12/9/22 + */ +public class DidiInvoiceOrder implements Comparable { + + private String orderid; + private String businessunit; + private String amount; + + @Override + public int compareTo(@NotNull DidiInvoiceOrder o) { + return getBusinessunit().compareTo(o.getBusinessunit()); + } + + @Override + public String toString() { + return "DidiInvoiceOrder{" + + "orderid='" + orderid + '\'' + + ", businessunit='" + businessunit + '\'' + + ", account='" + amount + '\'' + + '}'; + } + + public String getOrderid() { + return orderid; + } + + public void setOrderid(String orderid) { + this.orderid = orderid; + } + + public String getBusinessunit() { + return businessunit; + } + + public void setBusinessunit(String businessunit) { + this.businessunit = businessunit; + } + + public String getAmount() { + return amount; + } + + public void setAmount(String amount) { + this.amount = amount; + } +} diff --git a/src/main/java/weaver/seconddev/ey/zhangm/didi/entity/DidiOrder.java b/src/main/java/weaver/seconddev/ey/zhangm/didi/entity/DidiOrder.java new file mode 100644 index 0000000..fb89b7a --- /dev/null +++ b/src/main/java/weaver/seconddev/ey/zhangm/didi/entity/DidiOrder.java @@ -0,0 +1,543 @@ +package weaver.seconddev.ey.zhangm.didi.entity; + +/** + * @Description + * @Author miao.zhang + * @Version V1.0.0 + * @Since 1.0 + * @Date 11/2/22 + */ +public class DidiOrder { + private String order_id; + private String create_time; + private String use_car_type; + private String require_level; + private String city; + private String city_name; + private String start_name; + private String end_name; + private String actual_start_name; + private String actual_end_name; + private String actual_flat; + private String actual_flng; + private String actual_tlat; + private String actual_tlng; + private String departure_time; + private String finish_time; + private String status; + private String pay_type; + private String member_id; + private String pay_time; + private String normal_distance; + private String total_price; + private String actual_price; + private String refund_time; + private String refund_price; + private String company_pay; + private String company_card_pay; + private String personal_pay; + private String company_real_pay; + private String company_card_real_pay; + private String personal_real_pay; + private String company_real_refund; + private String company_card_real_refund; + private String personal_real_refund; + private String is_invoice; + private String call_phone; + private String passenger_phone; + private String passenger_name; + private String budget_center_id; + private String budget_item_id; + private String use_car_config_id; + private String order_source; + private String is_carpool; + private String encrypted_info; + private String approval_id; + private String out_approval_id; + private String callback_info; + private String engcode; + + @Override + public String toString() { + return "DidiOrder{" + + "order_id='" + order_id + '\'' + + ", create_time='" + create_time + '\'' + + ", use_car_type='" + use_car_type + '\'' + + ", require_level='" + require_level + '\'' + + ", city='" + city + '\'' + + ", city_name='" + city_name + '\'' + + ", start_name='" + start_name + '\'' + + ", end_name='" + end_name + '\'' + + ", actual_start_name='" + actual_start_name + '\'' + + ", actual_end_name='" + actual_end_name + '\'' + + ", actual_flat='" + actual_flat + '\'' + + ", actual_flng='" + actual_flng + '\'' + + ", actual_tlat='" + actual_tlat + '\'' + + ", actual_tlng='" + actual_tlng + '\'' + + ", departure_time='" + departure_time + '\'' + + ", finish_time='" + finish_time + '\'' + + ", status='" + status + '\'' + + ", pay_type='" + pay_type + '\'' + + ", member_id='" + member_id + '\'' + + ", pay_time='" + pay_time + '\'' + + ", normal_distance='" + normal_distance + '\'' + + ", total_price='" + total_price + '\'' + + ", actual_price='" + actual_price + '\'' + + ", refund_time='" + refund_time + '\'' + + ", refund_price='" + refund_price + '\'' + + ", company_pay='" + company_pay + '\'' + + ", company_card_pay='" + company_card_pay + '\'' + + ", personal_pay='" + personal_pay + '\'' + + ", company_real_pay='" + company_real_pay + '\'' + + ", company_card_real_pay='" + company_card_real_pay + '\'' + + ", personal_real_pay='" + personal_real_pay + '\'' + + ", company_real_refund='" + company_real_refund + '\'' + + ", company_card_real_refund='" + company_card_real_refund + '\'' + + ", personal_real_refund='" + personal_real_refund + '\'' + + ", is_invoice='" + is_invoice + '\'' + + ", call_phone='" + call_phone + '\'' + + ", passenger_phone='" + passenger_phone + '\'' + + ", passenger_name='" + passenger_name + '\'' + + ", budget_center_id='" + budget_center_id + '\'' + + ", budget_item_id='" + budget_item_id + '\'' + + ", use_car_config_id='" + use_car_config_id + '\'' + + ", order_source='" + order_source + '\'' + + ", is_carpool='" + is_carpool + '\'' + + ", encrypted_info='" + encrypted_info + '\'' + + ", approval_id='" + approval_id + '\'' + + ", out_approval_id='" + out_approval_id + '\'' + + ", callback_info='" + callback_info + '\'' + + ", engcode='" + engcode + '\'' + + '}'; + } + + public String getOrder_id() { + return order_id; + } + + public DidiOrder setOrder_id(String order_id) { + this.order_id = order_id; + return this; + } + + public String getCreate_time() { + return create_time; + } + + public DidiOrder setCreate_time(String create_time) { + this.create_time = create_time; + return this; + } + + public String getUse_car_type() { + return use_car_type; + } + + public DidiOrder setUse_car_type(String use_car_type) { + this.use_car_type = use_car_type; + return this; + } + + public String getRequire_level() { + return require_level; + } + + public DidiOrder setRequire_level(String require_level) { + this.require_level = require_level; + return this; + } + + public String getCity() { + return city; + } + + public DidiOrder setCity(String city) { + this.city = city; + return this; + } + + public String getCity_name() { + return city_name; + } + + public DidiOrder setCity_name(String city_name) { + this.city_name = city_name; + return this; + } + + public String getStart_name() { + return start_name; + } + + public DidiOrder setStart_name(String start_name) { + this.start_name = start_name; + return this; + } + + public String getEnd_name() { + return end_name; + } + + public DidiOrder setEnd_name(String end_name) { + this.end_name = end_name; + return this; + } + + public String getActual_start_name() { + return actual_start_name; + } + + public DidiOrder setActual_start_name(String actual_start_name) { + this.actual_start_name = actual_start_name; + return this; + } + + public String getActual_end_name() { + return actual_end_name; + } + + public DidiOrder setActual_end_name(String actual_end_name) { + this.actual_end_name = actual_end_name; + return this; + } + + public String getActual_flat() { + return actual_flat; + } + + public DidiOrder setActual_flat(String actual_flat) { + this.actual_flat = actual_flat; + return this; + } + + public String getActual_flng() { + return actual_flng; + } + + public DidiOrder setActual_flng(String actual_flng) { + this.actual_flng = actual_flng; + return this; + } + + public String getActual_tlat() { + return actual_tlat; + } + + public DidiOrder setActual_tlat(String actual_tlat) { + this.actual_tlat = actual_tlat; + return this; + } + + public String getActual_tlng() { + return actual_tlng; + } + + public DidiOrder setActual_tlng(String actual_tlng) { + this.actual_tlng = actual_tlng; + return this; + } + + public String getDeparture_time() { + return departure_time; + } + + public DidiOrder setDeparture_time(String departure_time) { + this.departure_time = departure_time; + return this; + } + + public String getFinish_time() { + return finish_time; + } + + public DidiOrder setFinish_time(String finish_time) { + this.finish_time = finish_time; + return this; + } + + public String getStatus() { + return status; + } + + public DidiOrder setStatus(String status) { + this.status = status; + return this; + } + + public String getPay_type() { + return pay_type; + } + + public DidiOrder setPay_type(String pay_type) { + this.pay_type = pay_type; + return this; + } + + public String getMember_id() { + return member_id; + } + + public DidiOrder setMember_id(String member_id) { + this.member_id = member_id; + return this; + } + + public String getPay_time() { + return pay_time; + } + + public DidiOrder setPay_time(String pay_time) { + this.pay_time = pay_time; + return this; + } + + public String getNormal_distance() { + return normal_distance; + } + + public DidiOrder setNormal_distance(String normal_distance) { + this.normal_distance = normal_distance; + return this; + } + + public String getTotal_price() { + return total_price; + } + + public DidiOrder setTotal_price(String total_price) { + this.total_price = total_price; + return this; + } + + public String getActual_price() { + return actual_price; + } + + public DidiOrder setActual_price(String actual_price) { + this.actual_price = actual_price; + return this; + } + + public String getRefund_time() { + return refund_time; + } + + public DidiOrder setRefund_time(String refund_time) { + this.refund_time = refund_time; + return this; + } + + public String getRefund_price() { + return refund_price; + } + + public DidiOrder setRefund_price(String refund_price) { + this.refund_price = refund_price; + return this; + } + + public String getCompany_pay() { + return company_pay; + } + + public DidiOrder setCompany_pay(String company_pay) { + this.company_pay = company_pay; + return this; + } + + public String getCompany_card_pay() { + return company_card_pay; + } + + public DidiOrder setCompany_card_pay(String company_card_pay) { + this.company_card_pay = company_card_pay; + return this; + } + + public String getPersonal_pay() { + return personal_pay; + } + + public DidiOrder setPersonal_pay(String personal_pay) { + this.personal_pay = personal_pay; + return this; + } + + public String getCompany_real_pay() { + return company_real_pay; + } + + public DidiOrder setCompany_real_pay(String company_real_pay) { + this.company_real_pay = company_real_pay; + return this; + } + + public String getCompany_card_real_pay() { + return company_card_real_pay; + } + + public DidiOrder setCompany_card_real_pay(String company_card_real_pay) { + this.company_card_real_pay = company_card_real_pay; + return this; + } + + public String getPersonal_real_pay() { + return personal_real_pay; + } + + public DidiOrder setPersonal_real_pay(String personal_real_pay) { + this.personal_real_pay = personal_real_pay; + return this; + } + + public String getCompany_real_refund() { + return company_real_refund; + } + + public DidiOrder setCompany_real_refund(String company_real_refund) { + this.company_real_refund = company_real_refund; + return this; + } + + public String getCompany_card_real_refund() { + return company_card_real_refund; + } + + public DidiOrder setCompany_card_real_refund(String company_card_real_refund) { + this.company_card_real_refund = company_card_real_refund; + return this; + } + + public String getPersonal_real_refund() { + return personal_real_refund; + } + + public DidiOrder setPersonal_real_refund(String personal_real_refund) { + this.personal_real_refund = personal_real_refund; + return this; + } + + public String getIs_invoice() { + return is_invoice; + } + + public DidiOrder setIs_invoice(String is_invoice) { + this.is_invoice = is_invoice; + return this; + } + + public String getCall_phone() { + return call_phone; + } + + public DidiOrder setCall_phone(String call_phone) { + this.call_phone = call_phone; + return this; + } + + public String getPassenger_phone() { + return passenger_phone; + } + + public DidiOrder setPassenger_phone(String passenger_phone) { + this.passenger_phone = passenger_phone; + return this; + } + + public String getPassenger_name() { + return passenger_name; + } + + public DidiOrder setPassenger_name(String passenger_name) { + this.passenger_name = passenger_name; + return this; + } + + public String getBudget_center_id() { + return budget_center_id; + } + + public DidiOrder setBudget_center_id(String budget_center_id) { + this.budget_center_id = budget_center_id; + return this; + } + + public String getBudget_item_id() { + return budget_item_id; + } + + public DidiOrder setBudget_item_id(String budget_item_id) { + this.budget_item_id = budget_item_id; + return this; + } + + public String getUse_car_config_id() { + return use_car_config_id; + } + + public DidiOrder setUse_car_config_id(String use_car_config_id) { + this.use_car_config_id = use_car_config_id; + return this; + } + + public String getOrder_source() { + return order_source; + } + + public DidiOrder setOrder_source(String order_source) { + this.order_source = order_source; + return this; + } + + public String getIs_carpool() { + return is_carpool; + } + + public DidiOrder setIs_carpool(String is_carpool) { + this.is_carpool = is_carpool; + return this; + } + + public String getEncrypted_info() { + return encrypted_info; + } + + public DidiOrder setEncrypted_info(String encrypted_info) { + this.encrypted_info = encrypted_info; + return this; + } + + public String getApproval_id() { + return approval_id; + } + + public DidiOrder setApproval_id(String approval_id) { + this.approval_id = approval_id; + return this; + } + + public String getOut_approval_id() { + return out_approval_id; + } + + public DidiOrder setOut_approval_id(String out_approval_id) { + this.out_approval_id = out_approval_id; + return this; + } + + public String getCallback_info() { + return callback_info; + } + + public void setCallback_info(String callback_info) { + this.callback_info = callback_info; + } + + public String getEngcode() { + return engcode; + } + + public void setEngcode(String engcode) { + this.engcode = engcode; + } +} diff --git a/src/main/java/weaver/seconddev/ey/zhangm/didi/entity/DidiQualification.java b/src/main/java/weaver/seconddev/ey/zhangm/didi/entity/DidiQualification.java new file mode 100644 index 0000000..7cf35ee --- /dev/null +++ b/src/main/java/weaver/seconddev/ey/zhangm/didi/entity/DidiQualification.java @@ -0,0 +1,109 @@ +package weaver.seconddev.ey.zhangm.didi.entity; + +/** + * @Description + * @Author miao.zhang + * @Version V1.0.0 + * @Since 1.0 + * @Date 11/29/22 + */ +public class DidiQualification { + + private String id; + private String company_id; + private String invoice_title; + private String tax_registration_number; + private String registered_address; + private String telephone; + private String deposit_bank; + private String bank_account; + private String subcompanyid; + + + @Override + public String toString() { + return "DidiQualification{" + + "pkid='" + id + '\'' + + ", company_id='" + company_id + '\'' + + ", invoice_title='" + invoice_title + '\'' + + ", tax_registration_number='" + tax_registration_number + '\'' + + ", registered_address='" + registered_address + '\'' + + ", telephone='" + telephone + '\'' + + ", deposit_bank='" + deposit_bank + '\'' + + ", bank_account='" + bank_account + '\'' + + ", subcompanyid='" + subcompanyid + '\'' + + '}'; + } + + public String getId() { + return id; + } + + public void setPkid(String id) { + this.id = id; + } + + public String getCompany_id() { + return company_id; + } + + public void setCompany_id(String company_id) { + this.company_id = company_id; + } + + public String getInvoice_title() { + return invoice_title; + } + + public void setInvoice_title(String invoice_title) { + this.invoice_title = invoice_title; + } + + public String getTax_registration_number() { + return tax_registration_number; + } + + public void setTax_registration_number(String tax_registration_number) { + this.tax_registration_number = tax_registration_number; + } + + public String getRegistered_address() { + return registered_address; + } + + public void setRegistered_address(String registered_address) { + this.registered_address = registered_address; + } + + public String getTelephone() { + return telephone; + } + + public void setTelephone(String telephone) { + this.telephone = telephone; + } + + public String getDeposit_bank() { + return deposit_bank; + } + + public void setDeposit_bank(String deposit_bank) { + this.deposit_bank = deposit_bank; + } + + public String getBank_account() { + return bank_account; + } + + public void setBank_account(String bank_account) { + this.bank_account = bank_account; + } + + public String getSubcompanyid() { + return subcompanyid; + } + + public void setSubcompanyid(String subcompanyid) { + this.subcompanyid = subcompanyid; + } +} diff --git a/src/main/java/weaver/seconddev/ey/zhangm/didi/entity/DidiTitle.java b/src/main/java/weaver/seconddev/ey/zhangm/didi/entity/DidiTitle.java new file mode 100644 index 0000000..1b3e34b --- /dev/null +++ b/src/main/java/weaver/seconddev/ey/zhangm/didi/entity/DidiTitle.java @@ -0,0 +1,68 @@ +package weaver.seconddev.ey.zhangm.didi.entity; + +/** + * @Description + * @Author miao.zhang + * @Version V1.0.0 + * @Since 1.0 + * @Date 11/29/22 + */ +public class DidiTitle { + private String id; + private String company_id; + private String invoice_title; + private String tax_registration_number; + private String subcompanyid; + + + @Override + public String toString() { + return "DidiTitle{" + + "pkid='" + id + '\'' + + ", company_id='" + company_id + '\'' + + ", invoice_title='" + invoice_title + '\'' + + ", tax_registration_number='" + tax_registration_number + '\'' + + ", subcompanyid='" + subcompanyid + '\'' + + '}'; + } + + public String getId() { + return id; + } + + public void setPkid(String id) { + this.id = id; + } + + public String getCompany_id() { + return company_id; + } + + public void setCompany_id(String company_id) { + this.company_id = company_id; + } + + public String getInvoice_title() { + return invoice_title; + } + + public void setInvoice_title(String invoice_title) { + this.invoice_title = invoice_title; + } + + public String getTax_registration_number() { + return tax_registration_number; + } + + public void setTax_registration_number(String tax_registration_number) { + this.tax_registration_number = tax_registration_number; + } + + public String getSubcompanyid() { + return subcompanyid; + } + + public void setSubcompanyid(String subcompanyid) { + this.subcompanyid = subcompanyid; + } +} diff --git a/src/main/java/weaver/seconddev/ey/zhangm/didi/entity/RequestLog.java b/src/main/java/weaver/seconddev/ey/zhangm/didi/entity/RequestLog.java new file mode 100644 index 0000000..37d4ddc --- /dev/null +++ b/src/main/java/weaver/seconddev/ey/zhangm/didi/entity/RequestLog.java @@ -0,0 +1,119 @@ +package weaver.seconddev.ey.zhangm.didi.entity; + +/** + * @Description + * @Author miao.zhang + * @Version V1.0.0 + * @Since 1.0 + * @Date 10/24/22 + */ + +public class RequestLog { + + private String qqsj; + private String url; + private String qqt; + private String qqcs; + private String xynr; + private String errno; + private String errmsg; + private String data; + private String httpstatus; + + + @Override + public String toString() { + return "RequestLog{" + + "qqsj='" + qqsj + '\'' + + ", url='" + url + '\'' + + ", qqt='" + qqt + '\'' + + ", qqcs='" + qqcs + '\'' + + ", xynr='" + xynr + '\'' + + ", errno='" + errno + '\'' + + ", errmsg='" + errmsg + '\'' + + ", data='" + data + '\'' + + ", httpstatus='" + httpstatus + '\'' + + '}'; + } + + public String getQqsj() { + return qqsj; + } + + public RequestLog setQqsj(String qqsj) { + this.qqsj = qqsj; + return this; + } + + public String getUrl() { + return url; + } + + public RequestLog setUrl(String url) { + this.url = url; + return this; + } + + public String getQqt() { + return qqt; + } + + public RequestLog setQqt(String qqt) { + this.qqt = qqt; + return this; + } + + public String getQqcs() { + return qqcs; + } + + public RequestLog setQqcs(String qqcs) { + this.qqcs = qqcs; + return this; + } + + public String getXynr() { + return xynr; + } + + public RequestLog setXynr(String xynr) { + this.xynr = xynr; + return this; + } + + public String getErrno() { + return errno; + } + + public RequestLog setErrno(String errno) { + this.errno = errno; + return this; + } + + public String getErrmsg() { + return errmsg; + } + + public RequestLog setErrmsg(String errmsg) { + this.errmsg = errmsg; + return this; + } + + public String getData() { + return data; + } + + public RequestLog setData(String data) { + this.data = data; + return this; + } + + public String getHttpstatus() { + return httpstatus; + } + + public RequestLog setHttpstatus(String httpstatus) { + this.httpstatus = httpstatus; + return this; + } +} diff --git a/src/main/java/weaver/seconddev/ey/zhangm/didi/entity/Result.java b/src/main/java/weaver/seconddev/ey/zhangm/didi/entity/Result.java new file mode 100644 index 0000000..4db552f --- /dev/null +++ b/src/main/java/weaver/seconddev/ey/zhangm/didi/entity/Result.java @@ -0,0 +1,111 @@ +package weaver.seconddev.ey.zhangm.didi.entity; + +/** + * @Description + * @Author miao.zhang + * @Version V1.0.0 + * @Since 1.0 + * @Date 10/24/22 + */ +public class Result { + + private int code; + private String content; + private String errmsg; + private Object data; + + public boolean isOk() { + return this.code == 0; + } + + public static Result create(int code, String content, String errmsg, Object data) { + return new Result() + .setCode(code) + .setContent(content) + .setErrmsg(errmsg) + .setData(data); + } + + public static Result create(int code, String content, String errmsg) { + return Result.create(code, content, errmsg, null); + } + + public static Result create(int code, String errmsg) { + return Result.create(code, null, errmsg, null); + } + + public static Result success() { + return Result.success(null); + } + + public static Result success(String content) { + return Result.success(content, null); + } + + public static Result success(String content, Object data) { + return Result.create(0, content, null, data); + } + + public static Result fail(String content, String errmsg, Object data) { + return Result.create(-1, content, errmsg, data); + } + + public static Result fail(String content) { + return Result.create(-1, content, null, null); + } + + public Result() { } + + @Override + public String toString() { + return "Result{" + + "code=" + code + + ", content='" + content + '\'' + + ", errmsg='" + errmsg + '\'' + + ", data=" + data + + '}'; + } + + public Result(int code, String content, String errmsg, Object data) { + this.code = code; + this.content = content; + this.errmsg = errmsg; + this.data = data; + } + + public int getCode() { + return code; + } + + public Result setCode(int code) { + this.code = code; + return this; + } + + public String getContent() { + return content; + } + + public Result setContent(String content) { + this.content = content; + return this; + } + + public String getErrmsg() { + return errmsg; + } + + public Result setErrmsg(String errmsg) { + this.errmsg = errmsg; + return this; + } + + public Object getData() { + return data; + } + + public Result setData(Object data) { + this.data = data; + return this; + } +} diff --git a/src/main/java/weaver/seconddev/ey/zhangm/didi/util/BUtils.java b/src/main/java/weaver/seconddev/ey/zhangm/didi/util/BUtils.java new file mode 100644 index 0000000..184963e --- /dev/null +++ b/src/main/java/weaver/seconddev/ey/zhangm/didi/util/BUtils.java @@ -0,0 +1,80 @@ +package weaver.seconddev.ey.zhangm.didi.util; + + +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; + +import java.lang.reflect.Field; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.stream.Collectors; +/** + * @Description + * @Author miao.zhang + * @Version V1.0.0 + * @Since 1.0 + * @Date 11/2/22 + */ +public class BUtils { + + public static List beanToAttrListWithSq(Object object, List fields) throws Exception { + List objectList = Lists.newArrayList(); +// for (Field declaredField : object.getClass().getDeclaredFields()) { +// System.out.println(declaredField.getName()); +// } + for (String fieldStr : fields) { + Field field = object.getClass().getDeclaredField(fieldStr); + field.setAccessible(true); + objectList.add(field.get(object)); + } + return objectList; + } + + public static List beanToAttrListWithSq(Object object, List fields,String apipkfield) throws Exception { + List objectList = Lists.newArrayList(); +// for (Field declaredField : object.getClass().getDeclaredFields()) { +// System.out.println(declaredField.getName()); +// } + for (String fieldStr : fields) { + Field field = object.getClass().getDeclaredField(fieldStr); + field.setAccessible(true); + objectList.add(field.get(object)); + } + //???????????? + if(!apipkfield.equals("")){ + Field field = object.getClass().getDeclaredField(apipkfield); + field.setAccessible(true); + objectList.add(field.get(object)); + } + return objectList; + } + + public static Map beanToAttrMap(Object object) throws IllegalAccessException { + Field[] fields = object.getClass().getDeclaredFields(); + Map res = Maps.newHashMap(); + for (Field field : fields) { + field.setAccessible(true); + res.put(field.getName(), field.get(object)); + } + return res; + } + + public static List beanAttrNameList(Class clazz) { + return Arrays.stream(clazz.getDeclaredFields()).map(Field::getName).collect(Collectors.toList()); + } + + public static Map beanToAttrMapNoNull(Object object) throws IllegalAccessException { + Field[] fields = object.getClass().getDeclaredFields(); + Map res = Maps.newHashMap(); + for (Field field : fields) { + field.setAccessible(true); + if (Objects.isNull(field.get(object))) { + continue; + } + res.put(field.getName(), StringUtils.val(field.get(object))); + } + return res; + } +} diff --git a/src/main/java/weaver/seconddev/ey/zhangm/didi/util/DaoUtils.java b/src/main/java/weaver/seconddev/ey/zhangm/didi/util/DaoUtils.java new file mode 100644 index 0000000..38125d1 --- /dev/null +++ b/src/main/java/weaver/seconddev/ey/zhangm/didi/util/DaoUtils.java @@ -0,0 +1,514 @@ +package weaver.seconddev.ey.zhangm.didi.util; + + +import com.google.common.base.Joiner; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; + +import weaver.conn.BatchRecordSet; +import weaver.conn.RecordSet; +import weaver.general.BaseBean; +import weaver.seconddev.ey.zhangm.didi.annotation.DaoField; + +import java.lang.reflect.Field; +import java.util.*; +/** + * @Description + * @Author miao.zhang + * @Version V1.0.0 + * @Since 1.0 + * @Date 11/2/22 + */ +public class DaoUtils { + + private static BaseBean baseBean = new BaseBean(); + + /** + * ȡݿ + * + * @return dbType + */ + public static String dbType() { + RecordSet recordSet = new RecordSet(); + return recordSet.getDBType(); + } + + /** + * ִв䣬mapļֵΪֵֶֶ + * + * @param tableName + * @param params + */ + public static void insert(String tableName, Map params) { + if (StringUtils.isEmpty(tableName)) { + baseBean.writeLog("ִв => Ϊ"); + return; + } + if (Objects.isNull(params) || params.isEmpty()) { + baseBean.writeLog("ִв => mapΪ"); + return; + } + List paramList = Lists.newArrayList(); + List valueList = Lists.newArrayList(); + params.forEach((key, value) -> { + paramList.add(key); + valueList.add(value); + }); + + executeUpdate(createInsertSql(tableName, paramList), valueList); + } + + public static void insert(String tableName, List params, List data) { + if (StringUtils.isEmpty(tableName)) { + baseBean.writeLog("ִв => Ϊ"); + return; + } + if (Objects.isNull(params) || params.isEmpty() || Objects.isNull(data) || data.isEmpty()) { + baseBean.writeLog("ִв => ֶμΪջݼΪ"); + return; + } + executeUpdate(createInsertSql(tableName, params), data); + } + + public static void batchInsert(String tableName, List params, List> data) { + if (StringUtils.isEmpty(tableName)) { + baseBean.writeLog("ִв => Ϊ"); + return; + } + if (Objects.isNull(params) || params.isEmpty() || Objects.isNull(data) || data.isEmpty()) { + baseBean.writeLog("ִв => ֶμΪջݼΪ"); + return; + } + batchExecute(createInsertSql(tableName, params), data); + } + + public static String createInsertSql(String tableName, List params) { + StringBuilder sql = new StringBuilder(String.format("insert into %s (", tableName)); + StringBuilder addParam = new StringBuilder(" values ("); + int i = 0; + List paramList = Lists.newArrayList(); + for (String param : params) { + if (i++ == 0) { + sql.append(" " + param); + addParam.append(" ?"); + } else { + sql.append(", " + param); + addParam.append(", ?"); + } + } + return sql.toString() + ")" + addParam.toString() + ")"; + } + + /** + * ӳRecordSetJavaBean + * + * @param recordSet + * @param clazz + * @param + * @return + */ + public static T recordSetMapToBean(RecordSet recordSet, Class clazz) { + try { + T t = clazz.newInstance(); + Field[] fields = clazz.getDeclaredFields(); + for (Field field : fields) { + // ȡǷע + DaoField daoField = field.getAnnotation(DaoField.class); + if (Objects.nonNull(daoField)) { + if (!daoField.value()) { // Ϊfalse + continue; + } + } + field.setAccessible(true); + String fieldName = field.getName(); + String value = recordSet.getString(fieldName); + field.set(t, value); + } + return t; + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException(e.getMessage()); + } + } + + public static T recordSetMapToBean(RecordSet recordSet, Class clazz, Map fieldMap) { + try { + T t = clazz.newInstance(); + Field[] fields = clazz.getDeclaredFields(); + for (Field field : fields) { + String fieldName = field.getName(); + String value = recordSet.getString(fieldMap.get(fieldName)); + field.setAccessible(true); + field.set(t, value); + } + return t; + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException(e.getMessage()); + } + } + + /** + * ѯ¼װʵ + * + * @param tableName + * @param clazz + * @param + * @return + */ + public static List queryTableToBean(String tableName, Class clazz) { + RecordSet recordSet = new RecordSet(); + String sql = String.format("select * from %s", tableName); + List tList = Lists.newArrayList(); + baseBean.writeLog("ִSQL => " + sql); + recordSet.executeQuery(sql); + while (recordSet.next()) + tList.add(recordSetMapToBean(recordSet, clazz)); + return tList; + } + + + public static List querySqlToBean(String sql, Class clazz, Map fields) { + RecordSet recordSet = new RecordSet(); + List tList = Lists.newArrayList(); + baseBean.writeLog("ִSQL => " + sql); + recordSet.executeQuery(sql); + while (recordSet.next()) + tList.add(recordSetMapToBean(recordSet, clazz)); + return tList; + } + + public static List queryTableToBean(String tableName, Class clazz, Map fields) { +// BiMap biMap = HashBiMap.create(fields); +// biMap.inverse(); + RecordSet recordSet = new RecordSet(); + String sql = String.format("select * from %s", tableName); + List tList = Lists.newArrayList(); + baseBean.writeLog("ִSQL => " + sql); + recordSet.executeQuery(sql); + while (recordSet.next()) + tList.add(recordSetMapToBean(recordSet, clazz, fields)); + return tList; + } + + public static T queryTableToSingleBean(String tableName, Class clazz, Map fields) { + RecordSet recordSet = new RecordSet(); + String sql = String.format("select * from %s", tableName); + baseBean.writeLog("ִSQL => " + sql); + recordSet.executeQuery(sql); + if (recordSet.next()) + return recordSetMapToBean(recordSet, clazz, fields); + return null; + } + + public static T queryTableToSingleBean(String tableName, Class clazz) { + RecordSet recordSet = new RecordSet(); + String sql = String.format("select * from %s", tableName); + baseBean.writeLog("ִSQL => " + sql); + recordSet.executeQuery(sql); + if (recordSet.next()) + return recordSetMapToBean(recordSet, clazz); + return null; + } + + public static String querySingleVal(String sql, Object... objs) { + RecordSet recordSet = new RecordSet(); + baseBean.writeLog("ִSQL => " + sql); + baseBean.writeLog("SQL => " + Arrays.toString(objs)); + recordSet.executeQuery(sql, objs); + if (recordSet.next()) { + return recordSet.getString(1); + } + return null; + } + + /** + * + * + * @param clazz clazz + * @param tableName tableName + * @param list list + * @throws Exception Exception + */ + public static void saveList(Class clazz, String tableName, List list) throws Exception { + List fields = BUtils.beanAttrNameList(clazz); + StringBuilder stringBuffer = new StringBuilder(String.format("insert into %s (", tableName)); + StringBuilder temp = new StringBuilder(); + for (int i = 0; i < fields.size(); i++) { + if (i == 0) { + stringBuffer.append(fields.get(i)); + temp.append("?"); + } else { + stringBuffer.append(", " + fields.get(i)); + temp.append(", ?"); + } + } + List> params = Lists.newArrayList(); + for (Object obj : list) { + params.add(BUtils.beanToAttrListWithSq(obj, fields)); + } + stringBuffer.append(") values (" + temp.toString() + ")"); + baseBean.writeLog("ִSQL => " + stringBuffer.toString()); + batchExecute(stringBuffer.toString(), params); + } + + /** + * + * + * @param fields clazz + * @param tableName tableName + * @param list list + * @throws Exception Exception + */ + public static void saveList(Map fields, String tableName, List list) throws Exception { + StringBuffer stringBuffer = new StringBuffer(String.format("insert into %s (", tableName)); + List keyList = Lists.newArrayList(fields.keySet()); + List valueList = Lists.newArrayList(); + StringBuffer temp = new StringBuffer(); + for (int i = 0; i < keyList.size(); i++) { + String value = fields.get(keyList.get(i)); + valueList.add(value); + if (i == 0) { + stringBuffer.append(value); + temp.append("?"); + } else { + stringBuffer.append(", " + value); + temp.append(", ?"); + } + } + List> params = Lists.newArrayList(); + for (Object obj : list) { + params.add(BUtils.beanToAttrListWithSq(obj, keyList)); + } + stringBuffer.append(") values (" + temp.toString() + ")"); + baseBean.writeLog("ִSQL => " + stringBuffer.toString()); + batchExecute(stringBuffer.toString(), params); + } + + /** + * ѯSQLװʵ + * + * @param clazz + * @param sql + * @param objs + * @param + * @return + */ + public static List querySqlToBean(String sql, Class clazz, Object... objs) { + RecordSet recordSet = new RecordSet(); + List tList = Lists.newArrayList(); + baseBean.writeLog("ִSQL => " + sql); + baseBean.writeLog("SQL => " + Arrays.toString(objs)); + recordSet.executeQuery(sql, objs); + while (recordSet.next()) + tList.add(recordSetMapToBean(recordSet, clazz)); + return tList; + } + + public static T findSqlToBean(Class clazz, String sql, Object... objs) { + RecordSet recordSet = new RecordSet(); + baseBean.writeLog("ִSQL => " + sql); + baseBean.writeLog("SQL => " + Arrays.toString(objs)); + recordSet.executeQuery(sql, objs); + if (recordSet.next()) + return recordSetMapToBean(recordSet, clazz); + return null; + } + + public static RecordSet executeQuery(String sql, Object... objs) { + RecordSet recordSet = new RecordSet(); + baseBean.writeLog("ִSQL => " + sql); + baseBean.writeLog("SQL => " + Arrays.toString(objs)); + if (recordSet.executeQuery(sql, objs)) + return recordSet; + return null; + } + + public static List> executeQueryToMapList(String sql, Object... objs) { + RecordSet recordSet = new RecordSet(); + baseBean.writeLog("ִSQL => " + sql); + baseBean.writeLog("SQL => " + Arrays.toString(objs)); + List> res = Lists.newArrayList(); + if (recordSet.executeQuery(sql, objs)) { + while (recordSet.next()) { + res.add(recordSetToMap(recordSet)); + } + } + return res; + } + + public static List> executeQueryToMapListPage(String primaryKey, String table, String criteria, List fields, int start, int limit, Object... objs) { + RecordSet recordSet = new RecordSet(); + String dbType = recordSet.getDBType().toUpperCase(); + // жݿ + baseBean.writeLog("dbType ===> " + dbType); + String sql = ""; + String fieldStr = Joiner.on(",").skipNulls().join(fields.toArray()); + // жϵǰݿ + if (dbType.contains("MYSQL")) { // MySQL + sql = String.format("select %s from %s %s limit %s, %s", fieldStr, table, criteria, start, limit); + } else { // Ĭ SQL SERVER + sql = String.format( + "select top (%s) * from ( " + + "select row_number() over(order by %s.%s) as rownumber, %s from %s %s" + + ") temp_row where rownumber > %s" + , limit, table, primaryKey, fieldStr, table, criteria, start); + } + baseBean.writeLog("ִSQL => " + sql); + baseBean.writeLog("SQL => " + Arrays.toString(objs)); + List> res = Lists.newArrayList(); + if (recordSet.executeQuery(sql, objs)) { + while (recordSet.next()) { + res.add(recordSetToMap(recordSet)); + } + } + return res; + } + + + /** + * ҳѯList> + */ + public static List> executeQueryToMapListPage(String table, String criteria, List fields, int start, int limit, Object... objs) { + return executeQueryToMapListPage("id", table, criteria, fields, start, limit, objs); + } + + public static Map executeQueryToMap(String sql, Object... objs) { + RecordSet recordSet = new RecordSet(); + baseBean.writeLog("ִSQL => " + sql); + baseBean.writeLog("SQL => " + Arrays.toString(objs)); + if (recordSet.executeQuery(sql, objs)) { + if (recordSet.next()) { + return recordSetToMap(recordSet); + } + } + return null; + } + + private static Map recordSetToMap(RecordSet recordSet) { + Map map = Maps.newHashMap(); + for (String s : recordSet.getColumnName()) { + map.put(s, recordSet.getString(s)); + } + return map; + } + + public static void executeUpdate(String sql, List param) { + RecordSet recordSet = new RecordSet(); + baseBean.writeLog("ִSQL => " + sql); + baseBean.writeLog("SQL => " + Arrays.toString(param.toArray())); + recordSet.executeUpdate(sql, param.toArray(new Object[]{})); + } + + public static void executeUpdate(String sql, Object... objs) { + RecordSet recordSet = new RecordSet(); + baseBean.writeLog("ִSQL => " + sql); + baseBean.writeLog("SQL => " + Arrays.toString(objs)); + recordSet.executeUpdate(sql, objs); + } + + public static void execute(String sql, List param) { + RecordSet recordSet = new RecordSet(); + baseBean.writeLog("ǰSQL => " + sql); + sql = toSingleSql(sql, param); + baseBean.writeLog("ִSQL => " + sql); + recordSet.execute(sql); + } + + public static void batchExecute(String sql, List> param) { + BatchRecordSet batchRecordSet = new BatchRecordSet(); + baseBean.writeLog("ִSQL => " + sql); + batchRecordSet.executeBatchSql(sql, param); + } + + private static String toSingleSql(String sql, List param) { + int pos = 0; + StringBuffer stringBuffer = new StringBuffer(); + for (int i = 0; i < sql.length(); i++) { + if (sql.charAt(i) == '?') { + stringBuffer.append(String.format("'%s'", param.get(pos++))); + } else { + stringBuffer.append(sql.charAt(i)); + } + } + return stringBuffer.toString(); + } + + public static void saveBean(String tableName, Object obj) throws IllegalAccessException { + Map param = BUtils.beanToAttrMap(obj); + StringBuilder sqlStr = new StringBuilder(String.format("insert into %s (", tableName)); + StringBuilder temp = new StringBuilder(" values ("); + List objects = Lists.newArrayList(); + int i = 0; + for (Map.Entry entry : param.entrySet()) { + if (i++ == 0) { + sqlStr.append(entry.getKey()); + temp.append("?"); + } else { + sqlStr.append(", " + entry.getKey()); + temp.append(", ?"); + } + objects.add(entry.getValue()); + } + String sql = sqlStr.toString() + " )" + temp.toString() + " )"; + executeUpdate(sql, objects); + } + + public static void saveBean(String tableName, Object obj, Map fields) throws Exception { +// Map param = BUtils.beanToAttrMap(obj); + StringBuffer sqlStr = new StringBuffer(String.format("insert into %s (", tableName)); + StringBuffer temp = new StringBuffer(" values ("); + int i = 0; + List keys = Lists.newArrayList(); + for (Map.Entry entry : fields.entrySet()) { + if (i++ == 0) { + sqlStr.append(entry.getValue()); + temp.append("?"); + } else { + sqlStr.append(", " + entry.getValue()); + temp.append(", ?"); + } + keys.add(entry.getKey()); + } + List objects = BUtils.beanToAttrListWithSq(obj, keys); + String sql = sqlStr.toString() + " )" + temp.toString() + " )"; + executeUpdate(sql, objects); + } + + public static String analyzeInsertSql(String tableName, Map param) { + StringBuffer sql = new StringBuffer(String.format("insert into %s (", tableName)); + StringBuffer temp = new StringBuffer(" ) values ("); + int i = 0; + for (Map.Entry entry : param.entrySet()) { + if (i++ == 0) { + sql.append(entry.getValue()); + temp.append("?"); + } else { + sql.append(", " + entry.getValue()); + temp.append(", ?"); + } + } + return sql.toString() + temp.toString() + ")"; + } + + public static List> analyzeObjList(List list, List fields) throws Exception { + List> params = Lists.newArrayList(); + for (Object obj : list) { + params.add(BUtils.beanToAttrListWithSq(obj, fields)); + } + return params; + } + + public static List> analyzeObjList(List list, Map fields) throws Exception { + return analyzeObjList(list, new ArrayList<>(fields.keySet())); + } + + public static T querySqlToSingleBean(String sql, Class clazz, Map fields, Object... objs) { + RecordSet recordSet = new RecordSet(); + baseBean.writeLog("ִSQL => " + sql); + recordSet.executeQuery(sql, objs); + if (recordSet.next()) + return recordSetMapToBean(recordSet, clazz, fields); + return null; + } +} diff --git a/src/main/java/weaver/seconddev/ey/zhangm/didi/util/DateUtils.java b/src/main/java/weaver/seconddev/ey/zhangm/didi/util/DateUtils.java new file mode 100644 index 0000000..2220bc7 --- /dev/null +++ b/src/main/java/weaver/seconddev/ey/zhangm/didi/util/DateUtils.java @@ -0,0 +1,354 @@ +package weaver.seconddev.ey.zhangm.didi.util; + + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +/** + * @Description + * @Author miao.zhang + * @Version V1.0.0 + * @Since 1.0 + * @Date 11/2/22 + */ +public class DateUtils { + + private static final long ONE_MINUTE = 60000L; + private static final long ONE_HOUR = 3600000L; + private static final long ONE_DAY = 86400000L; + private static final long ONE_WEEK = 604800000L; + + private static final String ONE_SECOND_AGO = "秒前"; + private static final String ONE_MINUTE_AGO = "分钟前"; + private static final String ONE_HOUR_AGO = "小时前"; + private static final String ONE_DAY_AGO = "天前"; + private static final String ONE_MONTH_AGO = "月前"; + private static final String ONE_YEAR_AGO = "年前"; + + + + + public static String relative(Date date) { + return relative(date, ONE_DAY * 3, "yyyy-MM-dd HH:mm:ss"); + } + + public static String relative(Date date, long maxOffset) { + return relative(date, maxOffset, "yyyy-MM-dd HH:mm:ss"); + } + + public static String relative(Date date, String partten) { + return relative(date, ONE_DAY * 3, partten); + } + + /** + * 计算两个时间的相对时间如 1分钟前、9小时前等 + * + * @param date 相对时间 + * @param maxOffset 最大间隔数,超过最大间隔将直接返回时间 + * @param partten 超过最大间隔将直接返回时间格式 + * @return + */ + public static String relative(Date date, long maxOffset, String partten) { + long delta = new Date().getTime() - date.getTime(); + if (delta > maxOffset) { + return DateUtils.date(date, partten); + } + if (delta < 1L * ONE_MINUTE) { + long seconds = toSeconds(delta); + return (seconds <= 0 ? 1 : seconds) + ONE_SECOND_AGO; + } + if (delta < 45L * ONE_MINUTE) { + long minutes = toMinutes(delta); + return (minutes <= 0 ? 1 : minutes) + ONE_MINUTE_AGO; + } + if (delta < 24L * ONE_HOUR) { + long hours = toHours(delta); + return (hours <= 0 ? 1 : hours) + ONE_HOUR_AGO; + } + if (delta < 48L * ONE_HOUR) { + return "昨天"; + } + if (delta < 30L * ONE_DAY) { + long days = toDays(delta); + return (days <= 0 ? 1 : days) == 2 ? "前天" : (days <= 0 ? 1 : days) + ONE_DAY_AGO; + } + if (delta < 12L * 4L * ONE_WEEK) { + long months = toYears(delta); + return (months <= 0 ? 1 : months) + ONE_MONTH_AGO; + } else { + long years = delta / 365L; + return (years <= 0 ? 1 : years) + ONE_YEAR_AGO; + } + } + + + private static long toSeconds(long date) { + return date / 1000L; + } + + private static long toMinutes(long date) { + return toSeconds(date) / 60L; + } + + private static long toHours(long date) { + return toMinutes(date) / 60L; + } + + private static long toDays(long date) { + return toHours(date) / 24L; + } + + private static long toMonths(long date) { + return toDays(date) / 30L; + } + + private static long toYears(long date) { + return toMonths(date) / 365L; + } + + public static String min(String date1, String date2) { + try { + if (StringUtils.isEmpty(date1)) return date2; + if (StringUtils.isEmpty(date2)) return date1; + long time1 = parse(date1).getTime(); + long time2 = parse(date2).getTime(); + return time1 < time2 ? date1 : date2; + } catch (Exception e) { + throw new RuntimeException(e.getMessage()); + } + } + + public static String max(String date1, String date2) { + try { + if (StringUtils.isEmpty(date1)) return date2; + if (StringUtils.isEmpty(date2)) return date1; + long time1 = parse(date1).getTime(); + long time2 = parse(date2).getTime(); + return time1 > time2 ? date1 : date2; + } catch (Exception e) { + throw new RuntimeException(e.getMessage()); + } + } + + public static boolean checkBetween(String datetime, String date1, String date2) { + try { + long time1 = parse(date1).getTime(); + long time2 = parse(date2).getTime(); + long check = parse(datetime, "yyyy-MM-dd HH:mm:ss").getTime(); + return check >= time1 && check <= time2; + } catch (Exception e) { + throw new RuntimeException(e.getMessage()); + } + } + + public static Date now() { + return new Date(); + } + + public static Date parse(String date) throws ParseException { + return parse(date, "yyyy-MM-dd"); + } + + public static Date parse(String date, String pattern) throws ParseException { + SimpleDateFormat dateFormat = new SimpleDateFormat(pattern); + return dateFormat.parse(date); + } + + /** + * 根据给定日期 和 格式串 返回指定格式日期时间 + * + * @param date 日期时间 + * @param partten 格式串 + * @return 指定格式日期时间 + */ + public static String date(Date date, String partten) { + SimpleDateFormat dateFormat = new SimpleDateFormat(partten); + return dateFormat.format(date); + } + + public static Date getDate(Date date, String pattern) throws ParseException { + return new SimpleDateFormat(pattern).parse(date(date, pattern)); + } + + public static Date getDate(Date date) throws ParseException { + return new SimpleDateFormat("yyyy-MM-dd").parse(date(date, "yyyy-MM-dd")); + } + + public static Date getDate() throws ParseException { + return new SimpleDateFormat("yyyy-MM-dd").parse(date(new Date(), "yyyy-MM-dd")); + } + + public static Date getDate(String pattern) throws ParseException { + return new SimpleDateFormat(pattern).parse(date(new Date(), pattern)); + } + + /** + * 根据格式串返回当前日期时间指定格式 + * + * @param pattern 格式串 + * @return 当前日期时间指定格式 + */ + public static String date(String pattern) { + return date(new Date(), pattern); + } + + /** + * 返回yyyy-MM-dd 格式指定日期时间 + * + * @param date 指定日期时间 + * @return yyyy-MM-dd 格式指定日期时间 + */ + public static String date(Date date) { + return date(date, "yyyy-MM-dd"); + } + + /** + * 返回yyyy-MM-dd 格式当前日期时间 + * + * @return yyyy-MM-dd 格式当前日期时间 + */ + public static String date() { + return date("yyyy-MM-dd"); + } + + /** + * 返回指定间隔天数的日期 + * + * @param date 指定日期 + * @param offset 指定偏移量(天) + * @return 指定间隔天数的日期 (yyyy-MM-dd) + */ + public static String date(Date date, int offset) { + Calendar calendar = new GregorianCalendar(); + calendar.setTime(date); + calendar.add(Calendar.DATE, offset); + return date(calendar.getTime()); + } + + public static String offset(int offset) { + return date(new Date(), offset); + } + + /** + * 返回指定间隔天数的当前日期 + * + * @param offset 指定偏移量(天) + * @return 指定间隔天数的房前日期 (yyyy-MM-dd) + */ + public static String date(int offset) { + return date(new Date(), offset); + } + + /** + * 返回yyyy-MM-dd HH:mm:ss格式日期时间 + * + * @return yyyy-MM-dd HH:mm:ss格式日期时间 + */ + public static String datetime() { + return date("yyyy-MM-dd HH:mm:ss"); + } + + /** + * 返回HH:mm:ss格式时间 + * + * @return HH:mm:ss格式时间 + */ + public static String time() { + return date("HH:mm:ss"); + } + + /** + * 返回指定日期偏移天数的起始时间 + * + * @param date 日期 + * @param offset 偏移量 + * @return 指定日期偏移天数的起始时间 + */ + public static Date dayStart(Date date, int offset) { + Calendar calendar = new GregorianCalendar(); + calendar.setTime(date); + calendar.add(Calendar.DATE, offset); + calendar.set(Calendar.HOUR_OF_DAY, 0); + calendar.set(Calendar.MINUTE, 0); + calendar.set(Calendar.SECOND, 0); + calendar.set(Calendar.MILLISECOND, 0); + return calendar.getTime(); + } + + /** + * 当前日期的起始时间 + * + * @return 当前日期的起始时间 + */ + public static Date dayStart() { + return dayStart(new Date(), 0); + } + + /** + * 当前日期的偏移量起始时间 + * + * @param offset 偏移量 + * @return 当前日期的偏移量起始时间 + */ + public static Date dayStart(int offset) { + return dayStart(new Date(), offset); + } + + /** + * 指定日期指定偏移天数结束时间 + * + * @param date 指定日期 + * @param offset 指定偏移天数 + * @return 指定日期指定偏移天数结束时间 + */ + public static Date dayEnd(Date date, int offset) { + Calendar calendar = new GregorianCalendar(); + calendar.setTime(date); + calendar.add(Calendar.DATE, offset); + calendar.set(Calendar.HOUR_OF_DAY, 23); + calendar.set(Calendar.MINUTE, 59); + calendar.set(Calendar.SECOND, 59); + calendar.set(Calendar.MILLISECOND, 999); + return calendar.getTime(); + } + + /** + * 当前日期结束时间 + * + * @return 当前日期结束时间 + */ + public static Date dayEnd() { + return dayEnd(new Date(), 0); + } + + /** + * 当前日期指定偏移天数结束时间 + * + * @param offset 偏移天数 + * @return 当前日期指定偏移天数结束时间 + */ + public static Date dayEnd(int offset) { + return dayEnd(new Date(), offset); + } + + /** + * 时间戳 + * + * @return 时间戳 + */ + public static String timestamp() { + return String.valueOf(System.currentTimeMillis()); + } + + public static boolean equals(Date date1, Date date2) { + if (date1 == null && date2 != null) + return false; + if (date1 == date2) + return true; + if (date1.equals(date2)) + return true; + return date1.getTime() == date2.getTime(); + } +} diff --git a/src/main/java/weaver/seconddev/ey/zhangm/didi/util/StringUtils.java b/src/main/java/weaver/seconddev/ey/zhangm/didi/util/StringUtils.java new file mode 100644 index 0000000..b0611ba --- /dev/null +++ b/src/main/java/weaver/seconddev/ey/zhangm/didi/util/StringUtils.java @@ -0,0 +1,291 @@ +package weaver.seconddev.ey.zhangm.didi.util; + +/** + * @Description + * @Author miao.zhang + * @Version V1.0.0 + * @Since 1.0 + * @Date 10/24/22 + */ +public class StringUtils { + + // 为了兼容apache StringUtils + public static String replace(String text, String repl, String with) { + return replace(text, repl, with, -1); + } + + public static String replace(String text, String repl, String with, int max) { + if (!isEmpty(text) && !isEmpty(repl) && with != null && max != 0) { + int start = 0; + int end = text.indexOf(repl, start); + if (end == -1) { + return text; + } else { + int replLength = repl.length(); + int increase = with.length() - replLength; + increase = Math.max(increase, 0); + increase *= max < 0 ? 16 : (Math.min(max, 64)); + + StringBuffer buf; + for (buf = new StringBuffer(text.length() + increase); end != -1; end = text.indexOf(repl, start)) { + buf.append(text.substring(start, end)).append(with); + start = end + replLength; + --max; + if (max == 0) { + break; + } + } + + buf.append(text.substring(start)); + return buf.toString(); + } + } else { + return text; + } + } + + + /** + * 按字符截取长度 + * + * @param text 原文本 + * @param maxLength 截取长度(按字符) + * @return + */ + public static String subStringByChar(String text, Integer maxLength) { + if (StringUtils.isBlank(text)) { + return text; + } + //名称最多展示14个字符,一个汉字算两个字符,超过展示... + StringBuilder sBuilder = new StringBuilder(); + char[] chars = text.toCharArray(); + int length = 0; + for (char ch : chars) { + boolean chineseChar = isChineseChar(ch) || isSymbol(ch); + length = length + (chineseChar ? 2 : 1); + if (length > maxLength) { + break; + } + sBuilder.append(ch); + } + String testResult = sBuilder.toString(); + if (length > maxLength) { + testResult = testResult; + } + return testResult; + } + + /** + * 是否中文符号 + * + * @param ch + * @return + */ + public static boolean isSymbol(char ch) { + if (isCnSymbol(ch)) return true; + if (isEnSymbol(ch)) return true; + + if (0x2010 <= ch && ch <= 0x2017) return true; + if (0x2020 <= ch && ch <= 0x2027) return true; + if (0x2B00 <= ch && ch <= 0x2BFF) return true; + if (0xFF03 <= ch && ch <= 0xFF06) return true; + if (0xFF08 <= ch && ch <= 0xFF0B) return true; + if (ch == 0xFF0D || ch == 0xFF0F) return true; + if (0xFF1C <= ch && ch <= 0xFF1E) return true; + if (ch == 0xFF20 || ch == 0xFF65) return true; + if (0xFF3B <= ch && ch <= 0xFF40) return true; + if (0xFF5B <= ch && ch <= 0xFF60) return true; + if (ch == 0xFF62 || ch == 0xFF63) return true; + if (ch == 0x0020 || ch == 0x3000) return true; + return false; + + } + + + public static boolean isCnSymbol(char ch) { + if (0x3004 <= ch && ch <= 0x301C) return true; + if (0x3020 <= ch && ch <= 0x303F) return true; + return false; + } + + public static boolean isEnSymbol(char ch) { + + if (ch == 0x40) return true; + if (ch == 0x2D || ch == 0x2F) return true; + if (0x23 <= ch && ch <= 0x26) return true; + if (0x28 <= ch && ch <= 0x2B) return true; + if (0x3C <= ch && ch <= 0x3E) return true; + if (0x5B <= ch && ch <= 0x60) return true; + if (0x7B <= ch && ch <= 0x7E) return true; + + return false; + } + + + + /** + * 是否汉字字符 + * + * @param c + * @return + */ + public static boolean isChineseChar(char c) { + return String.valueOf(c).matches("[\u4e00-\u9fa5]"); + } + + public static boolean isBlank(String str) { + int strLen; + if (str != null && (strLen = str.length()) != 0) { + for (int i = 0; i < strLen; ++i) { + if (!Character.isWhitespace(str.charAt(i))) { + return false; + } + } + + return true; + } else { + return true; + } + } + + + /** + * 把中文转成Unicode码 + * + * @param str + * @return + */ + public static String chinaToUnicode(String str) { + String result = ""; + for (int i = 0; i < str.length(); i++) { + int chr1 = (char) str.charAt(i); + if (chr1 >= 19968 && chr1 <= 171941) {// 汉字范围 \u4e00-\u9fa5 (中文) + result += "\\u" + Integer.toHexString(chr1); + } else { + result += str.charAt(i); + } + } + return result; + } + + public static String val(Object obj, String txt) { + if (obj == null) + return txt; + return obj.toString(); + } + + public static String valNotEmpty(Object obj, String txt) { + String val = val(obj); + return isEmpty(val) ? txt : val; + } + + public static String val(Object obj) { + return val(obj, null); + } + + + /** + * 截取字符串尾部指定长度 + * + * @param str 字符串源 + * @param len 截取长度 + * @return 符串尾部指定长度 + */ + public static String tailSubstring(String str, int len) { + if (len <= 0) return str; + if (str.length() < len) throw new RuntimeException("截取长度大于字符串本身"); + return str.substring(str.length() - len); + } + + public static String tailChar(String str) { + return tailSubstring(str, 1); + } + + public static String headChar(String str) { + return str.substring(0, 1); + } + + /** + * 判断是否为空 + * + * @param str 字符串源 + * @return 是否为空 + */ + public static boolean isEmpty(String str) { + if (str == null || str.length() == 0) return true; + return false; + } + + public static boolean isNotEmpty(String str) { + return !isEmpty(str); + } + + /** + * 判断字符串是否相等 + * + * @param str1 源串 + * @param str2 比较串 + * @return + */ + public static boolean equals(String str1, String str2) { + if (str1 == null && str2 == null) return true; + if (str1 == null || str2 == null) return false; + else return str1.equals(str2); + } + + /** + * 判断字符串是否相等 忽略大小写 + * + * @param str1 源串 + * @param str2 比较串 + * @return + */ + public static boolean equalsIgnoreCase(String str1, String str2) { + if (str1 == null && str2 == null) return true; + if (str1 == null || str2 == null) return false; + else return str1.equalsIgnoreCase(str2); + } + + /** + * 比较Object 与字符串是否相等 会使用toString + * + * @param obj 比较源 + * @param str 对比串 + * @return + */ + public static boolean equals(Object obj, String str) { + if (obj == null) return equals(null, str); + return equals(obj.toString(), str); + } + + public static boolean equals(Object obj1, Object obj2) { + if ((obj1 == null && obj2 != null) || (obj1 != null && obj2 == null)) { + return false; + } + if (obj1 == null || obj1.equals(obj2)) { + return true; + } + return equals(obj1.toString(), obj2.toString()); + } + + /** + * 比较Object 与字符串是否相等 会使用toString 忽略大小写 + * + * @param obj 比较源 + * @param str 对比串 + * @return + */ + public static boolean equalsIgnoreCase(Object obj, String str) { + if (obj == null) return equals(null, str); + return equalsIgnoreCase(obj.toString(), str); + } + + @FunctionalInterface + public interface ComputeFn { + String fn(); + } + + public static String compute(ComputeFn computeFn) { + return computeFn.fn(); + } +} diff --git a/src/main/java/weaver/seconddev/ey/zhangm/util/EYSeconddevUtil.java b/src/main/java/weaver/seconddev/ey/zhangm/util/EYSeconddevUtil.java new file mode 100644 index 0000000..ec74295 --- /dev/null +++ b/src/main/java/weaver/seconddev/ey/zhangm/util/EYSeconddevUtil.java @@ -0,0 +1,721 @@ +package weaver.seconddev.ey.zhangm.util; + + +import com.alibaba.fastjson.JSON; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.wbi.util.StringUtil; +import com.weaver.esb.client.EsbClient; +import com.weaver.esb.spi.EsbService; +import okhttp3.*; + +import org.apache.commons.lang.StringUtils; +import weaver.conn.RecordSet; +import weaver.general.BaseBean; +import weaver.general.Util; +import weaver.hrm.resource.ResourceComInfo; +import weaver.seconddev.ey.zhangm.didi.entity.Result; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.sql.Timestamp; +import java.text.SimpleDateFormat; +import java.util.*; + +public class EYSeconddevUtil extends BaseBean { + /** + * 校验EM、EP rank + * @param gpn + * @param mark 内部项目、外部项目标识 0 内部、1外部 + * @param role 项目角色标识标识 0 EP、1 EM + * @return + */ + public boolean validateEngagementRoleRank(String gpn,String mark,String role){ + RecordSet rs=new RecordSet(); + rs.executeQuery("select id from hrmresource where workcode=?",gpn); + String userId=""; + if(rs.next()){ + userId=Util.null2String(rs.getString(1)); + } + // 查询rank + String rank=""; + rs.executeQuery("select concat(field2,field24) from cus_fielddata scope='HrmCustomFieldByInfoType' and scopeid=-1 and id=?",userId); + if(rs.next()){ + rank=Util.null2String(rs.getString(1)); + } + // 校验rank + rs.executeQuery("select id from uf_xmjsrankjyb where rankcode=? and mark=? and role=?",rank,mark,role); + return rs.getCounts()>0; + } + + public String getSystemParamValue(String ssid){ + String paramvalue =""; + if(!"".equals(ssid)){ + String select_sql="select paramvalue from uf_dd_prmt where ssid ='"+ssid+"'"; + RecordSet rs =new RecordSet(); + rs.executeSql(select_sql); + if(rs.next()){ + paramvalue = Util.null2String(rs.getString("paramvalue")); + } + } + return paramvalue; + } + + public Map getSystemParamValues(String ssids){ + + HashMap paramvalues=new HashMap(); + String ssidsstr=""; + if(!"".equals(ssids)){ + String [] ssidsArray = ssids.split(","); + for (String s:ssidsArray){ + if(!"".equals(s)) { + ssidsstr = ssidsstr + "'" + s + "',"; + } + } + if(!"".equals(ssidsstr)) { + ssidsstr = ssidsstr.substring(0, ssidsstr.length() - 1); + String select_sql="select ssid,paramvalue from uf_dd_prmt where ssid in("+ssidsstr+")"; + RecordSet rs =new RecordSet(); + rs.executeSql(select_sql); + while (rs.next()){ + paramvalues.put(rs.getString("ssid"),rs.getString("paramvalue")); + } + } + } + return paramvalues; + } + + public String getUserAllRole(Integer userid){ + String returnStr = ""; + RecordSet rs = new RecordSet(); + rs.executeSql("select roleid from hrmrolemembers where resourceid=" + userid); + while (rs.next()) { + returnStr = returnStr + Util.null2String(rs.getString("roleid")) + ","; + } + if (!"".equals(returnStr)) { + returnStr = returnStr.substring(0, returnStr.length() - 1); + } + if ("".equals(returnStr)) { + returnStr = "0"; + } + return returnStr; + } + + public String getMD5Str(String plainText){ + //定义一个字节数组 + byte[] secretBytes = null; + try { + // 生成一个MD5加密计算摘要 + MessageDigest md = MessageDigest.getInstance("MD5"); + //对字符串进行加密 + md.update(plainText.getBytes()); + //获得加密后的数据 + secretBytes = md.digest(); + } catch (NoSuchAlgorithmException e) { + //throw new RuntimeException("没有md5这个算法!"); + //throw new RuntimeException(SystemEnv.getHtmlLabelName(517545,userLanguage)); + } + //将加密后的数据转换为16进制数字 + String md5code = new BigInteger(1, secretBytes).toString(16); + // 如果生成数字未满32位,需要前面补0 + // 不能把变量放到循环条件,值改变之后会导致条件变化。如果生成30位 只能生成31位md5 + int tempIndex = 32 - md5code.length(); + for (int i = 0; i < tempIndex; i++) { + md5code = "0" + md5code; + } + return md5code; + } + + public static String getCurrentTime() { + Date newdate = new Date(); + long datetime = newdate.getTime(); + Timestamp timestamp = new Timestamp(datetime); + String currenttime = (timestamp.toString()).substring(11, 13) + ":" + (timestamp.toString()).substring(14, 16) + ":" + + (timestamp.toString()).substring(17, 19); + return currenttime; + } + + public static String getCurrentDate() { + Date newdate = new Date(); + long datetime = newdate.getTime(); + Timestamp timestamp = new Timestamp(datetime); + String currentdate = (timestamp.toString()).substring(0, 4) + "-" + (timestamp.toString()).substring(5, 7) + "-" + + (timestamp.toString()).substring(8, 10); + return currentdate; + } + + /** + * 获取当前日期时间。 YYYY-MM-DD HH:MM:SS + * @return 当前日期时间 + */ + public static String getCurDateTime() { + Date newdate = new Date(); + long datetime = newdate.getTime(); + Timestamp timestamp = new Timestamp(datetime); + return (timestamp.toString()).substring(0, 19); + } + + /** + * 获取时间戳 格式如:19990101235959 + * @return + */ + public static String getTimestamp(){ + return getCurDateTime().replace("-", "").replace(":", "").replace(" ", ""); + } + + public static String doAction(Map paramDatajson,String url,String method){ + String resultstr=""; + try{ + OkHttpClient client = new OkHttpClient().newBuilder() + .build(); + MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded"); + new BaseBean().writeLog("json==>"+ JSON.toJSONString(paramDatajson)); + + RequestBody body = RequestBody.create(mediaType, "datajson="+ JSON.toJSONString(paramDatajson)); + + Request request = new Request.Builder() + .url(url) + .method(method, body) + .addHeader("Content-Type", "application/x-www-form-urlencoded") + .build(); + Response result = client.newCall(request).execute(); + resultstr = result.body().string(); + + }catch (Exception e){ + new BaseBean().writeLog("请求失败"+getCurrentDate()+" "+getCurrentDate()+"====errormsg:"+e.getMessage()); + } + return resultstr; + } + + /** + * 传入两个时间范围,返回这两个时间范围内的所有日期,并保存在一个集合中 + * + * @param beginTime + * @param endTime + * @return + * @throws Exception + */ + public static List findEveryDay(String beginTime, String endTime) + throws Exception { + //创建一个放所有日期的集合 + List dates = new ArrayList(); + + //创建时间解析对象规定解析格式 + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + + //将传入的时间解析成Date类型,相当于格式化 + Date dBegin = sdf.parse(beginTime); + Date dEnd = sdf.parse(endTime); + + //将格式化后的第一天添加进集合 + dates.add(sdf.format(dBegin)); + + //使用本地的时区和区域获取日历 + Calendar calBegin = Calendar.getInstance(); + + //传入起始时间将此日历设置为起始日历 + calBegin.setTime(dBegin); + + //判断结束日期前一天是否在起始日历的日期之后 + while (dEnd.after(calBegin.getTime())) { + + //根据日历的规则:月份中的每一天,为起始日历加一天 + calBegin.add(Calendar.DAY_OF_MONTH, 1); + + //得到的每一天就添加进集合 + dates.add(sdf.format(calBegin.getTime())); + //如果当前的起始日历超过结束日期后,就结束循环 + } + return dates; + } + + public String createHrToken() throws Exception{ + String accessToken=""; + OkHttpClient client = new OkHttpClient().newBuilder().build(); + String clientId =getSystemParamValue("eyhrclientId"); + String appId =getSystemParamValue("eyhrappId"); + String appSecret =getSystemParamValue("eyhrappSecret"); + String hrsynccreatetokenurl =getSystemParamValue("hrsynccreatetokenurl"); + String hrsyncaddress =getSystemParamValue("hrsyncaddress"); + Mapparams =new HashMap (); + params.put("clientId",clientId); + params.put("appId",appId); + params.put("appSecret",appSecret); + MediaType mediaType = MediaType.parse("application/json"); + RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(params)); + Request request = new Request.Builder() + .url(hrsyncaddress+hrsynccreatetokenurl) + .method("POST", body) + .addHeader("Content-Type", "application/json") + .build(); + Response response = client.newCall(request).execute(); + if (response.isSuccessful()) { + Result result = Result.success(Objects.requireNonNull(response.body()).string()); + if (result.isOk()) { + JSONObject data = JSON.parseObject(result.getContent()); + String code = Objects.requireNonNull(data).getString("code"); + String msg = Objects.requireNonNull(data).getString("msg"); + if(code.equals("0")){ + // 将组织机构数据封装至List + accessToken = Objects.requireNonNull(data).getJSONObject("data").getString("accessToken"); + //new BaseBean().writeLog("Token授权==>"+accessToken); + }else{ + //new BaseBean().writeLog("Token授权异常,code==>"+code+",msg==>"+msg); + } + } + } + //new BaseBean().writeLog("Token授权,accessToken==>"+accessToken); + return accessToken; + } + + public String createToken(String clientId,String appId,String appSecret,String address,String tokenurl) throws Exception{ + String accessToken=""; + OkHttpClient client = new OkHttpClient().newBuilder().build(); + Mapparams =new HashMap (); + params.put("clientId",clientId); + params.put("appId",appId); + params.put("appSecret",appSecret); + MediaType mediaType = MediaType.parse("application/json"); + RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(params)); + Request request = new Request.Builder() + .url(address+tokenurl) + .method("POST", body) + .addHeader("Content-Type", "application/json") + .build(); + Response response = client.newCall(request).execute(); + if (response.isSuccessful()) { + Result result = Result.success(Objects.requireNonNull(response.body()).string()); + if (result.isOk()) { + JSONObject data = JSON.parseObject(result.getContent()); + String code = Objects.requireNonNull(data).getString("code"); + String msg = Objects.requireNonNull(data).getString("msg"); + if(code.equals("0")){ + // 将组织机构数据封装至List + accessToken = Objects.requireNonNull(data).getJSONObject("data").getString("accessToken"); + //new BaseBean().writeLog("Token授权==>"+accessToken); + }else{ + //new BaseBean().writeLog("Token授权异常,code==>"+code+",msg==>"+msg); + } + } + } + //new BaseBean().writeLog("Token授权,accessToken==>"+accessToken); + return accessToken; + } + + /** + * 获取当前人所能看到所有数据 + */ + public String getEyCustomRigthSql(int userid,String tablename){ + String returnStr = " select id from "+tablename+" where "; + String matchsql ="select * from uf_stand_match_conf where tablename=?"; + RecordSet recordSet=new RecordSet(); + recordSet.executeQuery(matchsql,tablename); + if(recordSet.next()){ + try { + ResourceComInfo resourceComInfo=new ResourceComInfo(); + String workcode=resourceComInfo.getWorkcode(userid+"");//员工工号 + String currentroleids =getUserAllRole(userid);//获取当前人员所有角色id + String georegion_fieldname =Util.null2String(recordSet.getString("georegion_fieldname")); + String legalentity_fieldname =Util.null2String(recordSet.getString("legalentity_fieldname")); + String type_fieldname =Util.null2String(recordSet.getString("type_fieldname")); + String codeblock_fieldname =Util.null2String(recordSet.getString("codeblock_fieldname")); + String engagementcode_fieldname =Util.null2String(recordSet.getString("engagementcode_fieldname")); + //业务维度 + if(StringUtil.isNotBlank(codeblock_fieldname)){ + String codeblocksql = getEyCodeBlockRightSql(workcode,codeblock_fieldname); + if(StringUtil.isNotBlank(codeblocksql)){ + returnStr =returnStr+codeblocksql; + } + } + //3.1先查询中间匹配表-firm + //判断台账中间表是否配置完全 + if(StringUtil.isNotBlank(georegion_fieldname)&&StringUtil.isNotBlank(legalentity_fieldname)) { + String firmsql = getEyfirmRightSql(type_fieldname,georegion_fieldname, legalentity_fieldname, currentroleids); + if (StringUtil.isNotBlank(firmsql)) { + returnStr = returnStr + firmsql; + } + } + //3.2先查询中间匹配表-gds + if(StringUtil.isNotBlank(type_fieldname)) { + String typesql =getEyGdsRightSql(type_fieldname,currentroleids); + if(StringUtil.isNotBlank(typesql)){ + returnStr = returnStr + typesql; + } + } + writeLog("getEyCustomRigthSql,returnStr==>"+returnStr); + } catch (Exception e) { + e.printStackTrace(); + } + } + + return returnStr; + } + + /** + *业务维度权限 + */ + public String getEyCodeBlockRightSql(String workcode,String codeblock_fieldname){ + String result=""; + //1、项目卡片中所有成员 + String codeblocksql ="select codeblock from uf_xmjbxxjmbd where id in (" + + "select mainid from uf_xmjbxxjmbd_dt2 where role_gpn='"+workcode+"' " + + ")"; + //2、通过第三接口获取公司高层维护的codeblock + codeblocksql = codeblocksql +" union " + + " select codeblock from uf_permisson_conf_business where gpn='"+workcode+"' "; + result = " ( "+codeblock_fieldname+" in ("+codeblocksql+") ) or"; + writeLog("codeblocksql==>"+codeblocksql); + return result; + } + + /** + *FIRM财务维度权限 + */ + public String getEyfirmRightSql(String type_fieldname,String georegion_fieldname,String legalentity_fieldname,String currentroleids) { + String result=""; + RecordSet rs =new RecordSet(); + String firmrolesql =" select legalentity,georegion,roleids from uf_permissionconfig where isopen=0"; + rs.executeQuery(firmrolesql,new Object[0]); + List> firmmatchlist =new ArrayList >(); + while(rs.next()){ + String roleids =Util.null2String(rs.getString("roleids")); + String legalentity =Util.null2String(rs.getString("legalentity")); + String georegion =Util.null2String(rs.getString("georegion")); + //判断规则中间表是否配置完全 + if(!legalentity.equals("")&&!georegion.equals("")){ + String[] currentroleidarry =currentroleids.split(","); + //判断当前用户所有角色与规则表的角色是否匹配 + for(String roleid:currentroleidarry){ + if((","+roleid+",").indexOf(","+roleids+",")>=0){ + //legalentity和georegion封装 + HashMap rolematch =new HashMap (); + rolematch.put("legalentity",legalentity); + rolematch.put("georegion",georegion); + firmmatchlist.add(rolematch); + break; + } + } + } + } + //遍历legalentity和georegion封装的map 转换sql + if(firmmatchlist.size()>0){ + for(Map match:firmmatchlist){ + String type =Util.null2String(match.get("type")); + String legalentity =Util.null2String(match.get("legalentity")); + String georegion =Util.null2String(match.get("georegion")); + if(StringUtil.isNotBlank(type)){ + String firmsql =""; + String lesql = legalentity_fieldname + " in ("; + String geosql = georegion_fieldname + " in ("; + String[] typearry =type.split(","); + for(String t:typearry){ + firmsql =firmsql+type_fieldname+"='"+t+"' and"; + if(StringUtil.isNotBlank(legalentity)){ + String[] legalentityarry =legalentity.split(","); + for(String le:legalentityarry){ + lesql =lesql+"'"+le+"',"; + } + lesql=lesql.substring(0,lesql.length()-1)+")"; + firmsql =firmsql+lesql+" and"; + } + + if(StringUtil.isNotBlank(georegion)){ + String[] georegionarry =georegion.split(","); + for(String geo:georegionarry){ + geosql =geosql+"'"+geo+"',"; + } + geosql=geosql.substring(0,geosql.length()-1)+")"; + firmsql =firmsql+geosql+" and"; + } + } + result =result+"("+firmsql.substring(0,firmsql.length()-3)+")or"; + } + } + } + writeLog("result==>"+result); + return result; + } + + /** + *GDS财务维度权限 + */ + public String getEyGdsRightSql(String type_fieldname,String currentroleids){ + String result =""; + List> gdsmatchlist =new ArrayList >(); + RecordSet rs =new RecordSet(); + String gdsrolesql =" select type,legalentity,roleids from uf_permisson_conf_gds where isopen=0 "; + rs.executeQuery(gdsrolesql,new Object[0]); + while(rs.next()){ + String roleids =Util.null2String(rs.getString("roleids")); + String type =Util.null2String(rs.getString("type")); + if(!type.equals("")){ + String[] currentroleidarry =currentroleids.split(","); + //判断当前用户所有角色与规则表的角色是否匹配 + for(String roleid:currentroleidarry){ + if((","+roleid+",").indexOf(","+roleids+",")>=0){ + //legalentity和georegion封装 + HashMap rolematch =new HashMap (); + rolematch.put("type",type); + gdsmatchlist.add(rolematch); + break; + } + } + } + } + if(gdsmatchlist.size()>0){ + Set typeset =new HashSet(); + for(Map match:gdsmatchlist){ + String type =Util.null2String(match.get("type")); + String[] typearry =type.split(","); + for(String value:typearry){ + typeset.add(value); + } + } + for(String s:typeset){ + result =result + "("+type_fieldname+"='"+s+"') or"; + } + } + return result; + } + + public Map getConfidentialInfo(String opprCode,String paceFolderId,String clientId){ + Map result =new HashMap <>(); + String eventKey = "checkopportunitypaceandclient"; //事件标识 + Map body =new HashMap (); + Map params =new HashMap (); + List> reqdata =new ArrayList <>(); + params.put("opprCode",opprCode); + params.put("paceFolderId",paceFolderId); + params.put("clientId",clientId); + reqdata.add(params); + body.put("body",reqdata); + String paramsstr = JSON.toJSONString(body); //事件请求参数 + //EsbService其他方法及说明见ESB API接口说明文档 + EsbService service = EsbClient.getService(); //获取 ESB 服务 + String clientdetailjsonstr = service.execute(eventKey, paramsstr); + new BaseBean().writeLog("getConfidentialInfo,JsonStr==>"+clientdetailjsonstr); + if(StringUtils.isNotBlank(clientdetailjsonstr)){ + JSONObject jsonObject=JSON.parseObject(clientdetailjsonstr); + JSONArray resultdata =jsonObject.getJSONObject("data").getJSONArray("data"); + String errorStr =""; + String isConfidential ="1"; + for(int i=0;i0) { + for (int j = 0; j < opprsIsConfidential.size(); j++) { + String isConfidentialflag =Util.null2String(opprsIsConfidential.getJSONObject(j).getString("isConfidential")); + if (isConfidentialflag.equals("true")) { + isConfidential = "0"; + } + } + } + } + result.put("errorstr",errorStr); + result.put("isConfidential",isConfidential); + } + return result; + } + + public boolean getLegalEffective(String bucode,String oucode,String mucode,String smucode){ + boolean result =false; + String eventKey = "getLegalEffective"; //事件标识 + Map params =new HashMap (); + params.put("buCode",bucode); + params.put("ouCode",oucode); + params.put("muCode",mucode); + params.put("smuCode",smucode); + String paramsstr = JSON.toJSONString(params); //事件请求参数 + //EsbService其他方法及说明见ESB API接口说明文档 + EsbService service = EsbClient.getService(); //获取 ESB 服务 + String clientdetailjsonstr = service.execute(eventKey, paramsstr); + new BaseBean().writeLog("clientdetailjsonstr,getLegalEffective==>"+clientdetailjsonstr); + + if (StringUtils.isNotBlank(clientdetailjsonstr)) { + JSONObject jsonObject = JSON.parseObject(clientdetailjsonstr); + JSONObject resultdata = jsonObject.getJSONObject("data").getJSONObject("data"); + result = resultdata.getBoolean("isLegal"); + } + + return result; + } + + /** + * 获取预算信息 + * @param eventKey 事件key + * @param eventKey primaryKey + */ + public Map getBudgetInfo(String eventKey,String primaryKey){ + Map result =new HashMap <>(); + //事件标识 + Map params_mmt =new HashMap (); + params_mmt.put("PrimaryKey",primaryKey); + String paramsstr_mmt = JSON.toJSONString(params_mmt); //事件请求参数 + //EsbService其他方法及说明见ESB API接口说明文档 + EsbService service = EsbClient.getService(); //获取 ESB 服务 + String mmtdetailjsonstr = service.execute(eventKey, paramsstr_mmt); + new BaseBean().writeLog("getBudgetInfo===>"+mmtdetailjsonstr); + if(StringUtils.isNotBlank(mmtdetailjsonstr)){ + JSONObject jsonObject=JSON.parseObject(mmtdetailjsonstr); + if(jsonObject.getJSONObject("data").getJSONArray("list")!=null) { + JSONObject resultdata = jsonObject.getJSONObject("data").getJSONArray("list").getJSONObject(0); + if (eventKey.equals("smarthubbudgetdetail")) { + String startDate =resultdata.getString("startDate"); + String closeDate =resultdata.getString("closeDate"); + if(!startDate.equals("")){ + result.put("estimated_start_date", startDate.substring(0,10)); + }else{ + result.put("estimated_start_date", ""); + } + if(!closeDate.equals("")){ + result.put("estimated_close_date", closeDate.substring(0,10)); + }else{ + result.put("estimated_close_date", ""); + } + + } else { + result.put("estimated_start_date", formatDate(resultdata.getString("estimatedStartDate"))); + result.put("estimated_close_date", formatDate(resultdata.getString("estimatedEndDate"))); + } + if (eventKey.equals("smarthubbudgetdetail")) { + result.put("eaf", formatDouble(Util.null2String(resultdata.getString("eaf")))); + } else { + result.put("eaf", formatDouble(Util.null2String(resultdata.getString("engagementAdjustedFactor")))); + } + result.put("standard_engagement_revenue", resultdata.getString("ser")); + result.put("net_engagement_revenue", resultdata.getString("ner")); + if (eventKey.equals("smarthubbudgetdetail")) { + result.put("current_year_total_revenue", formatDouble(Util.null2String(resultdata.getString("ter")))); + } else { + result.put("current_year_total_revenue", Util.null2String(resultdata.getString("currentFyTer"))); + } + if (eventKey.equals("smarthubbudgetdetail")) { + result.put("margin", "0.00"); + } else { + result.put("margin", formatDouble(Util.null2String(resultdata.getString("marginPercent")))); + } + if (eventKey.equals("smarthubbudgetdetail")) { + result.put("partner_involvement", formatDouble(Util.null2String(resultdata.getString("partnerInvolvement")))); + } else { + result.put("partner_involvement", formatDouble(Util.null2String(resultdata.getString("partnerLeverage")))); + } + result.put("erp1", formatDouble(Util.null2String(resultdata.getString("erp")))); + + String expenses =Util.null2String(resultdata.getString("totalExpense")); + if(expenses.equals("")){ + expenses ="0.00"; + } + result.put("expenses",expenses); + if (eventKey.equals("smarthubbudgetdetail")) { + result.put("margin1", "0.00"); + } else { + result.put("margin1", resultdata.getString("margin")); + } + if (eventKey.equals("smarthubbudgetdetail")) { + result.put("total_cost", "0.00"); + } else { + result.put("total_cost", Util.null2String(resultdata.getString("stdCost"))); + } + String hours =Util.null2String(resultdata.getString("totalHours")); + if(hours.equals("")){ + hours ="0.00"; + } + result.put("hours",hours ); + } + new BaseBean().writeLog(JSON.toJSONString(result)); + } + return result; + } + + /** + * 获取客户信息 + * @param clientId 客户id + */ + public Map getCustomInfo(String clientId){ + Map result =new HashMap <>(); + String eventKey = "clientdetail"; //事件标识 + Map params =new HashMap (); + params.put("clientId",clientId); + String paramsstr = JSON.toJSONString(params); //事件请求参数 + //EsbService其他方法及说明见ESB API接口说明文档 + EsbService service = EsbClient.getService(); //获取 ESB 服务 + String clientdetailjsonstr = service.execute(eventKey, paramsstr); + String clientScope =""; + String chineseName =""; + new BaseBean().writeLog("clientdetailjsonstr,getCustomInfo==>"+clientdetailjsonstr); + if(StringUtils.isNotBlank(clientdetailjsonstr)){ + JSONObject jsonObject=JSON.parseObject(clientdetailjsonstr); + String returncode =jsonObject.getString("code"); + if(returncode.equals("100")){ + JSONObject resultdata =jsonObject.getJSONObject("data").getJSONObject("result"); + clientScope =Util.null2String(resultdata.getString("clientScope")); + chineseName =Util.null2String(resultdata.getString("chineseName")); + result.put("client_name",chineseName); + if(clientScope.equals("100")){ + result.put("client_type","0"); + }else if (clientScope.equals("101")){ + result.put("client_type","1"); + }else if (clientScope.equals("102")){ + result.put("client_type","2"); + } + } + result.put("code",returncode); + }else{ + result.put("code","-1"); + result.put("client_name",""); + result.put("client_type",""); + } + new BaseBean().writeLog("getCustomInfo,returnmap==>"+JSON.toJSONString(result)); + return result; + } + + private static String formatDouble(String value){ + String result=""; + if(value.equals("")){ + result ="0.00"; + }else{ + BigDecimal bigDecimal =new BigDecimal(value); + result = bigDecimal.divide(new BigDecimal(100)).toString(); + + } + return result; + } + + private static String formatDate(String datestr){ + long time = Long.parseLong(datestr); + Date date = new Date(time); + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); + String str = dateFormat.format(date); + return str; + } + + public static boolean vaildateImportEnagementName(String engagementname,String global_service_code){ + boolean flag=false; + if(engagementname.equals("")||global_service_code.equals("")){ + return flag; + } + RecordSet recordSet1=new RecordSet(); + String perfix = engagementname.substring(0, 3); + recordSet1.executeQuery("select id from uf_mcgzb where global_service_code=? and mcgz=?",global_service_code,perfix); + if(recordSet1.next()){ + flag =true; + } + return flag; + } + +} diff --git a/src/main/java/weaver/xuanran/wang/eny/data_async/util/EyDataAsyncTokenUtil.java b/src/main/java/weaver/xuanran/wang/eny/data_async/util/EyDataAsyncTokenUtil.java index 9ca81e4..1c15f2c 100644 --- a/src/main/java/weaver/xuanran/wang/eny/data_async/util/EyDataAsyncTokenUtil.java +++ b/src/main/java/weaver/xuanran/wang/eny/data_async/util/EyDataAsyncTokenUtil.java @@ -33,20 +33,11 @@ public class EyDataAsyncTokenUtil { **/ public static String getToken(String url, Map params) { if(token == null){ - synchronized (EyDataAsyncTokenUtil.class){ - if(token == null){ - return getTokenByHTTP(url, params); - } - } + return getTokenByHTTP(url, params); } long expiryTime = token.getExpiresTime(); if(System.currentTimeMillis() >= expiryTime){ - synchronized (EyDataAsyncTokenUtil.class){ - expiryTime = token.getExpiresTime(); - if(System.currentTimeMillis() >= expiryTime){ - return getTokenByHTTP(url, params); - } - } + return getTokenByHTTP(url, params); } return token.getAccessToken(); } diff --git a/src/test/java/xuanran/wang/http_test/test/TestMain.java b/src/test/java/xuanran/wang/http_test/test/TestMain.java index 2a17f12..f6be11f 100644 --- a/src/test/java/xuanran/wang/http_test/test/TestMain.java +++ b/src/test/java/xuanran/wang/http_test/test/TestMain.java @@ -4,7 +4,7 @@ import aiyh.utils.httpUtil.ResponeVo; import basetest.BaseTest; import com.alibaba.fastjson.JSONObject; import org.junit.Test; -import xuanran.wang.common.entity.CusResponseSuccess; +import xuanran.wang.rest_test.pojo.CusRestTemplateResponse; import xuanran.wang.rest_test.CusRestTemplate; import java.util.HashMap; @@ -20,26 +20,20 @@ public class TestMain extends BaseTest { @Test public void testA(){ - CusResponseSuccess builder = - CusResponseSuccess.builder() + CusRestTemplateResponse builder = + CusRestTemplateResponse.builder() .checkResponse(true) .successField("code") .successValue(0) .errorMsg("msg") .build(); CusRestTemplate restTemplate = new CusRestTemplate(); - Map map = new HashMap<>(); - builder.setCall(e->{ - map.put("msg", e.getMessage()); - map.put("status", false); - }); try { ResponeVo vo = restTemplate.apiGet("https://gl.shstx.cn:48002/auth/oauth/token?grant_type=client_credentials&client_id=fanwei&client_secret=b7c20b12cb124cbebb0b8833caac6b87", new HashMap<>(), new HashMap<>(), builder); Map o = restTemplate.parseObj(vo.getResponseMap(), "", Map.class); System.out.println("token : " + o); }catch (Exception e){ System.out.println("error : " + e.getMessage()); - System.out.println("e map : " + JSONObject.toJSONString(map)); System.out.println("cusSuccess : " + JSONObject.toJSONString(builder)); } diff --git a/src/test/java/xuanran/wang/rest_test/AbstractCusRestTemplate.java b/src/test/java/xuanran/wang/rest_test/AbstractCusRestTemplate.java new file mode 100644 index 0000000..231f66a --- /dev/null +++ b/src/test/java/xuanran/wang/rest_test/AbstractCusRestTemplate.java @@ -0,0 +1,188 @@ +package xuanran.wang.rest_test; + +import aiyh.utils.ThreadPoolConfig; +import aiyh.utils.Util; +import aiyh.utils.excention.CustomerException; +import aiyh.utils.httpUtil.ResponeVo; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import org.apache.commons.collections.MapUtils; +import org.apache.log4j.Logger; +import xuanran.wang.rest_test.pojo.CusRestTemplateResponse; +import xuanran.wang.log.cus_api_log.CusApiLogUtil; +import xuanran.wang.log.cus_api_log.dto.CusApiLogBaseDto; +import xuanran.wang.rest_test.impl.CusGetRequest; +import xuanran.wang.rest_test.impl.CusPostRequest; +import xuanran.wang.rest_test.interfaces.CusApiRequestInterface; + +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.ExecutorService; + +/** + *

+ * + * @author xuanran.wang + * @date 2023/7/13 09:55 + */ +public abstract class AbstractCusRestTemplate { + private static final int HTTP_SUCCESS_CODE = 200; + protected Logger log = Util.getLogger(); + private static final Map FUN = new HashMap<>(); + private static final ExecutorService EXECUTOR_SERVICE = ThreadPoolConfig.createThreadPoolInstance(); + protected static final Integer GET = 1; + protected static final Integer POST = 2; + protected static final Integer PUT = 3; + protected static final Integer DELETE = 4; + + static { + FUN.put(GET, new CusGetRequest()); + FUN.put(POST, new CusPostRequest()); + } + + protected ResponeVo sendRequest(String url, Object params, Map headers, + CusRestTemplateResponse cusSuccess, Integer type){ + try { + requestBeforeInit(url, params, cusSuccess); + ResponeVo vo = FUN.get(type).execute(url, params, headers, cusSuccess); + requestAfterInit(cusSuccess, vo); + checkResponse(url, vo, params, headers, cusSuccess); + successCallBack(cusSuccess); + return vo; + }catch (Exception e){ + errorCallBack(e, cusSuccess); + throw new CustomerException("send request error! : [ " + e.getMessage() + " ]", e); + } + } + + /** + *

根据cusSuccess对象校验响应是否成功

+ * @author xuanran.wang + * @dateTime 2023/7/7 17:17 + * @param url 请求地址 + * @param responseVo 响应对象 + * @param o 参数 + * @param cusSuccess 请求成功对象 + **/ + private void checkResponse(String url, ResponeVo responseVo, + Object o, Map header, + CusRestTemplateResponse cusSuccess) { + if (Objects.isNull(cusSuccess) || !cusSuccess.isCheckResponse()) { + return; + } + if (responseVo.getCode() != HTTP_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(o), JSON.toJSONString(header), responseVo.getCode(), // 相应状态码 + responseVo.getEntityString())); // 相应内容 + throw new CustomerException(Util.logStr("can not fetch [{}]", url)); // 自定义异常类 create 2022/3/9 2:20 PM 构建日志字符串 + } + Map response; + if (cusSuccess.getCusDataDecipher() != null) { + response = cusSuccess.getCusDataDecipher().decoder(responseVo); + } else { + response = responseVo.getResponseMap(); // 根据相应结果转化为map集合 + } + if(MapUtils.isEmpty(response)){ + return; + } + String responseValue = Util.null2DefaultStr(response.get(cusSuccess.getSuccessField()), ""); + String msg = Util.null2DefaultStr(response.get(cusSuccess.getErrorMsg()), ""); + cusSuccess.setMsg(msg); + if (!responseValue.equals(Util.null2DefaultStr(cusSuccess.getSuccessValue(), ""))) { + throw new CustomerException(Util.logStr("接口地址:[{}], 接口响应码不为: [{}], 接口响应信息: {}", url, cusSuccess.getSuccessValue(), msg)); // 自定义异常类 create 2022/3/9 2:20 PM 构建日志字符串 + } + } + + /** + *

请求前填充参数

+ * @author xuanran.wang + * @dateTime 2023/7/7 17:20 + * @param url url + * @param params 请求参数 + * @param cusSuccess 自定义成功对象 + **/ + private void requestBeforeInit(String url, Object params, CusRestTemplateResponse cusSuccess){ + if(!Objects.isNull(cusSuccess)){ + cusSuccess.setUrl(url); + cusSuccess.setRequestParam(params); + } + } + + /** + *

请求前填充参数

+ * @author xuanran.wang + * @dateTime 2023/7/7 17:20 + * @param cusSuccess 自定义成功对象 + * @param vo 响应对象 + **/ + private void requestAfterInit(CusRestTemplateResponse cusSuccess, ResponeVo vo){ + if(!Objects.isNull(cusSuccess)){ + cusSuccess.setVo(vo); + cusSuccess.setResponse(vo.getResponseMap()); + } + } + + + /** + *

请求成功执行自定义回调

+ * @author xuanran.wang + * @dateTime 2023/7/7 17:21 + * @param cusSuccess 自定义成功对象 + **/ + private void successCallBack(CusRestTemplateResponse cusSuccess){ + if(!Objects.isNull(cusSuccess) && !Objects.isNull(cusSuccess.getSuccessCallBack())){ + cusSuccess.getSuccessCallBack().accept(cusSuccess.getLogDto()); + } + writeLog(cusSuccess); + } + + /** + *

请求失败执行自定义回调

+ * @author xuanran.wang + * @dateTime 2023/7/7 17:21 + * @param e 异常 + * @param cusSuccess 自定义成功对象 + **/ + private void errorCallBack(Exception e, CusRestTemplateResponse cusSuccess){ + if(!Objects.isNull(cusSuccess) && !Objects.isNull(cusSuccess.getErrorCallBack())){ + cusSuccess.setException(e); + cusSuccess.getErrorCallBack().accept(e,cusSuccess.getLogDto()); + } + writeLog(cusSuccess); + } + + private void writeLog(CusRestTemplateResponse cusResponseSuccess){ + if(!Objects.isNull(cusResponseSuccess) && cusResponseSuccess.isWriteLog()){ + if(cusResponseSuccess.isAsyncWriteLog()){ + EXECUTOR_SERVICE.execute(()-> executeWriteLog(cusResponseSuccess)); + }else { + executeWriteLog(cusResponseSuccess); + } + } + } + + private void executeWriteLog(CusRestTemplateResponse cusResponseSuccess){ + try { + CusApiLogBaseDto dto = cusResponseSuccess.getLogDto(); + dto.setRequestParam(JSONObject.toJSONString(cusResponseSuccess.getRequestParam())); + dto.setRequestUrl(cusResponseSuccess.getUrl()); + dto.setResponseMsg(cusResponseSuccess.getMsg()); + dto.setResponse(JSONObject.toJSONString(cusResponseSuccess.getResponse())); + dto.setRequestSuccess(0); + dto.setResponseMsg(dto.getResponseMsg()); + Exception error = cusResponseSuccess.getException(); + if(null != error){ + dto.setRequestSuccess(1); + dto.setException(error.getMessage()); + } + CusApiLogUtil.insertApiLog(dto, Util.getIntValue(cusResponseSuccess.getLogModelId(),-1)); + }catch (Exception e){ + log.error("write log error : " + e.getMessage(), e); + } + } + + + +} diff --git a/src/test/java/xuanran/wang/rest_test/CusRestTemplate.java b/src/test/java/xuanran/wang/rest_test/CusRestTemplate.java index 5eb6838..0b358ae 100644 --- a/src/test/java/xuanran/wang/rest_test/CusRestTemplate.java +++ b/src/test/java/xuanran/wang/rest_test/CusRestTemplate.java @@ -1,10 +1,7 @@ package xuanran.wang.rest_test; -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.alibaba.fastjson.JSONObject; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JavaType; @@ -12,8 +9,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.type.TypeFactory; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; -import xuanran.wang.common.entity.CusResponseSuccess; +import xuanran.wang.rest_test.pojo.CusRestTemplateResponse; import java.util.List; import java.util.Map; @@ -25,11 +21,8 @@ import java.util.Objects; * @author xuanran.wang * @date 2023/7/7 10:56 */ -public class CusRestTemplate { +public class CusRestTemplate extends AbstractCusRestTemplate{ private static final ObjectMapper objectMapper = new ObjectMapper(); - private final Logger log = Util.getLogger(); - private final HttpUtils httpUtils = new HttpUtils(); - private static final int HTTP_SUCCESS_CODE = 200; /** *

get请求

@@ -43,17 +36,8 @@ public class CusRestTemplate { **/ public ResponeVo apiGet(String url, Map params, Map headers, - CusResponseSuccess cusSuccess) { - ResponeVo responeVo; - try { - requestBeforeInit(url, params, cusSuccess); - responeVo = httpUtils.apiGet(url, params, headers); - checkResponse(url, responeVo, params, cusSuccess); - return responeVo; - } catch (Exception e) { - callBack(e,cusSuccess); - throw new CustomerException(Util.logStr("发送请求发生异常! : {}", e.getMessage())); // 自定义异常类 create 2022/3/9 2:20 PM 构建日志字符串 - } + CusRestTemplateResponse cusSuccess) { + return sendRequest(url, params, headers, cusSuccess, GET); } @@ -67,51 +51,8 @@ public class CusRestTemplate { * @param cusSuccess 请求成功对象 * @return 响应对象 **/ - public ResponeVo apiPost(String url, Object params, Map headers, CusResponseSuccess cusSuccess) { - ResponeVo responeVo; - try { - requestBeforeInit(url, params, cusSuccess); - responeVo = httpUtils.apiPostObject(url, params, headers); - checkResponse(url, responeVo, params, cusSuccess); - return responeVo; - } catch (Exception e) { - callBack(e,cusSuccess); - throw new CustomerException(Util.logStr("发送请求发生异常! : {}", e.getMessage())); // 自定义异常类 create 2022/3/9 2:20 PM 构建日志字符串 - } - } - - /** - *

根据cusSuccess对象校验响应是否成功

- * @author xuanran.wang - * @dateTime 2023/7/7 17:17 - * @param url 请求地址 - * @param responseVo 响应对象 - * @param o 参数 - * @param cusSuccess 请求成功对象 - **/ - private void checkResponse(String url, ResponeVo responseVo, Object o, CusResponseSuccess cusSuccess) { - if (Objects.isNull(cusSuccess) || !cusSuccess.isCheckResponse()) { - return; - } - cusSuccess.setVo(responseVo); - if (responseVo.getCode() != HTTP_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(o), JSON.toJSONString(httpUtils.getGlobalCache().header), responseVo.getCode(), // 相应状态码 - responseVo.getEntityString())); // 相应内容 - throw new CustomerException(Util.logStr("can not fetch [{}]", url)); // 自定义异常类 create 2022/3/9 2:20 PM 构建日志字符串 - } - Map response; - if (cusSuccess.getCusDataDecipher() != null) { - response = cusSuccess.getCusDataDecipher().decoder(responseVo); - } else { - response = responseVo.getResponseMap(); // 根据相应结果转化为map集合 - } - cusSuccess.setResponse(response); - String responseValue = Util.null2DefaultStr(response.get(cusSuccess.getSuccessField()), ""); - if (!responseValue.equals(Util.null2DefaultStr(cusSuccess.getSuccessValue(), ""))) { - throw new CustomerException(Util.logStr("接口地址:[{}], 接口响应码不为: [{}], 接口响应信息: {}", url, cusSuccess.getSuccessValue(), Util.null2DefaultStr(response.get(cusSuccess.getErrorMsg()), ""))); // 自定义异常类 create 2022/3/9 2:20 PM 构建日志字符串 - } + public ResponeVo apiPost(String url, Object params, Map headers, CusRestTemplateResponse cusSuccess) { + return sendRequest(url, params, headers, cusSuccess, POST); } /** @@ -208,33 +149,4 @@ public class CusRestTemplate { return dataObject; } - /** - *

请求前填充参数

- * @author xuanran.wang - * @dateTime 2023/7/7 17:20 - * @param url url - * @param params 请求参数 - * @param cusSuccess 自定义成功对象 - **/ - private void requestBeforeInit(String url, Object params, CusResponseSuccess cusSuccess){ - if(!Objects.isNull(cusSuccess)){ - cusSuccess.setUrl(url); - cusSuccess.setRequestParam(params); - } - } - - /** - *

请求失败执行自定义回调

- * @author xuanran.wang - * @dateTime 2023/7/7 17:21 - * @param e 异常 - * @param cusSuccess 自定义成功对象 - **/ - public void callBack(Exception e, CusResponseSuccess cusSuccess){ - if(!Objects.isNull(cusSuccess.getCall())){ - cusSuccess.setE(e); - cusSuccess.getCall().accept(e); - } - } - } diff --git a/src/test/java/xuanran/wang/rest_test/impl/CusGetRequest.java b/src/test/java/xuanran/wang/rest_test/impl/CusGetRequest.java new file mode 100644 index 0000000..3c0cbaa --- /dev/null +++ b/src/test/java/xuanran/wang/rest_test/impl/CusGetRequest.java @@ -0,0 +1,25 @@ +package xuanran.wang.rest_test.impl; + +import aiyh.utils.httpUtil.ResponeVo; +import aiyh.utils.httpUtil.util.HttpUtils; +import xuanran.wang.rest_test.pojo.CusRestTemplateResponse; +import xuanran.wang.rest_test.interfaces.CusApiRequestInterface; + +import java.io.IOException; +import java.util.Map; + +/** + *

+ * + * @author xuanran.wang + * @date 2023/7/13 10:07 + */ +public class CusGetRequest implements CusApiRequestInterface { + private final HttpUtils httpUtils = new HttpUtils(); + + @Override + public ResponeVo execute(String url, Object params, Map headers, CusRestTemplateResponse cusSuccess) throws IOException { + return httpUtils.apiGet(url, (Map) params, headers); + } + +} diff --git a/src/test/java/xuanran/wang/rest_test/impl/CusPostRequest.java b/src/test/java/xuanran/wang/rest_test/impl/CusPostRequest.java new file mode 100644 index 0000000..0383fcb --- /dev/null +++ b/src/test/java/xuanran/wang/rest_test/impl/CusPostRequest.java @@ -0,0 +1,24 @@ +package xuanran.wang.rest_test.impl; + +import aiyh.utils.httpUtil.ResponeVo; +import aiyh.utils.httpUtil.util.HttpUtils; +import xuanran.wang.rest_test.pojo.CusRestTemplateResponse; +import xuanran.wang.rest_test.interfaces.CusApiRequestInterface; + +import java.io.IOException; +import java.util.Map; + +/** + *

+ * + * @author xuanran.wang + * @date 2023/7/13 10:09 + */ +public class CusPostRequest implements CusApiRequestInterface { + private final HttpUtils httpUtils = new HttpUtils(); + + @Override + public ResponeVo execute(String url, Object params, Map headers, CusRestTemplateResponse cusSuccess) throws IOException { + return httpUtils.apiPostObject(url, params, headers); + } +} diff --git a/src/test/java/xuanran/wang/rest_test/interfaces/CusApiRequestInterface.java b/src/test/java/xuanran/wang/rest_test/interfaces/CusApiRequestInterface.java new file mode 100644 index 0000000..ccd9beb --- /dev/null +++ b/src/test/java/xuanran/wang/rest_test/interfaces/CusApiRequestInterface.java @@ -0,0 +1,19 @@ +package xuanran.wang.rest_test.interfaces; + +import aiyh.utils.httpUtil.ResponeVo; +import xuanran.wang.rest_test.pojo.CusRestTemplateResponse; + +import java.io.IOException; +import java.util.Map; + +/** + *

+ * + * @author xuanran.wang + * @date 2023/7/13 10:06 + */ +public interface CusApiRequestInterface { + ResponeVo execute(String url, Object params, + Map headers, + CusRestTemplateResponse cusSuccess) throws IOException; +} diff --git a/src/test/java/xuanran/wang/rest_test/pojo/CusRestTemplateResponse.java b/src/test/java/xuanran/wang/rest_test/pojo/CusRestTemplateResponse.java new file mode 100644 index 0000000..dc15850 --- /dev/null +++ b/src/test/java/xuanran/wang/rest_test/pojo/CusRestTemplateResponse.java @@ -0,0 +1,50 @@ +package xuanran.wang.rest_test.pojo; + +import aiyh.utils.httpUtil.ResponeVo; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import weaver.xuanran.wang.common.service.CusDataDecipher; +import xuanran.wang.log.cus_api_log.dto.CusApiLogBaseDto; + +import java.util.Map; +import java.util.function.BiConsumer; +import java.util.function.Consumer; + + +/** + *

自定义请求条件

+ * + * @author xuanran.wang + * @date 2023/4/6 19:34 + */ +@Data +@Builder +@AllArgsConstructor +@NoArgsConstructor +public class CusRestTemplateResponse { + private ResponeVo vo; + private Object requestParam; + private String successField; + private Object successValue; + private String errorMsg; + private String dataKey; + private String msg; + private Map response; + private CusDataDecipher cusDataDecipher; + private String url; + private Exception exception; + @Builder.Default + private boolean checkResponse = true; + private BiConsumer errorCallBack; + @Builder.Default + private boolean writeLog = false; + private CusApiLogBaseDto logDto; + private String logModelId; + private Consumer successCallBack; + @Builder.Default + private boolean asyncWriteLog = true; + + +}