diff --git a/javascript/xuanran.wang/longgong/NewProductTest.js b/javascript/xuanran.wang/longgong/NewProductTest.js index b0f6285..ca63af7 100644 --- a/javascript/xuanran.wang/longgong/NewProductTest.js +++ b/javascript/xuanran.wang/longgong/NewProductTest.js @@ -8,8 +8,8 @@ const threeMonthIndex = 1; const submitWaitNode = WfForm.convertFieldNameToId("sftjddjd"); // 下次超时提醒日期 const timeoutRemindDateFiled = WfForm.convertFieldNameToId("cstxrq"); -// 跟踪天数 -const trackingDays = WfForm.getFieldValue(trackTimeField) <= 1 ? 15 : 30; +// 跟踪天数 <= 1 ? 15 : 30; +const trackingDaysField = WfForm.convertFieldNameToId("gzts") // 跟踪触发行数 const trackingLineField = WfForm.convertFieldNameToId("gzcfxs"); $(() => { @@ -44,6 +44,7 @@ function getNodeNum(){ let currentDate = getCurrentDate(); let dayDiff = getDaysDiff(firstSaleDate, currentDate); console.log('当前天数与首台销售日期相差天数 : ', dayDiff) + let trackingDays = WfForm.getFieldValue(trackingDaysField); return Math.floor(dayDiff / trackingDays) + 1; } @@ -52,6 +53,7 @@ function initTimeoutDate(){ let firstSaleDate = WfForm.getFieldValue(firstSaleDateField); const nodeNum = getNodeNum(); console.log('到达节点次数 ', nodeNum); + let trackingDays = WfForm.getFieldValue(trackingDaysField); console.log('跟踪天数 ', trackingDays); let computeTimeoutDate = addDays(firstSaleDate, nodeNum * trackingDays); console.log('计算下次超时日期 ', computeTimeoutDate); diff --git a/javascript/youhong.ai/pcn/workflow_code_block.js b/javascript/youhong.ai/pcn/workflow_code_block.js index f99dbcc..71111a0 100644 --- a/javascript/youhong.ai/pcn/workflow_code_block.js +++ b/javascript/youhong.ai/pcn/workflow_code_block.js @@ -688,15 +688,17 @@ $(() => { $(() => { const config = [{ // 源字段 - sourceField: '', + sourceField: 'htksrq', // 目标字段 - targetField: '', + targetField: 'htjsrq', // 日期加月份字段 - numberField: '' + numberField: 'contractperiod', + monthBase: 12 }, { - sourceField: '', - targetField: '', - numberField: '' + sourceField: 'syqksrq', + targetField: 'syqjsrq', + numberField: 'probationperiod', + monthBase: 1 }] runJs(); @@ -711,22 +713,26 @@ $(() => { let fieldId = WfForm.convertFieldNameToId(configItem.numberField) WfForm.bindFieldChangeEvent(fieldId, (obj, id, value) => { if ("" == value) { - WfForm.changeFieldValue(WfForm.convertFieldNameToId(configItem.targetField, {value: ""})) + WfForm.changeFieldValue(WfForm.convertFieldNameToId(configItem.targetField), {value: ""}) return } let sourceValue = WfForm.getFieldValue(WfForm.convertFieldNameToId(configItem.sourceField)); + if ("" == sourceValue) { + setTimeout(() => { + WfForm.changeFieldValue(fieldId, {value: ""}) + }, 10) + } let date = new Date(sourceValue) - date.setMonth(date.getMonth() + +value) - let objectDate = new Date(); - - - let day = objectDate.getDate(); - let month = objectDate.getMonth() + 1; - let year = objectDate.getFullYear(); - WfForm.changeFieldValue(WfForm.convertFieldNameToId(configItem.targetField, { + date.setMonth(date.getMonth() + +value * configItem.monthBase) + date.setDate(date.getDate() - 1) + let day = date.getDate(); + let month = date.getMonth() + 1; + let year = date.getFullYear(); + WfForm.changeFieldValue(WfForm.convertFieldNameToId(configItem.targetField), { value: `${year}-${fullNum(month)}-${fullNum(day)}` - })) + }) }) + } function fullNum(i) { @@ -738,4 +744,46 @@ $(() => { } }) -/* ******************* 计算年月日 end ******************* */ \ No newline at end of file +/* ******************* 计算年月日 end ******************* */ + + +/* ******************* 年假计算 start ******************* */ +$(() => { + let config = { + // 基础年假 + base: 21, + // 入职日期 + dateField: 'jrbsjjtsj', + // 年假 + targetField: 'nj' + } + + runJs() + + function runJs() { + WfForm.bindFieldChangeEvent(WfForm.convertFieldNameToId(config.dateField), (obj, id, value) => { + let date = new Date(value) + let nowDate = new Date() + let njValue = calculateBonus(date, nowDate, config) + if (value !== 0) { + WfForm.changeFieldValue(WfForm.convertFieldNameToId(config.targetField), {value: njValue}) + } + }) + + } + + function calculateBonus(startDate, endDate, config) { + const diffInMs = endDate.getTime() - startDate.getTime(); + const diffInYears = diffInMs / (1000 * 60 * 60 * 24 * 365); + + if (diffInYears < 3) { + return 0; + } else if (diffInYears >= 3 && diffInYears < 6) { + return config.base; + } else { + const extraYears = Math.floor((diffInYears - 3) / 3); + return config.base + extraYears * 2; + } + } +}) +/* ******************* 年假计算 end ******************* */ \ No newline at end of file diff --git a/src/main/java/aiyh/utils/Util.java b/src/main/java/aiyh/utils/Util.java index fd7046e..bb5deba 100644 --- a/src/main/java/aiyh/utils/Util.java +++ b/src/main/java/aiyh/utils/Util.java @@ -71,6 +71,7 @@ import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.function.BiConsumer; +import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.regex.Matcher; @@ -98,7 +99,7 @@ public class Util extends weaver.general.Util { public static final char DBC_SBC_STEP = 65248; // 全角半角转换间隔 public static final ExecutorService threadPool = ThreadPoolConfig.createThreadPoolInstance(); public static final String UF_CUS_DEV_CONFIG = "uf_cus_dev_config"; - private static final UtilService utilService = new UtilService(); + private static UtilService utilService = null; private static final RecordsetUtil recordsetUtil = new RecordsetUtil(); private static final RecordsetUtil recordsetTransUtil = new RecordsetUtil(); private static final UtilMapper mapper = recordsetUtil.getMapper(UtilMapper.class); @@ -110,12 +111,20 @@ public class Util extends weaver.general.Util { static { try { rs = new RecordSet(); + utilService = new UtilService(); } catch (Exception e) { e.printStackTrace(); new ToolUtil().writeErrorLog("\n初始化RecordSet失败!请检查系统是否正常启动!\n"); } } + public static UtilService getUtilService() { + if (utilService == null) { + return new UtilService(); + } + return utilService; + } + /** * 获取指定格式的当前时间 * @@ -1582,12 +1591,12 @@ public class Util extends weaver.general.Util { public static ApiConfigMainDTO queryApiConfig(String id) { // System.out.println(JSON.toJSONString(apiConfigMain)); - return utilService.getApiConfigMain(id); + return getUtilService().getApiConfigMain(id); } public static ApiConfigMainDTO queryApiConfigTree(String id) { // System.out.println(JSON.toJSONString(apiConfigMain)); - return utilService.getApiConfigMainTree(id); + return getUtilService().getApiConfigMainTree(id); } public static AZipOutputStream createZip(List inputList) throws IOException { @@ -1711,13 +1720,13 @@ public class Util extends weaver.general.Util { } public static Map queryLanguage(int groupId, int languageId) { - return utilService.queryLanguage(groupId, languageId); + return getUtilService().queryLanguage(groupId, languageId); } public static Map queryLanguage(int groupId, HttpServletRequest request, HttpServletResponse response) { User user = HrmUserVarify.getUser(request, response); int languageId = user.getLanguage(); - return utilService.queryLanguage(groupId, languageId); + return getUtilService().queryLanguage(groupId, languageId); } @@ -2920,6 +2929,17 @@ public class Util extends weaver.general.Util { submitWorkflowThread(requestId, userId, remark, 60); } + /** + *

异步提交流程,一般作用于action在节点前

+ * + * @param requestId 流程ID + * @param userId 用户id + * @param remark 签字意见 + */ + public static void submitWorkflowThread(Integer requestId, Integer userId, String remark, Consumer callback) { + submitWorkflowThread(requestId, userId, remark, 60, callback); + } + /** *

异步提交流程,一般作用于action在节点前

* @@ -2929,6 +2949,10 @@ public class Util extends weaver.general.Util { * @param seconds 延时多少秒提交 */ public static void submitWorkflowThread(Integer requestId, Integer userId, String remark, int seconds) { + submitWorkflowThread(requestId, userId, remark, seconds, null); + } + + public static void submitWorkflowThread(Integer requestId, Integer userId, String remark, int seconds, Consumer callback) { if (seconds <= 0) { seconds = 1; } @@ -2941,7 +2965,9 @@ public class Util extends weaver.general.Util { Util.getLogger().error("线程休眠失败", e); } int n = 0; + while (!Util.submitWorkflow(requestId, userId, remark)) { + log.info("异步提交流程失败,正在进行重试!!"); n++; try { Thread.sleep(1000 * 10); @@ -2949,10 +2975,17 @@ public class Util extends weaver.general.Util { e.printStackTrace(); } if (n > 5) { + if (callback != null) { + callback.accept(false); + } Util.getLogger().error("异步流程自动提交失败!"); break; } } + log.info("异步提交流程成功!"); + if (callback != null) { + callback.accept(true); + } }).start(); } @@ -4020,4 +4053,30 @@ public class Util extends weaver.general.Util { return filePath; } + public static String createTempFile(InputStream inputStream, String imageFileName, String tempDir) { + String filePath = getTempFilePath(tempDir, imageFileName); + try { + writeToFile(inputStream, filePath); + } catch (IOException e) { + throw new CustomerException("create temp file error!", e); + } + return filePath; + } + + public static void writeToFile(InputStream inputStream, String filePath) throws IOException { + Path path = Paths.get(filePath); + Path parentDir = path.getParent(); + if (parentDir != null) { + Files.createDirectories(parentDir); + } + Files.createFile(path); + + try (FileOutputStream outputStream = new FileOutputStream(filePath)) { + byte[] buffer = new byte[8192]; + int bytesRead; + while ((bytesRead = inputStream.read(buffer)) != -1) { + outputStream.write(buffer, 0, bytesRead); + } + } + } } diff --git a/src/main/java/aiyh/utils/action/SafeCusBaseAction.java b/src/main/java/aiyh/utils/action/SafeCusBaseAction.java index dbf0b05..92cdf9f 100644 --- a/src/main/java/aiyh/utils/action/SafeCusBaseAction.java +++ b/src/main/java/aiyh/utils/action/SafeCusBaseAction.java @@ -64,6 +64,7 @@ public abstract class SafeCusBaseAction implements Action { } try { Util.verifyRequiredField(this); + log.info("action trigger by " + src); if (!Strings.isNullOrEmpty(src)) { src = "submit"; } diff --git a/src/main/java/aiyh/utils/annotation/recordset/AssociationMethod.java b/src/main/java/aiyh/utils/annotation/recordset/AssociationMethod.java index 70d6607..b9c4a67 100644 --- a/src/main/java/aiyh/utils/annotation/recordset/AssociationMethod.java +++ b/src/main/java/aiyh/utils/annotation/recordset/AssociationMethod.java @@ -13,5 +13,8 @@ import java.lang.annotation.*; @Target(ElementType.METHOD) @Documented public @interface AssociationMethod { + int value(); + + String desc() default ""; } diff --git a/src/main/java/aiyh/utils/annotation/recordset/CollectionMethod.java b/src/main/java/aiyh/utils/annotation/recordset/CollectionMethod.java index d767632..9f8c64a 100644 --- a/src/main/java/aiyh/utils/annotation/recordset/CollectionMethod.java +++ b/src/main/java/aiyh/utils/annotation/recordset/CollectionMethod.java @@ -14,4 +14,6 @@ import java.lang.annotation.*; @Documented public @interface CollectionMethod { int value(); + + String desc() default ""; } diff --git a/src/main/java/aiyh/utils/dao/UtilDao.java b/src/main/java/aiyh/utils/dao/UtilDao.java index c5fd264..7af92cb 100644 --- a/src/main/java/aiyh/utils/dao/UtilDao.java +++ b/src/main/java/aiyh/utils/dao/UtilDao.java @@ -17,28 +17,28 @@ import java.util.List; public class UtilDao { private final RecordSet rs = new RecordSet(); - - + + public ApiConfigMainDTO getApiConfigMain(String id) { String query = "select id,workflow_type,api_url,api_name from uf_api_param_config where id = ?"; rs.executeQuery(query, id); return Util.recordeSet2Entity(rs, ApiConfigMainDTO.class, true); } - + public List getApiConfigDetail(int mainId) { String query = "select dt.id,dt.line_num,dt.param_name,dt.param_type,dt.object_child,dt.parent_line,dt.change_rule, " + - "dt.param_value,wf.fieldname workflow_field,wf.tablename tablename,dt.array_sql " + - "from uf_api_param_config_dt1 dt " + - "left join workflow_field_table_view wf on wf.id = dt.workflow_field " + - "where mainid = ? and (are_use is null or are_use = 1)"; + "dt.param_value,wf.fieldname workflow_field,wf.tablename tablename,dt.array_sql " + + "from uf_api_param_config_dt1 dt " + + "left join workflow_field_table_view wf on wf.id = dt.workflow_field " + + "where mainid = ? and (are_use is null or are_use = 1)"; rs.executeQuery(query, mainId); return Util.recordeSet2Array(rs, ApiConfigDetailDTO.class, true); } - + public List queryLanguage(int groupId) { String query = "select * from uf_multi_language_dt1 where mainid = ?"; rs.executeQuery(query, groupId); return Util.recordeSet2Array(rs, MultiLanguageDTO.class, true); } - + } diff --git a/src/main/java/aiyh/utils/fileUtil/pdf/PdfUtil.java b/src/main/java/aiyh/utils/fileUtil/pdf/PdfUtil.java index b6d62af..02180af 100644 --- a/src/main/java/aiyh/utils/fileUtil/pdf/PdfUtil.java +++ b/src/main/java/aiyh/utils/fileUtil/pdf/PdfUtil.java @@ -140,7 +140,7 @@ public class PdfUtil { FileOutputStream outputStreamTem; try { outputStreamTem = new FileOutputStream(tempPath); - } catch (FileNotFoundException e) { + } catch (Exception e) { throw new CustomerException("创建临时文件流和路径转换失败!", e); } PdfStamper pdfStamper = null; diff --git a/src/main/java/com/api/xuanran/wang/sh_bigdata/sso/controller/OtherSystemToOAController.java b/src/main/java/com/api/xuanran/wang/sh_bigdata/sso/controller/OtherSystemToOAController.java index 076bda2..668d3c6 100644 --- a/src/main/java/com/api/xuanran/wang/sh_bigdata/sso/controller/OtherSystemToOAController.java +++ b/src/main/java/com/api/xuanran/wang/sh_bigdata/sso/controller/OtherSystemToOAController.java @@ -45,12 +45,12 @@ public class OtherSystemToOAController { // 获取重定向地址和secret Map redirectUrlAndCorpsecret = service.getRedirectUrlAndCorpsecret(appId); String redirectUrl = Util.null2DefaultStr(redirectUrlAndCorpsecret.get("REDIRECTURL"),""); - log.info("successSendRedirectUrl : " + redirectUrl); if(StringUtils.isBlank(redirectUrl)){ throw new CustomerException("redirectUrl is null! " + JSONObject.toJSONString(redirectUrlAndCorpsecret)); } int userId = service.getUserFromOtherSys(code, redirectUrlAndCorpsecret); - SessionUtil.createSession(userId + "", request, response); + SessionUtil.createSession(String.valueOf(userId), request, response); + log.info("successSendRedirectUrl : " + redirectUrl); response.sendRedirect(redirectUrl); }catch (Exception e){ log.error("sso error : " + e.getMessage()); diff --git a/src/main/java/com/api/xuanran/wang/sh_bigdata/sso/mapper/OtherSystemToOAMapper.java b/src/main/java/com/api/xuanran/wang/sh_bigdata/sso/mapper/OtherSystemToOAMapper.java index f3c4884..c38b1b6 100644 --- a/src/main/java/com/api/xuanran/wang/sh_bigdata/sso/mapper/OtherSystemToOAMapper.java +++ b/src/main/java/com/api/xuanran/wang/sh_bigdata/sso/mapper/OtherSystemToOAMapper.java @@ -1,8 +1,11 @@ package com.api.xuanran.wang.sh_bigdata.sso.mapper; +import aiyh.utils.Util; import aiyh.utils.annotation.recordset.ParamMapper; import aiyh.utils.annotation.recordset.Select; import aiyh.utils.annotation.recordset.SqlMapper; +import aiyh.utils.annotation.recordset.SqlString; +import weaver.xuanran.wang.sh_bigdata.common.util.ShBigDataUtil; import java.util.Map; @@ -21,8 +24,8 @@ public interface OtherSystemToOAMapper { * @param outKey 外键id * @return oa ID **/ - @Select("select id from hrmresource where outkey = #{outKey}") - int selectUserIdByOutKey(@ParamMapper("outKey") String outKey); + @Select(custom = true) + int selectUserIdByOutKey(@SqlString String sql, @ParamMapper("outKey") String outKey); /** *

根据appId 查跳转的地址

* @author xuanran.wang diff --git a/src/main/java/com/api/xuanran/wang/sh_bigdata/sso/service/OtherSystemToOAService.java b/src/main/java/com/api/xuanran/wang/sh_bigdata/sso/service/OtherSystemToOAService.java index 7f736c4..69e69ec 100644 --- a/src/main/java/com/api/xuanran/wang/sh_bigdata/sso/service/OtherSystemToOAService.java +++ b/src/main/java/com/api/xuanran/wang/sh_bigdata/sso/service/OtherSystemToOAService.java @@ -21,7 +21,7 @@ public interface OtherSystemToOAService { * @param cusSuccess 自定义接口成功/失败标识 * @return 接口响应字段 **/ - int getUserIdByCode(String url, Map params, Map headers, CusSuccess cusSuccess, Map redirectUrlSecret); + Object getUserIdByCode(String url, Map params, Map headers, CusSuccess cusSuccess, Map redirectUrlSecret); /** *

根据第三方系统人员code匹配oa人员id

* @author xuanran.wang diff --git a/src/main/java/com/api/xuanran/wang/sh_bigdata/sso/service/impl/OtherSystemToOAServiceImpl.java b/src/main/java/com/api/xuanran/wang/sh_bigdata/sso/service/impl/OtherSystemToOAServiceImpl.java index 3e1581a..c07bd3c 100644 --- a/src/main/java/com/api/xuanran/wang/sh_bigdata/sso/service/impl/OtherSystemToOAServiceImpl.java +++ b/src/main/java/com/api/xuanran/wang/sh_bigdata/sso/service/impl/OtherSystemToOAServiceImpl.java @@ -28,12 +28,13 @@ public class OtherSystemToOAServiceImpl implements OtherSystemToOAService { .successField("code") .successValue(0) .errorMsg("msg") - .dataKey("data.id") + .dataKey("data." + Util.null2DefaultStr(ShBigDataUtil.getPropertiesValByKey("ssoInterfaceCompareField"), "id")) .build(); private final OtherSystemToOAMapper otherSystemToOAMapper = Util.getMapper(OtherSystemToOAMapper.class); private final Logger log = Util.getLogger(); + @Override - public int getUserIdByCode(String url, Map params, Map headers, CusSuccess cusSuccess, Map redirectUrlSecret) { + public Object getUserIdByCode(String url, Map params, Map headers, CusSuccess cusSuccess, Map redirectUrlSecret) { String secret = Util.null2DefaultStr(redirectUrlSecret.get("SECRET"), ""); log.info("secret : " + secret); if(StringUtils.isBlank(secret)){ @@ -48,7 +49,7 @@ public class OtherSystemToOAServiceImpl implements OtherSystemToOAService { params.put("code", code); // 获取第三方系统id String getUserInfoByCodeUrl = ShBigDataUtil.getPropertiesValByKey("getUserInfoByCodeUrl"); - int codeId; + Object codeId; try { codeId = getUserIdByCode(getUserInfoByCodeUrl, params, new HashMap<>(), cusSuccess, redirectUrlSecret); }catch (Exception e){ @@ -61,10 +62,12 @@ public class OtherSystemToOAServiceImpl implements OtherSystemToOAService { throw new CustomerException(e.getMessage()); } } - if(codeId < 0){ + String oaOutKey = Util.null2DefaultStr(codeId, ""); + if(StringUtils.isBlank(oaOutKey)){ throw new CustomerException(Util.logStr("code : {}, not found in {} .", code, getUserInfoByCodeUrl)); } - int id = otherSystemToOAMapper.selectUserIdByOutKey(codeId + ""); + String sql = "select id from hrmresource where " + Util.null2DefaultStr(ShBigDataUtil.getPropertiesValByKey("ssoOaCompareField"),"outkey") + " = #{outKey}"; + int id = otherSystemToOAMapper.selectUserIdByOutKey(sql, oaOutKey); if(id < 0){ throw new CustomerException(Util.logStr("code : {} not found in OA!", id)); } diff --git a/src/main/java/com/api/youhong/ai/pcn/organization/orgchart/mapper/OrgChartMapper.java b/src/main/java/com/api/youhong/ai/pcn/organization/orgchart/mapper/OrgChartMapper.java index 864fb93..0259a64 100644 --- a/src/main/java/com/api/youhong/ai/pcn/organization/orgchart/mapper/OrgChartMapper.java +++ b/src/main/java/com/api/youhong/ai/pcn/organization/orgchart/mapper/OrgChartMapper.java @@ -18,58 +18,58 @@ import java.util.List; @SqlMapper public interface OrgChartMapper { - - - /** - *

查询所有的在职状态人员

- * 2022/12/5 11:05 - * ****************************************** - * - * @param typeOfEmploymentField 人员自定义字段 - * @return List 返回的人员信息 - * @author youHong.ai ****************************************** - */ - @Select("select hrm.id, " + - " hrm.subcompanyid1 sub_company_id," + - " hrm.messagerurl avatar," + - " (case when cus.$t{lastNameEnField} is null then hrm.lastname " + - " else cus.$t{lastNameEnField} end) last_name, " + - " hrm.managerstr manager_str, " + - " hrm.jobtitle job_title_id, " + - " hrm.managerid manager_id, " + - " hrm.departmentid department_id, " + - " dept.DEPARTMENTNAME department_name, " + - " job.JOBTITLENAME job_title_name, " + - " uftb.$t{parentField} type_of_employment " + - "from hrmresource hrm " + - " inner join hrmjobtitles job on hrm.JOBTITLE = job.id " + - " inner join cus_fielddata cus on cus.ID = hrm.ID " + - " and cus.SCOPE = 'HrmCustomFieldByInfoType' " + - " and cus.SCOPEID = 1 " + - " inner join cus_fielddata cus1 on cus1.id = hrm.id" + - " and cus1.scope = 'HrmCustomFieldByInfoType' " + - " and cus1.scopeid = -1" + - " inner join hrmdepartment dept on dept.id = hrm.DEPARTMENTID " + - " inner join $t{typeOfEmploymentTable} uftb on uftb.$t{typeOfEmploymentIdField} = cus1.$t{typeOfEmploymentFiled} " + - "where hrm.status in (0, 1)") - List selectAll(@ParamMapper("typeOfEmploymentFiled") String typeOfEmploymentField, - @ParamMapper("lastNameEnField") String lastNameEnField, - @ParamMapper("typeOfEmploymentTable") String typeOfEmploymentTable, - @ParamMapper("parentField") String parentField, - @ParamMapper("typeOfEmploymentIdField") String typeOfEmploymentIdField); - - - /** - *

查询当前人员配置信息,是否全部展开,是否显示小红点点

- * 2022/12/5 11:51 - * ****************************************** - * - * @param userId 当前用户id - * @return ShowPointOrAll 展示与否的人员信息 - * @author youHong.ai ****************************************** - */ - @Select("select id,resources,show_all,show_type from uf_show_point_or_all " + - "where concat(',',resources,',') like concat('%,',#{userId},',%')") - ShowPointOrAll selectShowPointOrAll(@ParamMapper("userId") int userId); - + + + /** + *

查询所有的在职状态人员

+ * 2022/12/5 11:05 + * ****************************************** + * + * @param typeOfEmploymentField 人员自定义字段 + * @return List 返回的人员信息 + * @author youHong.ai ****************************************** + */ + @Select("select hrm.id, " + + " hrm.subcompanyid1 sub_company_id," + + " hrm.messagerurl avatar," + + " (case when cus.$t{lastNameEnField} is null then hrm.lastname " + + " else cus.$t{lastNameEnField} end) last_name, " + + " hrm.managerstr manager_str, " + + " hrm.jobtitle job_title_id, " + + " hrm.managerid manager_id, " + + " hrm.departmentid department_id, " + + " dept.DEPARTMENTNAME department_name, " + + " job.JOBTITLENAME job_title_name, " + + " uftb.$t{parentField} type_of_employment " + + "from hrmresource hrm " + + " left join hrmjobtitles job on hrm.JOBTITLE = job.id " + + " left join cus_fielddata cus on cus.ID = hrm.ID " + + " and cus.SCOPE = 'HrmCustomFieldByInfoType' " + + " and cus.SCOPEID = 1 " + + " left join cus_fielddata cus1 on cus1.id = hrm.id" + + " and cus1.scope = 'HrmCustomFieldByInfoType' " + + " and cus1.scopeid = -1" + + " left join hrmdepartment dept on dept.id = hrm.DEPARTMENTID " + + " left join $t{typeOfEmploymentTable} uftb on uftb.$t{typeOfEmploymentIdField} = cus1.$t{typeOfEmploymentFiled} " + + "where hrm.status in (0, 1)") + List selectAll(@ParamMapper("typeOfEmploymentFiled") String typeOfEmploymentField, + @ParamMapper("lastNameEnField") String lastNameEnField, + @ParamMapper("typeOfEmploymentTable") String typeOfEmploymentTable, + @ParamMapper("parentField") String parentField, + @ParamMapper("typeOfEmploymentIdField") String typeOfEmploymentIdField); + + + /** + *

查询当前人员配置信息,是否全部展开,是否显示小红点点

+ * 2022/12/5 11:51 + * ****************************************** + * + * @param userId 当前用户id + * @return ShowPointOrAll 展示与否的人员信息 + * @author youHong.ai ****************************************** + */ + @Select("select id,resources,show_all,show_type from uf_show_point_or_all " + + "where concat(',',resources,',') like concat('%,',#{userId},',%')") + ShowPointOrAll selectShowPointOrAll(@ParamMapper("userId") int userId); + } diff --git a/src/main/java/com/api/youhong/ai/pcn/organization/orgchart/service/OrgChartService.java b/src/main/java/com/api/youhong/ai/pcn/organization/orgchart/service/OrgChartService.java index 8fdbd6f..e4f79e7 100644 --- a/src/main/java/com/api/youhong/ai/pcn/organization/orgchart/service/OrgChartService.java +++ b/src/main/java/com/api/youhong/ai/pcn/organization/orgchart/service/OrgChartService.java @@ -27,258 +27,266 @@ import java.util.stream.Collectors; */ public class OrgChartService { - - private final OrgChartMapper mapper = Util.getMapper(OrgChartMapper.class); - - private final OrgChartMapStruct struct = OrgChartMapStruct.INSTANCE; - - /** - *

获取人员组织架构图数据

- * - * @param logInUser 当前登陆对象 - * @return 组织架构图数据 - * @author youHong.ai - */ - public List getOrgChartTree(User logInUser) { - int userId = logInUser.getUID(); - AtomicReference currentUser = new AtomicReference<>(); - List hrmResourceDtoList = getHrmResourceDtoList(userId, currentUser); - /* ******************* 系统管理员默认全部展开哦 ******************* */ - if (userId == 1) { - return systemAdminTree(hrmResourceDtoList); - } - filterCurrentSubCom(hrmResourceDtoList, currentUser, logInUser); - /* ******************* 查询当前用户的是否全部展示或显示小红点的配置信息 ******************* */ - ShowPointOrAll showPointOrAll = mapper.selectShowPointOrAll(userId); - List orgChartNodeVoList = null; - if (Objects.isNull(showPointOrAll)) { - /* ******************* 转换dto为Vo并且设置根节点标识 ******************* */ - orgChartNodeVoList = hrmResourceDtoList.stream() - .map(struct::hrmResourceDtoToVo) - .peek(item -> item.setType(-1)) - .collect(Collectors.toList()); - } else { - /* ******************* 转换dto为Vo并且设置根节点标识 ******************* */ - orgChartNodeVoList = hrmResourceDtoList.stream() - .map(struct::hrmResourceDtoToVo) - .peek(item -> { - if (showPointOrAll.isShowAll()) { - Builder.startSet(item) - .with(OrgChartNodeVo::setShow, 1) - .with(OrgChartNodeVo::setShowBrother, 1) - .with(OrgChartNodeVo::setShowChildren, 1) - .endSet(); - } - if (!showPointOrAll.isShowType()) { - item.setType(-1); - } - }).collect(Collectors.toList()); - - } - return Util.listToTree(orgChartNodeVoList, OrgChartNodeVo::getId, - OrgChartNodeVo::getManagerId, OrgChartNodeVo::getChildren, - OrgChartNodeVo::setChildren, - parentId -> parentId == null || parentId <= 0) - .stream() - .peek(item -> item.setIsRoot(true)) - .peek(item -> recursionChildrenNums(item, 0)) - .collect(Collectors.toList()); - } - - - /** - *

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

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

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

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

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

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

getHrmResourceDtoList 获取人力资源dto对象list

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

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

- * 2022/12/3 17:55 - * ****************************************** - * - * @param chartNodeVo 节点对象 - * @return Integer 对应节点的所有子节点的数量 - * @author youHong.ai ****************************************** - */ - private Integer recursionChildrenNums(OrgChartNodeVo chartNodeVo, int n) { - List children = chartNodeVo.getChildren(); - if (Objects.isNull(children) || children.size() == 0) { - chartNodeVo.setChildrenNum(0); - return 0; - } - n += children.size(); - for (OrgChartNodeVo child : children) { - child.setChildrenNum(recursionChildrenNums(child, 0)); - n += child.getChildrenNum(); - } - chartNodeVo.setChildrenNum(n); - return n; - } - + + private final OrgChartMapper mapper = Util.getMapper(OrgChartMapper.class); + + private final OrgChartMapStruct struct = OrgChartMapStruct.INSTANCE; + + /** + *

获取人员组织架构图数据

+ * + * @param logInUser 当前登陆对象 + * @return 组织架构图数据 + * @author youHong.ai + */ + public List getOrgChartTree(User logInUser) { + int userId = logInUser.getUID(); + AtomicReference currentUser = new AtomicReference<>(); + List hrmResourceDtoList = getHrmResourceDtoList(userId, currentUser); + /* ******************* 系统管理员默认全部展开哦 ******************* */ + if (userId == 1) { + return systemAdminTree(hrmResourceDtoList); + } + filterCurrentSubCom(hrmResourceDtoList, currentUser, logInUser); + /* ******************* 查询当前用户的是否全部展示或显示小红点的配置信息 ******************* */ + ShowPointOrAll showPointOrAll = mapper.selectShowPointOrAll(userId); + List orgChartNodeVoList = null; + if (Objects.isNull(showPointOrAll)) { + /* ******************* 转换dto为Vo并且设置根节点标识 ******************* */ + orgChartNodeVoList = hrmResourceDtoList.stream() + .map(struct::hrmResourceDtoToVo) + .peek(item -> item.setType(-1)) + .collect(Collectors.toList()); + } else { + /* ******************* 转换dto为Vo并且设置根节点标识 ******************* */ + orgChartNodeVoList = hrmResourceDtoList.stream() + .map(struct::hrmResourceDtoToVo) + .peek(item -> { + if (showPointOrAll.isShowAll()) { + Builder.startSet(item) + .with(OrgChartNodeVo::setShow, 1) + .with(OrgChartNodeVo::setShowBrother, 1) + .with(OrgChartNodeVo::setShowChildren, 1) + .endSet(); + } + if (!showPointOrAll.isShowType()) { + item.setType(-1); + } + }).collect(Collectors.toList()); + + } + sortByNameFirstLetter(orgChartNodeVoList); + return Util.listToTree(orgChartNodeVoList, OrgChartNodeVo::getId, + OrgChartNodeVo::getManagerId, OrgChartNodeVo::getChildren, + OrgChartNodeVo::setChildren, + parentId -> parentId == null || parentId <= 0) + .stream() + .peek(item -> item.setIsRoot(true)) + .peek(item -> recursionChildrenNums(item, 0)) + .collect(Collectors.toList()); + } + + public static void sortByNameFirstLetter(List nodeList) { + nodeList.sort((node1, node2) -> { + String name1 = node1.getName(); + String name2 = node2.getName(); + return name1.compareToIgnoreCase(name2); + }); + } + + /** + *

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

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

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

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

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

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

getHrmResourceDtoList 获取人力资源dto对象list

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

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

+ * 2022/12/3 17:55 + * ****************************************** + * + * @param chartNodeVo 节点对象 + * @return Integer 对应节点的所有子节点的数量 + * @author youHong.ai ****************************************** + */ + private Integer recursionChildrenNums(OrgChartNodeVo chartNodeVo, int n) { + List children = chartNodeVo.getChildren(); + if (Objects.isNull(children) || children.size() == 0) { + chartNodeVo.setChildrenNum(0); + return 0; + } + n += children.size(); + for (OrgChartNodeVo child : children) { + child.setChildrenNum(recursionChildrenNums(child, 0)); + n += child.getChildrenNum(); + } + chartNodeVo.setChildrenNum(n); + return n; + } + } diff --git a/src/main/java/com/api/youhong/ai/pcn/ssoyunzhao/service/SsoYunZhaoService.java b/src/main/java/com/api/youhong/ai/pcn/ssoyunzhao/service/SsoYunZhaoService.java index 1505673..06212b4 100644 --- a/src/main/java/com/api/youhong/ai/pcn/ssoyunzhao/service/SsoYunZhaoService.java +++ b/src/main/java/com/api/youhong/ai/pcn/ssoyunzhao/service/SsoYunZhaoService.java @@ -39,7 +39,8 @@ public class SsoYunZhaoService { Method method = User.class.getMethod(userCodeMethod); String value = Util.null2String(method.invoke(user)); long currentTime = System.currentTimeMillis(); - String token = this.rsaEncryptedUserInfo(value + "\"" + String.valueOf(currentTime).substring(0, 10)); + String str = value + "\"" + String.valueOf(currentTime).substring(0, 10); + String token = this.rsaEncryptedUserInfo(str); String yunZhaoSsoPathUrl = Util.getCusConfigValue("YunZhaoSSOPathURL"); Assert.notEmpty(yunZhaoSsoPathUrl, "can not find [YunZhaoSSOPathURL] from table [uf_cus_dev_config]"); return yunZhaoSsoPathUrl + URLEncoder.encode(token, "UTF-8"); diff --git a/src/main/java/com/api/youhong/ai/yashilandai/openbill/service/OpenTheBillService.java b/src/main/java/com/api/youhong/ai/yashilandai/openbill/service/OpenTheBillService.java index f4720c2..06a3dc8 100644 --- a/src/main/java/com/api/youhong/ai/yashilandai/openbill/service/OpenTheBillService.java +++ b/src/main/java/com/api/youhong/ai/yashilandai/openbill/service/OpenTheBillService.java @@ -21,6 +21,7 @@ import org.apache.poi.xssf.streaming.SXSSFCell; import org.apache.poi.xssf.streaming.SXSSFRow; import org.apache.poi.xssf.streaming.SXSSFSheet; import org.apache.poi.xssf.streaming.SXSSFWorkbook; +import weaver.conn.RecordSet; import java.io.OutputStream; import java.text.DateFormat; @@ -46,6 +47,8 @@ public class OpenTheBillService { private final Logger log = Util.getLogger(); + private final RecordSet res = new RecordSet(); + public Map getOpenBillListData(String startDate, String endDate, String orderNo) { return getData(startDate, endDate, orderNo); } @@ -150,6 +153,7 @@ public class OpenTheBillService { SXSSFCell cell, SXSSFSheet sheet, Map singularLine, Map evenNumberLine) { + int columnWidth = sheet.getColumnWidth(colIndex); String value = cell.getStringCellValue(); /** 计算字符串中中文字符的数量 */ @@ -160,27 +164,17 @@ public class OpenTheBillService { if (length >= columnWidth && length < 256 * 256) { sheet.setColumnWidth(colIndex, length); } - if (rowIndex % 2 == 1) { - if (singularLine.containsKey(colIndex)) { - return singularLine.get(colIndex); - } - CellStyle cellStyle = getCellStyle(workbook, rowIndex, colIndex, cell, sheet); - singularLine.put(colIndex, cellStyle); - return cellStyle; - } else { - if (evenNumberLine.containsKey(colIndex)) { - return evenNumberLine.get(colIndex); - } - CellStyle cellStyle = getCellStyle(workbook, rowIndex, colIndex, cell, sheet); - // 设置字体格式 - Font font = workbook.createFont(); - font.setFontName("微软雅黑"); - font.setFontHeightInPoints((short) 10); - - cellStyle.setFont(font); - evenNumberLine.put(colIndex, cellStyle); - return cellStyle; + if (singularLine.containsKey(-1)) { + return singularLine.get(-1); } + // 设置字体格式 + Font font = workbook.createFont(); + font.setFontName("微软雅黑"); + font.setFontHeightInPoints((short) 10); + CellStyle cellStyle = getCellStyle(workbook, rowIndex, colIndex, cell, sheet); + cellStyle.setFont(font); + singularLine.put(-1, cellStyle); + return cellStyle; } private CellStyle getCellStyle(SXSSFWorkbook workbook, Integer rowIndex, Integer colIndex, SXSSFCell cell, SXSSFSheet sheet) { @@ -232,6 +226,16 @@ public class OpenTheBillService { return count; } + public Map findMapByField(String filterString, List> list) { + for (Map map : list) { + if (map.containsKey("field") && map.get("field").equals(filterString)) { + return map; + } + } + // 如果找不到匹配的 Map,则返回 null + return null; + } + public Map getData(String startDate, String endDate, String orderNo) { Map config = Util.readProperties2Map("esteeLauderExcelExport", "export"); Assert.notEmpty(config, "esteeLauderExcelExport.properties文件读取配置为空,请检查配置信息"); @@ -246,7 +250,8 @@ public class OpenTheBillService { Util.null2String(config.get("createDate")), condition); } else { - dataList = mapper.selectList(Util.null2String(config.get("tableName"))); + // dataList = mapper.selectList(Util.null2String(config.get("tableName"))); + dataList = Collections.emptyList(); } Object head = config.get("head"); Map result = new HashMap<>(16); @@ -309,6 +314,7 @@ public class OpenTheBillService { if (finalBgm.equals("Y")) { // 都过了bgm for (Map item : list) { + item.put(Util.null2String(config.get("additional")), ""); item.put(Util.null2String(config.get("openBillKey")), ""); } } else { @@ -319,6 +325,7 @@ public class OpenTheBillService { // 不全部都是y或者n for (Map item : list) { item.put(Util.null2String(config.get("openBillKey")), "全部订单总金额达到GM审批标准,拆分后无法到达GM审批节点。"); + item.put(Util.null2String(config.get("additional")), "此单为系统判定疑似拆单"); } } @@ -400,10 +407,12 @@ public class OpenTheBillService { if (flag) { for (Map item : list) { item.put(Util.null2String(config.get("openBillKey")), "全部订单总金额达到GM审批标准,拆分后无法到达GM审批节点。"); + item.put(Util.null2String(config.get("additional")), "此单为系统判定疑似拆单"); } } else { for (Map item : list) { item.put(Util.null2String(config.get("openBillKey")), ""); + item.put(Util.null2String(config.get("additional")), ""); } } } @@ -468,6 +477,7 @@ public class OpenTheBillService { private void calculationCondition(List> dataList, Map config) { + Map convert = (Map) config.get("convert"); for (Map map : dataList) { // 订单分类 String orderType = Util.null2String(map.get(Util.null2String(config.get("orderType")))); @@ -485,7 +495,7 @@ public class OpenTheBillService { // 内部领用 // orderUse + " " + shipTo + " " + costCenter + " " + sku // condition = "订单用途:" + orderUse + " " + "ShipTo:" + shipTo + " CostCenter:" + costCenter + " sku:" + sku; - condition = orderUse + " :" + shipTo + ":" + costCenter + ":" + sku; + condition = "订单用途:" + orderUse + "、" + "shipTo:" + shipTo + "、" + "CostCenter:" + costCenter + "、" + "sku:" + sku; } break; case "1": @@ -494,13 +504,28 @@ public class OpenTheBillService { // 第三方 + 柜台订单 // orderUse + ":" + shipTo + ":" + sku // condition = "订单用途:" + orderUse + " " + "ShipTo:" + shipTo + " sku:" + sku + " 订单分类:" + orderType; - condition = orderUse + ":" + shipTo + ":" + sku + ":" + orderType; + condition = "订单用途:" + orderUse + "、" + "shipTo:" + shipTo + "、" + "sku:" + sku + "、" + "订单分类:" + orderType; } break; default: break; } + map.put(Util.null2String(config.get("additional")), ""); map.put(Util.null2String(config.get("conditionKey")), condition); + if (Objects.nonNull(convert)) { + for (Map.Entry entry : map.entrySet()) { + if (convert.containsKey(entry.getKey())) { + String sql = Util.null2String(convert.get(entry.getKey())); + if (StrUtil.isNotBlank(sql)) { + res.executeQuery(sql, entry.getValue()); + if (res.next()) { + entry.setValue(res.getInt(1)); + } else { + } + } + } + } + } } } diff --git a/src/main/java/com/api/youhong/ai/zhishichanquan/ssocaiwu/controller/SingleSignOnController.java b/src/main/java/com/api/youhong/ai/zhishichanquan/ssocaiwu/controller/SingleSignOnController.java index 02db8c1..480e5f3 100644 --- a/src/main/java/com/api/youhong/ai/zhishichanquan/ssocaiwu/controller/SingleSignOnController.java +++ b/src/main/java/com/api/youhong/ai/zhishichanquan/ssocaiwu/controller/SingleSignOnController.java @@ -15,6 +15,7 @@ import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.Context; import java.lang.reflect.Method; +import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; @@ -47,8 +48,10 @@ public class SingleSignOnController { Map param = new HashMap<>(8); param.put("user", value); param.put("ts", System.currentTimeMillis()); - String encrypt = AES.encrypt(key, initVector, JSON.toJSONString(param)); - response.sendRedirect(url + "?params=" + encrypt); + String json = JSON.toJSONString(param); + String encrypt = AES.encrypt(key, initVector, json); + Util.getLogger().info("加密内容: " + json + " 加密结果: " + encrypt); + response.sendRedirect(url + "?params=" + URLEncoder.encode(encrypt, "UTF-8")); } catch (Exception e) { log.error("单点登录路径处理失败!" + e.getMessage() + "\n" + Util.getErrString(e)); } diff --git a/src/main/java/com/customization/youhong/taibao/trisubreq/impl/TriSubRequestAfterInterceptImpl.java b/src/main/java/com/customization/youhong/taibao/trisubreq/impl/TriSubRequestAfterInterceptImpl.java new file mode 100644 index 0000000..fff594b --- /dev/null +++ b/src/main/java/com/customization/youhong/taibao/trisubreq/impl/TriSubRequestAfterInterceptImpl.java @@ -0,0 +1,86 @@ +package com.customization.youhong.taibao.trisubreq.impl; + +import aiyh.utils.Util; +import aiyh.utils.excention.CustomerException; +import aiyh.utils.tool.cn.hutool.core.collection.CollectionUtil; +import com.customization.youhong.taibao.trisubreq.impl.entity.SubRequestEntity; +import com.customization.youhong.taibao.trisubreq.impl.entity.SubRequestToDataConfig; +import com.engine.core.cfg.annotation.ServiceDynamicProxy; +import com.engine.core.impl.aop.AbstractServiceProxy; +import com.engine.workflow.service.SubRequestService; +import com.engine.workflow.service.impl.SubRequestServiceImpl; +import org.apache.log4j.Logger; +import weaver.workflow.request.DiffWfTriggerSetting; +import weaver.workflow.request.SameWfTriggerSetting; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + *

触发子流程

+ * + *

create: 2023/5/24 22:52

+ * + * @author youHong.ai + */ +@ServiceDynamicProxy(target = SubRequestServiceImpl.class, desc = "拦截签字意见信息,是否需要隐私控制") +public class TriSubRequestAfterInterceptImpl extends AbstractServiceProxy implements SubRequestService { + + private final TriSubRequestAfterMapper mapper = Util.getMapper(TriSubRequestAfterMapper.class); + + private final Logger log = Util.getLogger(); + + @Override + public void triSameSubRequestBefore(int i, List list) { + + } + + @Override + public void triDiffSubRequestBefore(int i, List list) { + + } + + @Override + public void triSubRequestAfter(int i) { + List subRequestEntities = mapper.selectSubRequestByMainRequest(i); + if (CollectionUtil.isEmpty(subRequestEntities)) { + return; + } + List subRequestToDataConfigs = mapper.selectConfig(); + if (CollectionUtil.isEmpty(subRequestToDataConfigs)) { + return; + } + Map collect = subRequestToDataConfigs + .stream() + .collect( + Collectors.toMap( + SubRequestToDataConfig::getWorkflowType, + value -> value + )); + + List> requestDataList = new ArrayList<>(); + for (SubRequestEntity subRequestEntity : subRequestEntities) { + // 查询流程对应的配置信息 + Map requestData = getRequestData(subRequestEntity); + requestDataList.add(requestData); + } + if (CollectionUtil.isEmpty(requestDataList)) { + return; + } + Map mainRequestData = mapper.selectRequestBase(Util.null2String(i)); + + } + + private Map getRequestData(SubRequestEntity subRequestEntity) { + String tableName = subRequestEntity.getWorkflowTable(); + Map requestData = mapper.selectWorkflowData(tableName, subRequestEntity.getRequestId()); + Map requestBaseData = mapper.selectRequestBase(subRequestEntity.getRequestId()); + if (CollectionUtil.isEmpty(requestBaseData)) { + throw new CustomerException("查询流程基本信息失败!"); + } + requestBaseData.putAll(requestData); + return requestBaseData; + } +} diff --git a/src/main/java/com/customization/youhong/taibao/trisubreq/impl/TriSubRequestAfterMapper.java b/src/main/java/com/customization/youhong/taibao/trisubreq/impl/TriSubRequestAfterMapper.java new file mode 100644 index 0000000..98580b6 --- /dev/null +++ b/src/main/java/com/customization/youhong/taibao/trisubreq/impl/TriSubRequestAfterMapper.java @@ -0,0 +1,116 @@ +package com.customization.youhong.taibao.trisubreq.impl; + +import aiyh.utils.annotation.recordset.*; +import com.customization.youhong.taibao.trisubreq.impl.entity.SubRequestEntity; +import com.customization.youhong.taibao.trisubreq.impl.entity.SubRequestToDataConfig; +import com.customization.youhong.taibao.trisubreq.impl.entity.SubRequestToDataMapping; + +import java.util.List; +import java.util.Map; + +/** + *

sql查询

+ * + *

create: 2023/5/24 23:09

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

查询子流程信息

+ * + * @param mainRequestId 主流程信息 + * @return 子流程信息 + */ + @Select("select requestid request_id,workflowid workflow_id from " + + "workflow_requestbase where mainrequestid = #{mainRequestId}") + @Associations({ + @Association( + property = "workflowTable", + column = "workflowid", + id = @Id(value = String.class, methodId = 2) + ) + }) + List selectSubRequestByMainRequest(@ParamMapper("mainRequestId") Integer mainRequestId); + + /** + *

查询流程表名

+ * + * @param billId 流程表id + * @return 流程表 + */ + @Select("select tablename workflow_table from workflow_base wb\n" + + "inner join workflow_table_view wv on wv.id = wb.id\n" + + "where wb.id = #{billId}") + @AssociationMethod(value = 2, desc = "查询流程对应的表表名") + String selectWorkflowTable(@ParamMapper("billId") String billId); + + /** + *

查询配置表信息

+ * + * @return 配置表信息 + */ + @Select("select * from uf_sub_wf_to_mode") + @Associations({ + @Association( + property = "modelTableName", + column = "model_table", + select = "aiyh.utils.mapper.UtilMapper.selectModelTableInfo", + id = @Id(value = Integer.class) + ) + }) + @CollectionMappings({ + @CollectionMapping( + property = "mappings", + column = "id", + id = @Id(value = String.class, methodId = 1) + ) + }) + List selectConfig(); + + + /** + *

查询配置表明细信息

+ * + * @param mainId 主表id + * @return 明细数据 + */ + @CollectionMethod(value = 1, desc = "查询配置表明细信息") + @Select("select * from uf_sub_wf_to_mode_dt1 where mainid = #{mainId}") + @Associations({ + @Association( + property = "modelField", + column = "model_field", + select = "aiyh.utils.mapper.UtilMapper.selectFieldInfo", + id = @Id(value = Integer.class) + ), + @Association( + property = "workflowField", + column = "workflow_field", + select = "aiyh.utils.mapper.UtilMapper.selectFieldInfo", + id = @Id(value = Integer.class) + ) + }) + List selectConfigDt(String mainId); + + /** + *

查询流程数据

+ * + * @param tableName 表名称 + * @param requestId 请求id + * @return 流程数据 + */ + @Select("select $t{tableName} where requestid = #{requestId}") + Map selectWorkflowData(@ParamMapper("tableName") String tableName, @ParamMapper("requestId") String requestId); + + /** + *

查询流程信息

+ * + * @param requestId 流程id + * @return 流程信息 + */ + @Select("select * from workflow_requestbase where requestid = #{requestId}") + Map selectRequestBase(@ParamMapper("requestId") String requestId); +} diff --git a/src/main/java/com/customization/youhong/taibao/trisubreq/impl/entity/SubRequestEntity.java b/src/main/java/com/customization/youhong/taibao/trisubreq/impl/entity/SubRequestEntity.java new file mode 100644 index 0000000..bbd8bad --- /dev/null +++ b/src/main/java/com/customization/youhong/taibao/trisubreq/impl/entity/SubRequestEntity.java @@ -0,0 +1,26 @@ +package com.customization.youhong.taibao.trisubreq.impl.entity; + +import aiyh.utils.annotation.recordset.SqlOracleDbFieldAnn; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** + *

子流程实体类

+ * + *

create: 2023/5/24 23:13

+ * + * @author youHong.ai + */ +@Getter +@Setter +@ToString +public class SubRequestEntity { + @SqlOracleDbFieldAnn("REQUEST_ID") + private String requestId; + @SqlOracleDbFieldAnn("WORKFLOW_ID") + private String workflowId; + + @SqlOracleDbFieldAnn("WORKFLOW_TABLE") + private String workflowTable; +} diff --git a/src/main/java/com/customization/youhong/taibao/trisubreq/impl/entity/SubRequestToDataConfig.java b/src/main/java/com/customization/youhong/taibao/trisubreq/impl/entity/SubRequestToDataConfig.java new file mode 100644 index 0000000..50be919 --- /dev/null +++ b/src/main/java/com/customization/youhong/taibao/trisubreq/impl/entity/SubRequestToDataConfig.java @@ -0,0 +1,36 @@ +package com.customization.youhong.taibao.trisubreq.impl.entity; + +import aiyh.utils.entity.ModelTableInfo; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +import java.util.List; + +/** + *

配置表实体类

+ * + *

create: 2023/5/29 10:31

+ * + * @author youHong.ai + */ +@Getter +@Setter +@ToString +public class SubRequestToDataConfig { + + private Integer id; + + /** 流程 */ + private String workflowType; + /** 建模 */ + private String modelTable; + /** 更新条件 */ + private String conditionUpdate; + + /** 建模表 */ + private ModelTableInfo modelTableName; + + private List mappings; + +} diff --git a/src/main/java/com/customization/youhong/taibao/trisubreq/impl/entity/SubRequestToDataMapping.java b/src/main/java/com/customization/youhong/taibao/trisubreq/impl/entity/SubRequestToDataMapping.java new file mode 100644 index 0000000..03260f4 --- /dev/null +++ b/src/main/java/com/customization/youhong/taibao/trisubreq/impl/entity/SubRequestToDataMapping.java @@ -0,0 +1,29 @@ +package com.customization.youhong.taibao.trisubreq.impl.entity; + +import aiyh.utils.annotation.recordset.SqlDbFieldAnn; +import aiyh.utils.entity.FieldViewInfo; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** + *

字段映射

+ * + *

create: 2023/5/29 10:37

+ * + * @author youHong.ai + */ +@Getter +@Setter +@ToString +public class SubRequestToDataMapping { + private Integer id; + + @SqlDbFieldAnn("mainid") + private Integer mainId; + + /** 建模字段 */ + private FieldViewInfo modelField; + /** 流程字段 */ + private FieldViewInfo workflowField; +} diff --git a/src/main/java/com/engine/yunjinshan/modeDelete/service/impl/DeleteModeDataServiceImp.java b/src/main/java/com/engine/yunjinshan/modeDelete/service/impl/DeleteModeDataServiceImp.java new file mode 100644 index 0000000..a72934f --- /dev/null +++ b/src/main/java/com/engine/yunjinshan/modeDelete/service/impl/DeleteModeDataServiceImp.java @@ -0,0 +1,156 @@ +package com.engine.yunjinshan.modeDelete.service.impl; + +import com.alibaba.fastjson.JSON; +import com.weaverboot.frame.ioc.anno.classAnno.WeaIocReplaceComponent; +import com.weaverboot.frame.ioc.anno.methodAnno.WeaReplaceAfter; +import com.weaverboot.frame.ioc.anno.methodAnno.WeaReplaceBefore; +import com.weaverboot.frame.ioc.handler.replace.weaReplaceParam.impl.WeaAfterReplaceParam; +import com.weaverboot.frame.ioc.handler.replace.weaReplaceParam.impl.WeaBeforeReplaceParam; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.BaseBean; +import weaver.general.Util; +import weaver.yunjinshan.formmode.action.CostIncomeUpdate; + +import java.util.*; + +/** + * 云锦山 + * 建模记录删除方法拦截方法 + */ +@WeaIocReplaceComponent("CubeExpandService") +public class DeleteModeDataServiceImp { + + /** + * 定义一个当前线程 + */ + private static final ThreadLocal>> threadLocal = new ThreadLocal<>(); + + private final static BaseBean bean = new BaseBean(); + + + /** + * 调用删除前 进行方法拦截 + * 人员成本管理、合同管理建模进行处理 + * + * @param weaBeforeReplaceParam 拦截参数 + */ + @WeaReplaceBefore(value = "/api/cube/expand/deleteData", order = 1, description = "删除建模数据,在数据删除前进行拦截") + public void before(WeaBeforeReplaceParam weaBeforeReplaceParam) { + // 获取请求参数 + Map param = weaBeforeReplaceParam.getParamMap(); + + bean.writeLog("进入删除拦截:" + JSON.toJSONString(param)); + // 模块ID + String modeId = Util.null2String(param.get("modeId")); + // 具体的数据ID + String billids = Util.null2String(param.get("billids")); + + // 人力成本管理模块ID + String humanCostModeId = Util.null2String(Prop.getPropValue("DeleteModeData", "HumanCostModeId"), "4"); + // 合同管理模块ID + String contractManagementModeId = Util.null2String(Prop.getPropValue("DeleteModeData", "ContractManagementModeId"), "3"); + + if ("".equals(humanCostModeId)) { + humanCostModeId = "4"; + } + + if ("".equals(contractManagementModeId)) { + contractManagementModeId = "3"; + } + // 人员成本管理、合同管理 建模模块 + if (contractManagementModeId.equals(modeId) || humanCostModeId.equals(modeId)) { + // 将待删除的记录写入临时表 + String selectData = ""; + + bean.writeLog("删除建模数据!模块id: " + modeId); + bean.writeLog("删除的数据id: " + billids); + + if (contractManagementModeId.equals(modeId)) { + selectData = "select qdny,yjbm,khmc from uf_hetongguanli where id in (" + billids + ")"; + } + + if (humanCostModeId.equals(modeId)) { + selectData = "select ny,yjbm,kh from uf_renlichengben where id in (" + billids + ")"; + } + + RecordSet rs = new RecordSet(); + + // 从当前线程中获取已删除的记录 + List> dataList = new ArrayList<>(); + + if (rs.executeQuery(selectData)) { + while (rs.next()) { + // 年月 + String yearMonth = Util.null2String(rs.getString(1)); + // 一级部门 + String superiorDepartment = Util.null2String(rs.getString(2)); + // 客户 + String customer = Util.null2String(rs.getString(3)); + + Map detailMap = new HashMap<>(8); + detailMap.put("yearMonth", yearMonth); + detailMap.put("superiorDepartment", superiorDepartment); + detailMap.put("customer", customer); + detailMap.put("modeId", modeId); + dataList.add(detailMap); + } + } + + threadLocal.set(dataList); + } + } + + /** + * 调用删除后 进行方法拦截 + * 人员成本管理、合同管理建模进行处理 + * + * @param weaAfterReplaceParam 拦截参数 + */ + @WeaReplaceAfter(value = "/api/cube/expand/deleteData", order = 1, description = "删除建模数据,在数据删除后进行拦截,处理特殊业务") + public void after(WeaAfterReplaceParam weaAfterReplaceParam) { + + bean.writeLog("----------------删除拦截后!"); + try { + // 从当前线程中获取已删除的记录 + List> dataList = threadLocal.get(); + + if (Objects.nonNull(dataList) && dataList.size() > 0) { + bean.writeLog("删除的数据信息: " + JSON.toJSONString(dataList)); + // 人力成本管理模块ID + String humanCostModeId = Util.null2String(Prop.getPropValue("DeleteModeData", "HumanCostModeId"), "4"); + // 合同管理模块ID + String contractManagementModeId = Util.null2String(Prop.getPropValue("DeleteModeData", "ContractManagementModeId"), "3"); + if ("".equals(humanCostModeId)) { + humanCostModeId = "4"; + } + if ("".equals(contractManagementModeId)) { + contractManagementModeId = "3"; + } + CostIncomeUpdate incomeUpdate = new CostIncomeUpdate(); + for (Map detailMap : dataList) { + // 年月 + String yearMonth = Util.null2String(detailMap.get("yearMonth")); + // 一级部门 + String superiorDepartment = Util.null2String(detailMap.get("superiorDepartment")); + // 客户 + String customer = Util.null2String(detailMap.get("customer")); + + String modeId = Util.null2String(detailMap.get("modeId")); + + if (humanCostModeId.equals(modeId)) { + incomeUpdate.updateByHumanCost(yearMonth, superiorDepartment, customer); + } + if (contractManagementModeId.equals(modeId)) { + incomeUpdate.updateByContract(yearMonth, superiorDepartment, customer); + } + } + } + + } catch (Exception e) { + bean.writeLog("处理删除数据信息异常!异常信息:" + e.getMessage()); + } finally { + threadLocal.remove(); + } + } +} diff --git a/src/main/java/weaver/chaoyang/he/hcy_hangtiankeji/gmgetdatafromlowgroup/controller/GMGatherOtherSystemInfoController.java b/src/main/java/weaver/chaoyang/he/hcy_hangtiankeji/gmgetdatafromlowgroup/controller/GMGatherOtherSystemInfoController.java new file mode 100644 index 0000000..9915190 --- /dev/null +++ b/src/main/java/weaver/chaoyang/he/hcy_hangtiankeji/gmgetdatafromlowgroup/controller/GMGatherOtherSystemInfoController.java @@ -0,0 +1,43 @@ +package weaver.chaoyang.he.hcy_hangtiankeji.gmgetdatafromlowgroup.controller; + + +import aiyh.utils.Util; +import org.apache.log4j.Logger; +import weaver.chaoyang.he.hcy_hangtiankeji.gmgetdatafromlowgroup.service.GMGatherOtherSystemInfoService; +import weaver.chaoyang.he.hcy_hangtiankeji.gmgetdatafromlowgroup.service.impl.GMGatherOtherSystemInfoServiceImpl; +import weaver.interfaces.schedule.BaseCronJob; + +/** + *

GM集团获取GM集团下级单位合同台账信息

+ * @author hcy + * @date 2023/5/9 13:56 + */ +public class GMGatherOtherSystemInfoController extends BaseCronJob { + + //日志处理 + private final Logger logger = Util.getLogger(); + + private final GMGatherOtherSystemInfoService gmgatherOtherSystemInfoService = new GMGatherOtherSystemInfoServiceImpl(); + + //同步标准:0 同步全量数据 1 同步前一天的数据 + public String syncStandard; + + //GM集团获取GM集团下级单位的url + public String URL; + + //GM集团数据库表名 + public String formTableNameGM; + + public void execute() { + try { + boolean insertDataBool = gmgatherOtherSystemInfoService.insertDataIntoGM(syncStandard,URL,formTableNameGM); + if (insertDataBool){ + logger.info("GM集团获取GM集团下级单位合同台账信息执行成功!"); + }else { + logger.error("GM集团获取GM集团下级单位合同台账信息执行失败!"); + } + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/src/main/java/weaver/chaoyang/he/hcy_hangtiankeji/gmgetdatafromlowgroup/controller/GMGatherSMInfoController.java b/src/main/java/weaver/chaoyang/he/hcy_hangtiankeji/gmgetdatafromlowgroup/controller/GMGatherSMInfoController.java new file mode 100644 index 0000000..5660339 --- /dev/null +++ b/src/main/java/weaver/chaoyang/he/hcy_hangtiankeji/gmgetdatafromlowgroup/controller/GMGatherSMInfoController.java @@ -0,0 +1,15 @@ +package weaver.chaoyang.he.hcy_hangtiankeji.gmgetdatafromlowgroup.controller; + +import weaver.interfaces.schedule.BaseCronJob; + +/** + *

GM集团获取商密集团合同台账信息

+ * @author hcy + * @date 2023/5/9 18:20 + */ +public class GMGatherSMInfoController extends BaseCronJob { + + public void execute() { + + } +} diff --git a/src/main/java/weaver/chaoyang/he/hcy_hangtiankeji/gmgetdatafromlowgroup/controller/GMGatherSameSystemInfoController.java b/src/main/java/weaver/chaoyang/he/hcy_hangtiankeji/gmgetdatafromlowgroup/controller/GMGatherSameSystemInfoController.java new file mode 100644 index 0000000..14a4ada --- /dev/null +++ b/src/main/java/weaver/chaoyang/he/hcy_hangtiankeji/gmgetdatafromlowgroup/controller/GMGatherSameSystemInfoController.java @@ -0,0 +1,39 @@ +package weaver.chaoyang.he.hcy_hangtiankeji.gmgetdatafromlowgroup.controller; + +import aiyh.utils.Util; +import org.apache.log4j.Logger; +import weaver.chaoyang.he.hcy_hangtiankeji.gmgetdatafromlowgroup.service.GMGatherSameSystemInfoService; +import weaver.chaoyang.he.hcy_hangtiankeji.gmgetdatafromlowgroup.service.impl.GMGatherSameSystemInfoServiceImpl; +import weaver.interfaces.schedule.BaseCronJob; + + +/** + *

前提条件:GM集团与GM下级单位使用同一套系统,由GM集团每日执行定时任务,将对应的下级单位台账信息进行数据同步

+ * @author hcy + * @date 2023/5/9 17:16 + */ +public class GMGatherSameSystemInfoController extends BaseCronJob { + + + //业务主要逻辑 + private final GMGatherSameSystemInfoService gmgatherSameSystemInfoService = new GMGatherSameSystemInfoServiceImpl(); + + //日志处理 + private final Logger logger = Util.getLogger(); + + //配置表主表名称 + public String configurationMainTableName; + + //配置表明细表1名称 + public String configurationDetailTableName1; + + //配置表明细表2名称 + public String configurationDetailTableName2; + + //唯一标识 + public String uniqueIdentification; + + public void execute() { + gmgatherSameSystemInfoService.dealMainLogic(configurationMainTableName,configurationDetailTableName1,configurationDetailTableName2,uniqueIdentification); + } +} diff --git a/src/main/java/weaver/chaoyang/he/hcy_hangtiankeji/gmgetdatafromlowgroup/mapper/GMGatherOtherSystemInfoMapper.java b/src/main/java/weaver/chaoyang/he/hcy_hangtiankeji/gmgetdatafromlowgroup/mapper/GMGatherOtherSystemInfoMapper.java new file mode 100644 index 0000000..77d48c2 --- /dev/null +++ b/src/main/java/weaver/chaoyang/he/hcy_hangtiankeji/gmgetdatafromlowgroup/mapper/GMGatherOtherSystemInfoMapper.java @@ -0,0 +1,30 @@ +package weaver.chaoyang.he.hcy_hangtiankeji.gmgetdatafromlowgroup.mapper; + +import aiyh.utils.annotation.recordset.Delete; +import aiyh.utils.annotation.recordset.ParamMapper; +import aiyh.utils.annotation.recordset.Select; +import aiyh.utils.annotation.recordset.SqlMapper; + +@SqlMapper +public interface GMGatherOtherSystemInfoMapper { + + @Select("insert into $t{formTableNameGM} $t{keys} value $t{values}") + boolean insertData(@ParamMapper("formTableNameGM") String formTableNameGM, + @ParamMapper("keys") String keys, + @ParamMapper("values") String values); + + + @Select("select count(*) from $t{formTableNameGM} where htbm = #{htbm}") + int selectCountHtbm(@ParamMapper("formTableNameGM")String formTableNameGM, + @ParamMapper("htbm")String htbm); + + + + @Select("select id from $t{formTableNameGM} where htbm = #{htbm}") + String selectId(@ParamMapper("formTableNameGM") String formTableNameGM, + @ParamMapper("htbm")String htbm); + + @Delete("delete from $t{s} where mainid = #{mainid}") + boolean deleteByMainId(@ParamMapper("s")String s, @ParamMapper("mainid")String mainid); + +} diff --git a/src/main/java/weaver/chaoyang/he/hcy_hangtiankeji/gmgetdatafromlowgroup/mapper/GMGatherSMInfoMapper.java b/src/main/java/weaver/chaoyang/he/hcy_hangtiankeji/gmgetdatafromlowgroup/mapper/GMGatherSMInfoMapper.java new file mode 100644 index 0000000..97ace43 --- /dev/null +++ b/src/main/java/weaver/chaoyang/he/hcy_hangtiankeji/gmgetdatafromlowgroup/mapper/GMGatherSMInfoMapper.java @@ -0,0 +1,7 @@ +package weaver.chaoyang.he.hcy_hangtiankeji.gmgetdatafromlowgroup.mapper; + +import aiyh.utils.annotation.recordset.SqlMapper; + +@SqlMapper +public class GMGatherSMInfoMapper { +} diff --git a/src/main/java/weaver/chaoyang/he/hcy_hangtiankeji/gmgetdatafromlowgroup/mapper/GMGatherSameSystemInfoMapper.java b/src/main/java/weaver/chaoyang/he/hcy_hangtiankeji/gmgetdatafromlowgroup/mapper/GMGatherSameSystemInfoMapper.java new file mode 100644 index 0000000..6655d4a --- /dev/null +++ b/src/main/java/weaver/chaoyang/he/hcy_hangtiankeji/gmgetdatafromlowgroup/mapper/GMGatherSameSystemInfoMapper.java @@ -0,0 +1,37 @@ +package weaver.chaoyang.he.hcy_hangtiankeji.gmgetdatafromlowgroup.mapper; + +import aiyh.utils.annotation.recordset.ParamMapper; +import aiyh.utils.annotation.recordset.Select; +import aiyh.utils.annotation.recordset.SqlMapper; + +import java.util.List; +import java.util.Map; + +@SqlMapper +public interface GMGatherSameSystemInfoMapper { + + + @Select("select * from #{configurationMainTableName} where wybs = #{uniqueIdentification}") + List> getConfigInformation(@ParamMapper("configurationMainTableName") String configurationMainTableName, + @ParamMapper("uniqueIdentification") String uniqueIdentification); + + @Select("select * from #{configurationDetailTableName1} where mainid = #{mainid}") + List> getConfigDetal1Information(@ParamMapper("configurationDetailTableName1")String configurationDetailTableName1, + @ParamMapper("mainid")String mainid); + + @Select("select * from #{configurationDetailTableName2} where mainid = #{mainid}") + List> getConfigDetal2Information(@ParamMapper("configurationDetailTableName2")String configurationDetailTableName2, + @ParamMapper("mainid")String mainid); + + @Select("select * from #{ejdwtzb_name} where LEFT(modedatacreatedate,7) = LEFT(#{yesterday},7)") + List> getSMCountLowGroupdata(@ParamMapper("ejdwtzb_name")String ejdwtzb_name, + @ParamMapper("yesterday")String yesterday); + + @Select("select * from #{ejdwtzb_name} where LEFT(modedatacreatedate,7) = LEFT(#{yesterday},7)") + List> getSMCountLowGroupDataUpdate(@ParamMapper("ejdwtzb_name")String ejdwtzb_name, + @ParamMapper("yesterday")String yesterday); + + @Select("select * from #{jttzbd} where htbm = #{htbm}") + List> selectHtbmData(@ParamMapper("jttzbd")String jttzbd, + @ParamMapper("htbm")String htbm); +} diff --git a/src/main/java/weaver/chaoyang/he/hcy_hangtiankeji/gmgetdatafromlowgroup/service/GMGatherOtherSystemInfoService.java b/src/main/java/weaver/chaoyang/he/hcy_hangtiankeji/gmgetdatafromlowgroup/service/GMGatherOtherSystemInfoService.java new file mode 100644 index 0000000..0791018 --- /dev/null +++ b/src/main/java/weaver/chaoyang/he/hcy_hangtiankeji/gmgetdatafromlowgroup/service/GMGatherOtherSystemInfoService.java @@ -0,0 +1,6 @@ +package weaver.chaoyang.he.hcy_hangtiankeji.gmgetdatafromlowgroup.service; + +public interface GMGatherOtherSystemInfoService { + + boolean insertDataIntoGM(String syncStandard, String url,String formTableNameGM); +} diff --git a/src/main/java/weaver/chaoyang/he/hcy_hangtiankeji/gmgetdatafromlowgroup/service/GMGatherSMInfoService.java b/src/main/java/weaver/chaoyang/he/hcy_hangtiankeji/gmgetdatafromlowgroup/service/GMGatherSMInfoService.java new file mode 100644 index 0000000..e985245 --- /dev/null +++ b/src/main/java/weaver/chaoyang/he/hcy_hangtiankeji/gmgetdatafromlowgroup/service/GMGatherSMInfoService.java @@ -0,0 +1,4 @@ +package weaver.chaoyang.he.hcy_hangtiankeji.gmgetdatafromlowgroup.service; + +public interface GMGatherSMInfoService { +} diff --git a/src/main/java/weaver/chaoyang/he/hcy_hangtiankeji/gmgetdatafromlowgroup/service/GMGatherSameSystemInfoService.java b/src/main/java/weaver/chaoyang/he/hcy_hangtiankeji/gmgetdatafromlowgroup/service/GMGatherSameSystemInfoService.java new file mode 100644 index 0000000..a08081e --- /dev/null +++ b/src/main/java/weaver/chaoyang/he/hcy_hangtiankeji/gmgetdatafromlowgroup/service/GMGatherSameSystemInfoService.java @@ -0,0 +1,5 @@ +package weaver.chaoyang.he.hcy_hangtiankeji.gmgetdatafromlowgroup.service; + +public interface GMGatherSameSystemInfoService { + void dealMainLogic(String configurationMainTableName, String configurationDetailTableName1, String configurationDetailTableName2, String uniqueIdentification); +} diff --git a/src/main/java/weaver/chaoyang/he/hcy_hangtiankeji/gmgetdatafromlowgroup/service/impl/GMGatherOtherSystemInfoServiceImpl.java b/src/main/java/weaver/chaoyang/he/hcy_hangtiankeji/gmgetdatafromlowgroup/service/impl/GMGatherOtherSystemInfoServiceImpl.java new file mode 100644 index 0000000..09c2301 --- /dev/null +++ b/src/main/java/weaver/chaoyang/he/hcy_hangtiankeji/gmgetdatafromlowgroup/service/impl/GMGatherOtherSystemInfoServiceImpl.java @@ -0,0 +1,232 @@ +package weaver.chaoyang.he.hcy_hangtiankeji.gmgetdatafromlowgroup.service.impl; + +import aiyh.utils.Util; +import aiyh.utils.httpUtil.ResponeVo; +import aiyh.utils.httpUtil.util.HttpUtils; +import aiyh.utils.sqlUtil.builderSql.impl.BuilderSqlImpl; +import aiyh.utils.sqlUtil.sqlResult.impl.PrepSqlResultImpl; +import aiyh.utils.sqlUtil.whereUtil.impl.PrepWhereImpl; +import org.apache.log4j.Logger; +import weaver.chaoyang.he.hcy_hangtiankeji.gmgetdatafromlowgroup.mapper.GMGatherOtherSystemInfoMapper; +import weaver.chaoyang.he.hcy_hangtiankeji.gmgetdatafromlowgroup.service.GMGatherOtherSystemInfoService; +import weaver.conn.RecordSet; +import weaver.formmode.setup.ModeRightInfo; +import weaver.general.TimeUtil; + +import java.io.IOException; +import java.util.*; +import java.util.stream.Collectors; + +public class GMGatherOtherSystemInfoServiceImpl implements GMGatherOtherSystemInfoService { + + + //日志处理 + private final Logger logger = Util.getLogger(); + //sql + private final GMGatherOtherSystemInfoMapper gmGatherOtherSystemInfoMapper = Util.getMapper(GMGatherOtherSystemInfoMapper.class); + + /** + * 执行数据插入逻辑 + * @param syncStandard 同步标准:0 同步全量数据 1 同步前一天的数据 + * @param URL 访问url + * @param formTableNameGM 需要插入的表名 + * @return 是否插入成功 + */ + public boolean insertDataIntoGM(String syncStandard, String URL,String formTableNameGM) { + try { + //连接GM下级单位暴露的接口获取台账所有的数据 + this.getEntityInsertDB(syncStandard,URL,formTableNameGM); + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + /** + * 向台账中同步数据 + * @param syncStandard 同步标准:0 同步全量数据 1 同步前一天的数据 + * @param URL 访问url + * @param formTableNameGM 需要插入的表名 + * @return 是否插入成功 + */ + public boolean getEntityInsertDB(String syncStandard, String URL,String formTableNameGM) { + try { + ResponeVo responeVo = getEntityMap(syncStandard, URL); + int code = responeVo.getCode(); + if (code != 200) { + logger.info("对方接口状态码为:" + code + " 程序执行错误"); + return false; + } + Map entityMap = responeVo.getResponseMap(); + List> datas = (List>) entityMap.get("data"); + if (datas.isEmpty()) return false;//数据为空返回:数据为空 + if ("1".equals(syncStandard)) { + int failNum = 0;//失败的次数 + for (Map totalDataMap : datas) { + //用于存放全部主表数据,排除所有明细表数据 + Map newDataMap = new HashMap<>(totalDataMap.entrySet().stream() + .filter(entry -> !("detailData".equals(entry.getKey()) || "id".equals(entry.getKey()))) + .collect(Collectors.toMap( + Map.Entry::getKey, + Map.Entry::getValue))); + String htbm = Util.null2String(totalDataMap.get("htbm")); + int countHtbm = gmGatherOtherSystemInfoMapper.selectCountHtbm(formTableNameGM,htbm); + RecordSet recordSet = new RecordSet(); + if (countHtbm == 0){ + int mainid = this.createmodedata(formTableNameGM, 1, newDataMap);//先插入数据id,在根据数据id,插入所有明细数据 + if (mainid>0){ + //开始插入明细表 + List> detailData = (List>) totalDataMap.get("detailData"); + for (Map detailDatum : detailData) { + detailDatum.put("mainid",mainid); + insertSql(formTableNameGM,detailDatum);//插入明细表 + } + } + }else if (countHtbm > 0 ){ + BuilderSqlImpl builderSql = new BuilderSqlImpl(); + PrepWhereImpl prepWhere = new PrepWhereImpl(); + prepWhere.whereAnd("htbm = ?"); + prepWhere.addArgs(htbm); + PrepSqlResultImpl prepSqlResult = builderSql.updateSql(formTableNameGM, newDataMap, prepWhere); + boolean updateBool = recordSet.executeUpdate(prepSqlResult.getSqlStr(), prepSqlResult.getArgs()); + if (!updateBool){ + logger.error("数据更新失败,SQL:["+prepSqlResult+"]"); + failNum++; + }else { + //先删明细数据 + String mainid = gmGatherOtherSystemInfoMapper.selectId(formTableNameGM,htbm); + //开始插入明细表 + List> detailData = (List>) totalDataMap.get("detailData"); + for (Map detailDatum : detailData) { + //先删明细数据 + boolean deleteBool = gmGatherOtherSystemInfoMapper.deleteByMainId(formTableNameGM+"_dt1",Util.null2String(mainid)); + if (deleteBool){ + detailDatum.put("mainid",mainid); + insertSql(formTableNameGM,detailDatum);//插入明细表 + } + } + } + + } + } + logger.info("数据更新失败"+failNum+"次"); + } else if ("0".equals(syncStandard)){ + for (Map totalDataMap : datas) { + //用于存放全部主表数据,排除所有明细表数据 + Map newDataMap = new HashMap<>(totalDataMap.entrySet().stream() + .filter(entry -> !("detailData".equals(entry.getKey()) || "id".equals(entry.getKey()))) + .collect(Collectors.toMap( + Map.Entry::getKey, + Map.Entry::getValue))); + int createmodedata = createmodedata(formTableNameGM, 1, newDataMap); + if (createmodedata>0){ + List> detailData = (List>) totalDataMap.get("detailData"); + if (detailData.isEmpty()) continue; + for (Map detailDatum : detailData) { + detailDatum.put("mainid",createmodedata); + insertSql(formTableNameGM,detailDatum); + } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + /** + * 访问国密下级单位暴露的接口,获取ResponeVo + * @param syncStandard 同步标准:0 同步全量数据 1 同步前一天的数据 + * @param URL 接口访问路径 + * @return ResponeVo + */ + public ResponeVo getEntityMap(String syncStandard, String URL){ + try { + HttpUtils httpUtils = new HttpUtils(); + Map paramsMap = new HashMap<>(); + paramsMap.put("syncStandard", syncStandard); + return httpUtils.apiPost(URL, paramsMap); + } catch (IOException e) { + e.printStackTrace(); + } + return null; + } + + /** + * 将数据插入表单建模 + * @param tablename 建模表名 + * @param userid 创建人id + * @param map 数据map + * @return int 返回数据id + */ + public int createmodedata(String tablename, int userid, Map map) { + Integer modeid = getModeidByTableName(tablename); + int dataid = 0; + RecordSet rs = new RecordSet(); + + String uuid = map.containsKey("modeuuid") ? map.get("modeuuid").toString() : UUID.randomUUID().toString(); + boolean flag = rs.execute("insert into " + tablename + + "(modeuuid,modedatacreater,modedatacreatedate,modedatacreatetime,formmodeid) values('" + uuid + "'," + + userid + ",'" + TimeUtil.getCurrentDateString() + "','" + TimeUtil.getOnlyCurrentTimeString() + "'," + + modeid + ")"); + if (flag) { + rs.execute("select id from " + tablename + " where modeuuid='" + uuid + "'"); + rs.next(); + dataid = weaver.general.Util.getIntValue(rs.getString("id")); + + if (dataid > 0) { + // 遍历数据 进行update + StringBuilder updatesql = new StringBuilder("update " + tablename + " set "); + Set keySet = map.keySet(); + for (String key : keySet) { + updatesql.append(key).append("='").append(map.get(key).toString()).append("',"); + } + if (updatesql.toString().endsWith(",")) { + updatesql = new StringBuilder(updatesql.substring(0, updatesql.length() - 1)); + + updatesql.append(" where id=").append(dataid); + boolean execute = rs.execute(updatesql.toString()); + if(!execute){ + logger.info("出错的sql==="+updatesql); + } + } + /* + * 进行权限重构 + */ + ModeRightInfo moderight = new ModeRightInfo(); + moderight.editModeDataShare(userid, modeid, dataid); + } + } + return dataid; + } + + /** + * 获取没一张表的modeid + * @param tablename 表名称 + * @return + */ + public Integer getModeidByTableName(String tablename) { + RecordSet rs = new RecordSet(); + String sql = "select b.TABLENAME,a.FORMID,a.id modeid from modeinfo a left join workflow_bill b on a.FORMID=b.id where b.TABLENAME= '" + + tablename + "'"; + rs.execute(sql); + rs.next(); + return Math.abs(rs.getInt("modeid")); + } + + /** + * 执行数据插入操作 + * @param tableName 表名 + * @param datas 数据集合 + */ + public void insertSql(String tableName,Map datas){ + BuilderSqlImpl builderSql = new BuilderSqlImpl(); + PrepSqlResultImpl prepSqlResult = builderSql.insertSql(tableName + "_dt1", datas); + RecordSet recordSet1 = new RecordSet(); + boolean insertBool = recordSet1.executeUpdate(prepSqlResult.getSqlStr(), prepSqlResult.getArgs()); + if (!insertBool){ + logger.error("数据插入失败,失败SQL:["+prepSqlResult+"]"); + } + } +} diff --git a/src/main/java/weaver/chaoyang/he/hcy_hangtiankeji/gmgetdatafromlowgroup/service/impl/GMGatherSMInfoServiceImpl.java b/src/main/java/weaver/chaoyang/he/hcy_hangtiankeji/gmgetdatafromlowgroup/service/impl/GMGatherSMInfoServiceImpl.java new file mode 100644 index 0000000..5c6c05f --- /dev/null +++ b/src/main/java/weaver/chaoyang/he/hcy_hangtiankeji/gmgetdatafromlowgroup/service/impl/GMGatherSMInfoServiceImpl.java @@ -0,0 +1,7 @@ +package weaver.chaoyang.he.hcy_hangtiankeji.gmgetdatafromlowgroup.service.impl; + + +import weaver.chaoyang.he.hcy_hangtiankeji.gmgetdatafromlowgroup.service.GMGatherSMInfoService; + +public class GMGatherSMInfoServiceImpl implements GMGatherSMInfoService { +} diff --git a/src/main/java/weaver/chaoyang/he/hcy_hangtiankeji/gmgetdatafromlowgroup/service/impl/GMGatherSameSystemInfoServiceImpl.java b/src/main/java/weaver/chaoyang/he/hcy_hangtiankeji/gmgetdatafromlowgroup/service/impl/GMGatherSameSystemInfoServiceImpl.java new file mode 100644 index 0000000..8511d29 --- /dev/null +++ b/src/main/java/weaver/chaoyang/he/hcy_hangtiankeji/gmgetdatafromlowgroup/service/impl/GMGatherSameSystemInfoServiceImpl.java @@ -0,0 +1,162 @@ +package weaver.chaoyang.he.hcy_hangtiankeji.gmgetdatafromlowgroup.service.impl; + +import aiyh.utils.Util; +import com.google.common.base.Joiner; +import com.weaver.formmodel.util.DateHelper; +import org.apache.log4j.Logger; +import weaver.chaoyang.he.hcy_hangtiankeji.gmgetdatafromlowgroup.mapper.GMGatherSameSystemInfoMapper; +import weaver.chaoyang.he.hcy_hangtiankeji.gmgetdatafromlowgroup.service.GMGatherSameSystemInfoService; +import weaver.conn.RecordSet; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +public class GMGatherSameSystemInfoServiceImpl implements GMGatherSameSystemInfoService { + /** + * 日志 + */ + private final Logger logger = Util.getLogger(); + + //sql + private final GMGatherSameSystemInfoMapper gmGatherSameSystemInfoMapper = Util.getMapper(GMGatherSameSystemInfoMapper.class); + + /** + * 处理从国密集团下级单位台账数据库查询数据向国密集团总台账数据库中插入或者更新数据 + * @param configurationMainTableName 配置表主表名称 + * @param configurationDetailTableName1 配置表明细表1名称 + * @param configurationDetailTableName2 配置表明细表2名称 + * @param uniqueIdentification 唯一标识 + */ + public void dealMainLogic(String configurationMainTableName, String configurationDetailTableName1, String configurationDetailTableName2, String uniqueIdentification) { + //第一步获取配置表中数据 + if (configurationMainTableName.equals("") && configurationDetailTableName1.equals("") && uniqueIdentification.equals("")) return; + //主表数据 + List> configMainTableData = gmGatherSameSystemInfoMapper.getConfigInformation(configurationMainTableName,uniqueIdentification); + logger.info("配置表主表数据---configMainTableData---"+configMainTableData); + if (configMainTableData.isEmpty()) return; + + String jttzbd = Util.null2String(configMainTableData.get(0).get("jttzbd"));//集团台账表单 + String mainid = Util.null2String(configMainTableData.get(0).get("mainid")); + logger.info("配置表主表数据---mainid---"+mainid); + if (mainid.equals("")) return; + + //配置表明细表1数据:用来统计商密下级单位台账名称 + List> configDetal1TableData = gmGatherSameSystemInfoMapper.getConfigDetal1Information(configurationDetailTableName1,mainid); + logger.info("配置表明细表数据---configDetal1TableData---"+configDetal1TableData); + //明细表2数据 + List> configDetal2TableData = gmGatherSameSystemInfoMapper.getConfigDetal2Information(configurationDetailTableName2,mainid); + logger.info("配置表明细表数据---configDetal2TableData---"+configDetal2TableData); + List keys = new ArrayList<>();//用于insert和update的key + for (Map configdetal2 : configDetal2TableData) { + keys.add(Util.null2String(configdetal2.get("tbzd"))); + } + + +//第二步:其次我们需要根据数据创建时间,和数据修改时间来判断二级单位中的这条数据是第一次进来的,还是二次进来修改的,如果只有创建时间没有修改时间那么就对这条数据进行增加,如果既有创建时间又有修改时间,那么就需要将这条数据进行修改 + if (configDetal1TableData.isEmpty()) return; + for (Map config1 : configDetal1TableData) { + String ejdwtzb_name = Util.null2String(config1.get("ejdwtzb")); //二级单位台账表数据库名称 + String bz = Util.null2String(config1.get("bz")); //备注 + logger.info("二级单位台账表数据库名称===="+ejdwtzb_name+" 二级单位台账表数名称==="+bz); + //获取当天日期的前一天,如果和创建时间吻合,并且满足修改时间为空那么,这条数据就是纯插入的数据 + List> smCountLowGroupDataInsert = gmGatherSameSystemInfoMapper.getSMCountLowGroupdata(ejdwtzb_name, DateHelper.getYesterday()); + logger.info("smCountLowGroupDataInsert===="+smCountLowGroupDataInsert); + + //获取当天日期的前一天,如果和修改时间吻合,那么这条数据就是更新操作的数据 + List> smCountLowGroupDataupdate = gmGatherSameSystemInfoMapper.getSMCountLowGroupDataUpdate(ejdwtzb_name,DateHelper.getYesterday()); + logger.info("smCountLowGroupDataupdate===="+smCountLowGroupDataupdate); + + //数据插入商密集团总台账 + if (smCountLowGroupDataInsert.size()>0){ + this.insertData(smCountLowGroupDataInsert,jttzbd,keys); + } + //数据更新商密集团总台账 + if (smCountLowGroupDataupdate.size()>0){ + this.updateData(smCountLowGroupDataupdate,jttzbd,keys); + } + } + } + + + /** + *

插入数据

+ * @param smCountLowGroupDataInsert 插入数据集合 + * @param jttzbd 集团台账数据库名 + * @param keys 需要insert的字段key + * @author hcy + * 2023/5/6 17:41 + */ + private void insertData(List> smCountLowGroupDataInsert, String jttzbd,List keys) { + + RecordSet recordSet = new RecordSet(); + for (Map insertDatas : smCountLowGroupDataInsert) { + String htbm = Util.null2String(insertDatas.get("htbm")); + List> selectHtbmData = gmGatherSameSystemInfoMapper.selectHtbmData(jttzbd,htbm); + if (selectHtbmData.size()==0){ + + String insertKey = Joiner.on(",").join((Iterable) keys);//key + ArrayList valueList = new ArrayList<>(); + for (String key : keys) { + String v = Util.null2String(insertDatas.get(key)); + valueList.add(v); + } + + String insertValue = Joiner.on(",").join((Iterable) valueList);//value + + String insertSql = "insert into "+jttzbd + "(" +insertKey + ")"+ "value " +"("+insertValue+")";//拼接插入的sql语句 + boolean insertBool = recordSet.executeQuery(insertSql); + if (insertBool){ + logger.info("数据插入成功"); + }else{ + logger.info("数据插入失败"); + } + } + } + } + + /** + *

更新数据

+ * @param smCountLowGroupDataupdate 更新语句集合 + * @param jttzbd 集团台账数据库名 + * @param keys 数据更新的key组成的集合 + * @author hcy + * 2023/5/6 17:40 + */ + + private void updateData(List> smCountLowGroupDataupdate, String jttzbd, List keys) { + try { + + RecordSet recordSet = new RecordSet(); + for (Map updateDates : smCountLowGroupDataupdate) { + String htbm = Util.null2String(updateDates.get("htbm")); + List> updateDatas = gmGatherSameSystemInfoMapper.selectHtbmData(jttzbd, htbm); + if (updateDatas.size()>0){ + //拼接sql + List updateValueList = new ArrayList<>(); + for (String key : keys) { + String value = Util.null2String(updateDates.get(key)); + updateValueList.add(value); + } + StringBuilder builder = new StringBuilder(); + + Joiner.on(", ").appendTo(builder, keys); + builder.append(" = "); + Joiner.on(", ").appendTo(builder, updateValueList); + + + String updateSql = "update "+jttzbd + "set " + builder + " where htbm = ?"; + boolean updateBool = recordSet.executeQuery(updateSql, htbm); + if (updateBool){ + logger.info("======数据更新成功======"); + }else { + logger.info("======数据更新失败======"); + } + } + } + } catch (Exception e) { + e.printStackTrace(); + logger.info("----GMGatherSameSystemInfoServiceImpl----smCountLowGroupDataupdate----异常如下===="+e); + } + } +} diff --git a/src/main/java/weaver/chaoyang/he/hcy_hangtiankeji/smcountlowgruop/controller/SMCountLowGroupDataController.java b/src/main/java/weaver/chaoyang/he/hcy_hangtiankeji/smcountlowgruop/controller/SMCountLowGroupDataController.java new file mode 100644 index 0000000..3910438 --- /dev/null +++ b/src/main/java/weaver/chaoyang/he/hcy_hangtiankeji/smcountlowgruop/controller/SMCountLowGroupDataController.java @@ -0,0 +1,73 @@ +package weaver.chaoyang.he.hcy_hangtiankeji.smcountlowgruop.controller; + +import aiyh.utils.Util; +import lombok.SneakyThrows; +import org.apache.log4j.Logger; +import weaver.chaoyang.he.hcy_hangtiankeji.smcountlowgruop.service.SMCountLowGroupDataService; +import weaver.chaoyang.he.hcy_hangtiankeji.smcountlowgruop.service.impl.SMCountLowGroupDataServiceImpl; +import weaver.interfaces.schedule.BaseCronJob; + +/** + *

由于商密集团与商密下级单位使用同一套环境,所以可以使用定时任务的方式,商密集团每日执行定时任务,将下级单位的台账信息同步到商密集团的台账中

+ * @Author hcy + * @Date 2023/4/26 18:14 + */ +public class SMCountLowGroupDataController extends BaseCronJob { + + //业务主要逻辑 + private final SMCountLowGroupDataService smCountLowGroupData = new SMCountLowGroupDataServiceImpl(); + + //日志处理 + private final Logger logger = Util.getLogger(); + + //配置表主表名称 + public String configurationMainTableName; + + //配置表明细表1名称 + public String configurationDetailTableName1; + + //配置表明细表2名称 + public String configurationDetailTableName2; + + //唯一标识 + public String uniqueIdentification; + + @SneakyThrows + public void execute() { + smCountLowGroupData.dealMainLogic(configurationMainTableName,configurationDetailTableName1,configurationDetailTableName2,uniqueIdentification);//处理业务主要逻辑 + } + + public String getConfigurationDetailTableName1() { + return configurationDetailTableName1; + } + + public void setConfigurationDetailTableName1(String configurationDetailTableName1) { + this.configurationDetailTableName1 = configurationDetailTableName1; + } + + public String getConfigurationDetailTableName2() { + return configurationDetailTableName2; + } + + public void setConfigurationDetailTableName2(String configurationDetailTableName2) { + this.configurationDetailTableName2 = configurationDetailTableName2; + } + + + + public String getConfigurationMainTableName() { + return configurationMainTableName; + } + + public void setConfigurationMainTableName(String configurationMainTableName) { + this.configurationMainTableName = configurationMainTableName; + } + + public String getUniqueIdentification() { + return uniqueIdentification; + } + + public void setUniqueIdentification(String uniqueIdentification) { + this.uniqueIdentification = uniqueIdentification; + } +} diff --git a/src/main/java/weaver/chaoyang/he/hcy_hangtiankeji/smcountlowgruop/mapper/SMCountLowGroupDataMapper.java b/src/main/java/weaver/chaoyang/he/hcy_hangtiankeji/smcountlowgruop/mapper/SMCountLowGroupDataMapper.java new file mode 100644 index 0000000..25b67ea --- /dev/null +++ b/src/main/java/weaver/chaoyang/he/hcy_hangtiankeji/smcountlowgruop/mapper/SMCountLowGroupDataMapper.java @@ -0,0 +1,60 @@ +package weaver.chaoyang.he.hcy_hangtiankeji.smcountlowgruop.mapper; + +import aiyh.utils.annotation.recordset.Delete; +import aiyh.utils.annotation.recordset.ParamMapper; +import aiyh.utils.annotation.recordset.Select; +import aiyh.utils.annotation.recordset.SqlMapper; + +import java.util.List; +import java.util.Map; + +@SqlMapper +public interface SMCountLowGroupDataMapper { + + @Select("select * from $t{configurationMainTableName} where wybs = #{uniqueIdentification}") + List> getConfigInformation(@ParamMapper("configurationMainTableName") String configurationMainTableName, + @ParamMapper("uniqueIdentification") String uniqueIdentification); + + @Select("select * from $t{configurationDetailTableName1} where mainid = #{mainid}") + List> getConfigDetal1Information(@ParamMapper("configurationDetailTableName1")String configurationDetailTableName1, + @ParamMapper("mainid")String mainid); + + @Select("select * from $t{configurationDetailTableName2} where mainid = #{mainid}") + List> getConfigDetal2Information(@ParamMapper("configurationDetailTableName2")String configurationDetailTableName2, + @ParamMapper("mainid")String mainid); + + @Select("select * from $t{ejdwtzb_name} where LEFT(modedatacreatedate,7) = LEFT(#{yesterday},7) ") + List> getSMCountLowGroupdata(@ParamMapper("ejdwtzb_name")String ejdwtzb_name, + @ParamMapper("yesterday")String yesterday); + + @Select("select * from $t{ejdwtzb_name} where LEFT(modedatamodifydatetime,7) = LEFT(#{yesterday},7)") + List> getSMCountLowGroupDataUpdate(@ParamMapper("ejdwtzb_name")String ejdwtzb_name, + @ParamMapper("yesterday")String yesterday); + + @Select("select * from $t{jttzbd} where htbm = #{htbm}") + List> selectHtbmData(@ParamMapper("jttzbd")String jttzbd, + @ParamMapper("htbm")String htbm); + + @Select("select * from $t{ejdwtzb_name}") + List> getSMCountLowGroupTotalData(@ParamMapper("ejdwtzb_name") String ejdwtzb_name); + + @Select("select id from $t{jttzbd} where htbm = #{htbm}") + String selectIdByHtbm(@ParamMapper("jttzbd")String jttzbd, + @ParamMapper("htbm")String htbm); + + + @Delete("delete from $t{s} where mainid = #{id}") + boolean deleteDetalDataByMainId(@ParamMapper("s")String s, + @ParamMapper("id")String id); + + + @Select("select id from $t{ejdwtzb_name} where htbm = #{htbm1}") + String selectDetailTableSouceId(@ParamMapper("ejdwtzb_name")String ejdwtzb_name, + @ParamMapper("htbm1")String htbm1); + + + @Select("select * from $t{s} where mainid = #{ejdw_id}") + List> selectDetailTableSouceData(@ParamMapper("s")String s, + @ParamMapper("ejdw_id")String ejdw_id); + +} diff --git a/src/main/java/weaver/chaoyang/he/hcy_hangtiankeji/smcountlowgruop/service/SMCountLowGroupDataService.java b/src/main/java/weaver/chaoyang/he/hcy_hangtiankeji/smcountlowgruop/service/SMCountLowGroupDataService.java new file mode 100644 index 0000000..2592148 --- /dev/null +++ b/src/main/java/weaver/chaoyang/he/hcy_hangtiankeji/smcountlowgruop/service/SMCountLowGroupDataService.java @@ -0,0 +1,9 @@ +package weaver.chaoyang.he.hcy_hangtiankeji.smcountlowgruop.service; + +import java.io.IOException; + +public interface SMCountLowGroupDataService { + + + void dealMainLogic(String configurationMainTableName, String configurationDetailTableName1, String configurationDetailTableName2, String uniqueIdentification) throws IOException; +} diff --git a/src/main/java/weaver/chaoyang/he/hcy_hangtiankeji/smcountlowgruop/service/impl/SMCountLowGroupDataServiceImpl.java b/src/main/java/weaver/chaoyang/he/hcy_hangtiankeji/smcountlowgruop/service/impl/SMCountLowGroupDataServiceImpl.java new file mode 100644 index 0000000..728f3d0 --- /dev/null +++ b/src/main/java/weaver/chaoyang/he/hcy_hangtiankeji/smcountlowgruop/service/impl/SMCountLowGroupDataServiceImpl.java @@ -0,0 +1,329 @@ +package weaver.chaoyang.he.hcy_hangtiankeji.smcountlowgruop.service.impl; + +import aiyh.utils.Util; +import aiyh.utils.sqlUtil.builderSql.impl.BuilderSqlImpl; +import aiyh.utils.sqlUtil.sqlResult.impl.PrepSqlResultImpl; +import aiyh.utils.sqlUtil.whereUtil.impl.PrepWhereImpl; +import com.weaver.formmodel.util.DateHelper; +import org.apache.log4j.Logger; +import weaver.chaoyang.he.hcy_hangtiankeji.smcountlowgruop.mapper.SMCountLowGroupDataMapper; +import weaver.chaoyang.he.hcy_hangtiankeji.smcountlowgruop.service.SMCountLowGroupDataService; +import weaver.conn.RecordSet; +import weaver.formmode.setup.ModeRightInfo; +import weaver.general.TimeUtil; + +import java.io.IOException; +import java.util.*; + +// 3、开发补充详细开发方案 +// (1)我们现在要做的事情就是要将商密下级单位台账表中的数据同步到商密集团台账表uf_hthpjtz中 +// (2)首先我们需要根据合同台账同步表uf_httztb来获取数据库二级单位表名称和想要同步不来的字段名称,这里要求做成配置的是因为后续便于字段增删 +// (3)其次我们需要根据数据创建时间,和数据修改时间来判断二级单位中的这条数据是第一次进来的,还是二次进来修改的,如果只有创建时间没有修改时间那么就对这条数据进行增加,如果既有创建时间又有修改时间,那么就需要将这条数据进行修改 +// (4)在向商密集团总台账插入数据的时候,同时为了保证数据的准确性,我们首先需要根据合同编码来查询合同总台账中查询本条数据是否已经存在,如果存在执行更新操作,如果不存在执行插入操作。 +public class SMCountLowGroupDataServiceImpl implements SMCountLowGroupDataService { + + //处理sql + private final SMCountLowGroupDataMapper smCountLowGroupDataMapper = Util.getMapper(SMCountLowGroupDataMapper.class); + + //构建inser、update 的sql语句 + private final BuilderSqlImpl builderSqlImpl = new BuilderSqlImpl(); + + //日志 + private final Logger logger = Util.getLogger(); + + /** + *

处理从商密二级单位台账数据库查询数据向商密集团总台账数据库中插入或者更新数据

+ * @author hcy 2023/5/6 14:59 + */ + public void dealMainLogic(String configurationMainTableName, String configurationDetailTableName1, String configurationDetailTableName2, String uniqueIdentification) throws IOException { + //第一步获取配置表中数据 + if (configurationMainTableName.equals("") && configurationDetailTableName1.equals("") && uniqueIdentification.equals("")) return; + //主表数据 + List> configMainTableData = smCountLowGroupDataMapper.getConfigInformation(configurationMainTableName,uniqueIdentification); + logger.info("配置表主表数据---configMainTableData---"+configMainTableData); + if (configMainTableData.isEmpty()) return; + + String jttzbd = Util.null2String(configMainTableData.get(0).get("jttzbd"));//集团台账表单 + String mainid = Util.null2String(configMainTableData.get(0).get("id")); + logger.info("配置表主表数据---mainid---"+mainid); + if (mainid.equals("") && "".equals(jttzbd)) return; + + //配置表明细表1数据:用来统计商密下级单位台账名称 + List> configDetal1TableData = smCountLowGroupDataMapper.getConfigDetal1Information(configurationDetailTableName1,mainid); + logger.info("配置表明细表数据---configDetal1TableData---"+configDetal1TableData); + //明细表2数据 + List> configDetal2TableData = smCountLowGroupDataMapper.getConfigDetal2Information(configurationDetailTableName2,mainid); + logger.info("配置表明细表数据---configDetal2TableData---"+configDetal2TableData); + List mainTablekeys = new ArrayList<>();//用于存放主表中insert和update的key + List detalTablekeys = new ArrayList<>();//用于存放主表中insert和update的key + for (Map configdetal2 : configDetal2TableData) { + String sfzb = Util.null2String(configdetal2.get("sfzb")); + if ("0".equals(sfzb)){ + mainTablekeys.add(Util.null2String(configdetal2.get("tbzd"))); + }else if ("1".equals(sfzb)){ + detalTablekeys.add(Util.null2String(configdetal2.get("tbzd"))); + } + } + + +//第二步:其次我们需要根据数据创建时间,和数据修改时间来判断二级单位中的这条数据是第一次进来的,还是二次进来修改的,如果只有创建时间没有修改时间那么就对这条数据进行增加,如果既有创建时间又有修改时间,那么就需要将这条数据进行修改 + if (configDetal1TableData.isEmpty()) return; + for (Map config1 : configDetal1TableData) { + String ejdwtzb_name = Util.null2String(config1.get("ejdwtzb")); //二级单位台账表数据库名称 + String bz = Util.null2String(config1.get("bz")); //备注 + String tbzt = Util.null2String(config1.get("tbzt")); + logger.info("二级单位台账表数据库名称===="+ejdwtzb_name+" 二级单位台账表数名称==="+bz+" 同步状态==="+tbzt); + + if ("0".equals(tbzt)){ + //查询全量数据 + List> smCountLowGroupTotalData = smCountLowGroupDataMapper.getSMCountLowGroupTotalData(ejdwtzb_name);//第一次同步数据 + if (smCountLowGroupTotalData.size()>0){ + this.insertData(smCountLowGroupTotalData,jttzbd,ejdwtzb_name,mainTablekeys,detalTablekeys,tbzt);//全增量主表数据执行插入 并且包含明细表的删除,和再次添加 + } + }else if ("1".equals(tbzt)){ //非第一次同步数据 + //获取当天日期的前一天,如果和创建时间吻合,并且满足修改时间为空那么,这条数据就是纯插入的数据 + List> smCountLowGroupDataInsert = smCountLowGroupDataMapper.getSMCountLowGroupdata(ejdwtzb_name,DateHelper.getYesterday()); + logger.info("smCountLowGroupDataInsert===="+smCountLowGroupDataInsert); + + //获取当天日期的前一天,如果和修改时间吻合,那么这条数据就是更新操作的数据 + List> smCountLowGroupDataupdate = smCountLowGroupDataMapper.getSMCountLowGroupDataUpdate(ejdwtzb_name,DateHelper.getYesterday()); + logger.info("smCountLowGroupDataupdate===="+smCountLowGroupDataupdate); + + //数据插入商密集团总台账 + if (smCountLowGroupDataInsert.size()>0){ + this.insertData(smCountLowGroupDataInsert,jttzbd,ejdwtzb_name,mainTablekeys,detalTablekeys, tbzt); + } + //数据更新商密集团总台账 + if (smCountLowGroupDataupdate.size()>0){ + this.updateData(smCountLowGroupDataupdate,jttzbd,ejdwtzb_name,mainTablekeys,detalTablekeys); + } + } + + } + } + + + /** + *

插入数据

+ * @param smCountLowGroupDataInsert 插入数据集合 + * @param jttzbd 集团台账数据库名 + * @param ejdwtzb_name 二级单位数据库名 + * @param keys 需要insert的字段key + * @param detalTablekeys 需要插入的明细表字段数据库名组成的list + * @param tbzt 同步状态用来判断是第一次同步还是非首次同步 + * @author hcy + * 2023/5/6 17:41 + */ + private void insertData(List> smCountLowGroupDataInsert, String jttzbd, String ejdwtzb_name, List keys, List detalTablekeys, String tbzt) { + + RecordSet recordSet = new RecordSet(); + int successNum = 0; + int failNum = 0; + for (Map insertDatas : smCountLowGroupDataInsert) { + String htbm = Util.null2String(insertDatas.get("htbm")); + List> selectHtbmData = smCountLowGroupDataMapper.selectHtbmData(jttzbd,htbm); + if (selectHtbmData.size()==0){ +// String insertKey = Joiner.on(",").join((Iterable) keys);//key + Map keyValueMap = new HashMap<>(); + for (String key : keys) { +// if("htzje".equals(key) || "htjrrmb".equals(key)){ +// String o = Util.null2String(insertDatas.get(key)); +// if ("".equals(o)){ +// keyValueMap.put(key, null); +// }else { +// keyValueMap.put(key, o); +// } +// }else { +// Object o = insertDatas.get(key); +// keyValueMap.put(key, o); +// } + Object o = insertDatas.get(key); + keyValueMap.put(key, o); + } +// PrepSqlResultImpl prepSqlResult = builderSqlImpl.insertSql(jttzbd, keyValueMap); +// boolean insertBool = recordSet.executeUpdate(prepSqlResult.getSqlStr(), prepSqlResult.getArgs()); + + int createmodedata = createmodedata(jttzbd, 1, keyValueMap); + if (createmodedata>0){ + String htbm1 = Util.null2String(keyValueMap.get("htbm")); + deleteAndInsertDetailTable(htbm1,jttzbd,ejdwtzb_name,detalTablekeys); + } +// if(insertBool){ +// successNum++; +// String htbm1 = Util.null2String(keyValueMap.get("htbm")); +// //执行明细表的数据删除和数据插入 +// deleteAndInsertDetailTable(htbm1,jttzbd,ejdwtzb_name,detalTablekeys); +// }else{ +// failNum++; +// logger.error("台账数据插入失败,失败SQL:["+ prepSqlResult +"----失败次数:"+failNum+"]"); +// } + logger.info("台账数据插入成功 "+successNum+"次"); + + } + } + } + + /** + *

更新数据

+ * @param smCountLowGroupDataupdate 更新语句集合 + * @param jttzbd 集团台账数据库名 + * @param ejdwtzb_name 二级单位数据库名 + * @param keys 数据更新的key组成的集合 + * @param detalTablekeys 需要插入的明细表字段数据库名组成的list + * @author hcy + * 2023/5/6 17:40 + */ + + private void updateData(List> smCountLowGroupDataupdate, String jttzbd, String ejdwtzb_name, List keys, List detalTablekeys) { + RecordSet recordSet = new RecordSet(); + int failNum = 0; + int successNum = 0; + for (Map updateDates : smCountLowGroupDataupdate) { + String htbm = Util.null2String(updateDates.get("htbm")); + List> selecthtbmData = smCountLowGroupDataMapper.selectHtbmData(jttzbd, htbm); + if (selecthtbmData.size()>0){ + Map keyValueMap = getKeyValueMap(updateDates, keys); + PrepWhereImpl prepWhere = new PrepWhereImpl(); + prepWhere.whereAnd("htbm = ?"); + prepWhere.addArgs(htbm); + PrepSqlResultImpl prepSqlResult = builderSqlImpl.updateSql(jttzbd, keyValueMap, prepWhere); + boolean insertBool = recordSet.executeUpdate(prepSqlResult.getSqlStr(), prepSqlResult.getArgs()); + if (insertBool){ + String htbm1 = Util.null2String(keyValueMap.get("htbm")); + //执行明细表的数据删除和数据插入 + deleteAndInsertDetailTable(htbm1,jttzbd,ejdwtzb_name,detalTablekeys); + successNum++; + }else { + failNum++; + logger.error("台账数据更新失败,SQL:["+ prepSqlResult +"------失败次数:"+failNum+"]"); + } + logger.info("台账数据更新成功 "+successNum + "次"); + } + } + } + + /** + * 用于封装insert或者update的key,value的map集合 + * @param datas 数据源 + * @param keys 需要更新或者插入的keys + * @return 预期的key,value对应的map集合 + */ + public Map getKeyValueMap(Map datas ,List keys){ + Map keyValueMap = new HashMap<>(); + for (String key : keys) { + String v = Util.null2String(datas.get(key)); + keyValueMap.put(key, v); + } + return keyValueMap; + } + + /** + * 删除并插入明细表中的数据 + * @param htbm1 合同编号用来作为唯一标识 + * @param jttzbd 商密集团台账数据库名称 + * @param ejdwtzb_name 二级单位名称 + * @param detalTablekeys 需要插入的明细表字段数据库名组成的list + */ + public void deleteAndInsertDetailTable(String htbm1,String jttzbd,String ejdwtzb_name,List detalTablekeys){ + + try { + RecordSet insertDatailRS = new RecordSet(); + //执行明细表的插入语句 + String id = smCountLowGroupDataMapper.selectIdByHtbm(jttzbd,htbm1); + int successNum = 0; + int failNum = 0; + if (!"".equals(id)){ + boolean deleteBool = smCountLowGroupDataMapper.deleteDetalDataByMainId(jttzbd+"_dt1",id);//明细表插入数据之前,先执行删除语句 + if (deleteBool){ + //执行明细表插入逻辑 + String ejdw_id = smCountLowGroupDataMapper.selectDetailTableSouceId(ejdwtzb_name,htbm1); + List> souceDetailDatas = smCountLowGroupDataMapper.selectDetailTableSouceData(ejdwtzb_name+"_dt1",ejdw_id); + if (souceDetailDatas.size()==0) return; + for (Map souceDetailData : souceDetailDatas) { + Map dealwithData = new HashMap<>();//根据配置表处理完需要字段后的数据Map + for (String key : detalTablekeys) { + dealwithData.put(key,souceDetailData.get(key)); + } + //将mainid拼进去 + dealwithData.put("mainid",id); + //开始插入明细表数据 + PrepSqlResultImpl prepSqlResult = builderSqlImpl.insertSql(jttzbd+"_dt1", dealwithData); + boolean detailInsertBool = insertDatailRS.executeUpdate(prepSqlResult.getSqlStr(), prepSqlResult.getArgs()); + if (detailInsertBool){ + successNum++; + }else { + failNum++; + logger.error("明细表数据插入失败,SQL:["+prepSqlResult+"------失败次数:"+failNum+"]"); + } + logger.info("明细表数据插入成功数量:"+successNum); + } + + } + } + } catch (Exception e) { + e.printStackTrace(); + logger.error("报错=="+e); + } + } + + /** + * 方法描述 : 将数据插入表单建模 + * @param tablename 建模表明 + * @param userid 创建人id + * @param map 数据map + * @return int 返回数据id + */ + public int createmodedata(String tablename, int userid, Map map) { + Integer modeid = getModeidByTableName(tablename); + int dataid = 0; + RecordSet rs = new RecordSet(); + + String uuid = map.containsKey("modeuuid") ? map.get("modeuuid").toString() : UUID.randomUUID().toString(); + boolean flag = rs.execute("insert into " + tablename + + "(modeuuid,modedatacreater,modedatacreatedate,modedatacreatetime,formmodeid) values('" + uuid + "'," + + userid + ",'" + TimeUtil.getCurrentDateString() + "','" + TimeUtil.getOnlyCurrentTimeString() + "'," + + modeid + ")"); + if (flag) { + rs.execute("select id from " + tablename + " where modeuuid='" + uuid + "'"); + rs.next(); + dataid = weaver.general.Util.getIntValue(rs.getString("id")); + + if (dataid > 0) { + // 遍历数据 进行update + String updatesql = "update " + tablename + " set "; + Set keySet = map.keySet(); + for (String key : keySet) { + updatesql += key + "='" + map.get(key).toString() + "',"; + } + if (updatesql.endsWith(",")) { + updatesql = updatesql.substring(0, updatesql.length() - 1); + + updatesql += " where id=" + dataid; + boolean execute = rs.execute(updatesql); + if(!execute){ + logger.info("出错的sql==="+updatesql); + } + } + /* + * 进行权限重构 + */ + ModeRightInfo moderight = new ModeRightInfo(); + moderight.editModeDataShare(userid, modeid, dataid); + } + } + + return dataid; + } + + + public static Integer getModeidByTableName(String tablename) { + RecordSet rs = new RecordSet(); + String sql = "select b.TABLENAME,a.FORMID,a.id modeid from modeinfo a left join workflow_bill b on a.FORMID=b.id where b.TABLENAME= '" + + tablename + "'"; + rs.execute(sql); + rs.next(); + return Math.abs(rs.getInt("modeid")); + } + + +} diff --git a/src/main/java/weaver/xiao/commons/config/service/DealWithMapping.java b/src/main/java/weaver/xiao/commons/config/service/DealWithMapping.java index e9b168e..94b1c6a 100644 --- a/src/main/java/weaver/xiao/commons/config/service/DealWithMapping.java +++ b/src/main/java/weaver/xiao/commons/config/service/DealWithMapping.java @@ -5,7 +5,6 @@ import com.google.common.base.Strings; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; -import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; import weaver.conn.RecordSet; @@ -61,7 +60,7 @@ public class DealWithMapping extends ToolUtil { private RecordSet tempRs; private DealWithMapper mapper = null; - + private final Logger logger = aiyh.utils.Util.getLogger("json-util"); { @@ -115,19 +114,23 @@ public class DealWithMapping extends ToolUtil { || "NUMBER".equalsIgnoreCase(type) || "INTEGER".equalsIgnoreCase(type) || "TINYINT".equalsIgnoreCase(type) || "SMALLINT".equalsIgnoreCase(type)) { map.put(key, rs.getInt(i) == -1 ? rs.getString(i) : rs.getInt(i)); + map.put(key.toLowerCase(), rs.getInt(i) == -1 ? rs.getString(i) : rs.getInt(i)); continue; } if ("FLOAT".equalsIgnoreCase(type)) { map.put(key, rs.getFloat(i)); + map.put(key.toLowerCase(), rs.getFloat(i)); continue; } if ("DATE".equalsIgnoreCase(type) || "TIMESTAMP".equalsIgnoreCase(type) || "DATETIME".equalsIgnoreCase(type)) { map.put(key, rs.getString(i)); + map.put(key.toLowerCase(), rs.getString(i)); continue; } if ("DOUBLE".equalsIgnoreCase(type)) { map.put(key, Util.getDoubleValue(rs.getString(i))); + map.put(key.toLowerCase(), Util.getDoubleValue(rs.getString(i))); continue; } if ("DECIMAL".equalsIgnoreCase(type) || "NUMERIC".equalsIgnoreCase(type)) { @@ -144,10 +147,12 @@ public class DealWithMapping extends ToolUtil { decimal = new BigDecimal(val); } map.put(key, decimal); + map.put(key.toLowerCase(), decimal); // map.put(key, rs.getDouble(i)); continue; } map.put(key, rs.getString(i)); + map.put(key.toLowerCase(), rs.getString(i)); } return map; } @@ -675,6 +680,12 @@ public class DealWithMapping extends ToolUtil { } } } + // 自定义sql用{mainTable}代替当前表名 解决极兔ncc问题 + if(StringUtils.isNotBlank(mainTable)){ + valueContext = valueContext.replace("{mainTable}", mainTable); + }else { + logger.error("mainTable is null!"); + } String requestId = Util.null2String(mainMap.get("requestid")); tempValue = "'" + tempValue + "'"; value = this.getValueByChangeRule(valueContext, tempValue, requestId, detailId); @@ -688,7 +699,9 @@ public class DealWithMapping extends ToolUtil { // 数据id case MAIN_DATA_ID: { if ("1".equals(childSource)) { - value = Util.null2String(detailMap.get("id")); + if (Objects.nonNull(detailMap)) { + value = Util.null2String(detailMap.get("id")); + } } else { value = Util.null2String(mainMap.get("id")); } @@ -1007,7 +1020,7 @@ public class DealWithMapping extends ToolUtil { } else if ("0".equals(childSource)) { tempValue = Util.null2String(mainMap.get(fieldName)); if ("".equals(tempValue)) { - tempValue = Util.null2String(detailMap.get(fieldNameLower)); + tempValue = Util.null2String(mainMap.get(fieldNameLower)); } } else { tempValue = Util.null2String(relationRs.getString(fieldName)); @@ -1021,6 +1034,12 @@ public class DealWithMapping extends ToolUtil { tempValue = Util.null2String(tempRs.getString(fieldName)); } } + // 自定义sql用{mainTable}代替当前表名 解决极兔ncc问题 + if(StringUtils.isNotBlank(mainTable)){ + valueContext = valueContext.replace("{mainTable}", mainTable); + }else { + logger.error("mainTable is null!"); + } tempValue = "'" + tempValue + "'"; value = this.getValueByChangeRule(valueContext, tempValue, requestId, detailId); } @@ -1068,7 +1087,7 @@ public class DealWithMapping extends ToolUtil { } else { value = Util.null2String(mainMap.get(fieldName)); if ("".equals(value)) { - value = Util.null2String(detailMap.get(fieldNameLower)); + value = Util.null2String(mainMap.get(fieldNameLower)); } } String fileIds = Util.null2String(value); @@ -1108,7 +1127,7 @@ public class DealWithMapping extends ToolUtil { } else { value = Util.null2String(mainMap.get(fieldName)); if ("".equals(value)) { - value = Util.null2String(detailMap.get(fieldNameLower)); + value = Util.null2String(mainMap.get(fieldNameLower)); } } } @@ -1521,33 +1540,6 @@ public class DealWithMapping extends ToolUtil { if (split.length > 1) { paramStr = Arrays.stream(split).skip(1).collect(Collectors.joining("?")); } -/* 获取?后的参数:"weaver.aiyh_jitu.pushdata.service.toones.GetRequestValueCusGetValueImpl?" + - "requestType=get&apiOnlyMark=getAssign&valueKey=data&assign=#{main.zd2}&" + - "#processorClass=weaver.aiyh_jitu.pushdata.service.toones.GetAssignProcessorProcessorImpl" + - "&afterProcessor.hrmId=#{main.zd2}&beforeProcessor.hrmId=#{main.zd2}&高=udh高殿下g" + - "&assignValue=#sql{select workcode from hrmresource where id = #{main.zd1} and test = #{h-hah} and a in (${hrmids})}&hah=haode"; - 最终获取到的map,如下 - key:requestType - value:get - key:apiOnlyMark - value:getAssign - key:valueKey - value:data - key:assign - value:#{main.zd2} - key:#processorClass - value:weaver.aiyh_jitu.pushdata.service.toones.GetAssignProcessorProcessorImpl - key:afterProcessor.hrmId - value:#{main.zd2} - key:beforeProcessor.hrmId - value:#{main.zd2} - key:高 - value:udh高殿下g - key:assignValue - value:#sql{select workcode from hrmresource where id = #{main.zd1} and test = #{h-hah} and a in (${hrmids})} - key:hah - value:haode*/ - // 最终通过反射调用weaver.aiyh_jitu.pushdata.service.GetAssignProcessorProcessorImpl类,将参数传递给这个类, 使用``包裹的字符串会被解析为一个字符串 String pattern = "&?(?([#.\\w\\u4E00-\\u9FA5]+))=" + "(?((`([^`]*)`)|" + "((#(\\{|sql\\{))?([():/\\-$_#={ }.\\w\\u4E00-\\u9FA5?]+)?}?)))&?"; diff --git a/src/main/java/weaver/xuanran/wang/eighty_five_degreec/sap/action/WorkflowToSap.java b/src/main/java/weaver/xuanran/wang/eighty_five_degreec/sap/action/WorkflowToSap.java index 46cc313..63443f3 100644 --- a/src/main/java/weaver/xuanran/wang/eighty_five_degreec/sap/action/WorkflowToSap.java +++ b/src/main/java/weaver/xuanran/wang/eighty_five_degreec/sap/action/WorkflowToSap.java @@ -1,17 +1,14 @@ package weaver.xuanran.wang.eighty_five_degreec.sap.action; -import aiyh.utils.ThreadPoolConfig; import aiyh.utils.action.SafeCusBaseAction; -import aiyh.utils.annotation.ActionDesc; -import aiyh.utils.annotation.PrintParamMark; -import aiyh.utils.annotation.RequiredMark; +import aiyh.utils.annotation.*; +import aiyh.utils.excention.CustomerException; import weaver.hrm.User; import weaver.soa.workflow.request.RequestInfo; import weaver.xuanran.wang.eighty_five_degreec.sap.entity.eneity.MainRequestConfig; import weaver.xuanran.wang.eighty_five_degreec.sap.service.WorkflowToSapService; import weaver.xuanran.wang.eighty_five_degreec.sap.service.impl.WorkflowToSapServiceImpl; -import java.util.concurrent.ExecutorService; /** *

将流程数据推送到sap中

@@ -23,31 +20,53 @@ import java.util.concurrent.ExecutorService; public class WorkflowToSap extends SafeCusBaseAction { private final WorkflowToSapService service = new WorkflowToSapServiceImpl(); - private final ExecutorService pool = ThreadPoolConfig.createThreadPoolInstance(); @PrintParamMark @RequiredMark("配置表唯一标识") + @ActionDefaultTestValue(value = "****") private String uniqueCode; @PrintParamMark @RequiredMark("日志表模块id") + @ActionDefaultTestValue(value = "11") private String modelId; + @PrintParamMark + @RequiredMark("成功失败/标识字段") + @ActionDefaultTestValue(value = "soap-env:Envelope.soap-env:Body.n0:ZFI_OA_DOC_POSTINGResponse.ES_OA_OUTPUT.TYPE") + private String successField; + @PrintParamMark + @RequiredMark("成功时候的值") + @ActionDefaultTestValue(value = "T") + private String successVal; + @PrintParamMark + @RequiredMark("消息提示字段") + @ActionDefaultTestValue(value = "soap-env:Envelope.soap-env:Body.n0:ZFI_OA_DOC_POSTINGResponse.ES_OA_OUTPUT.MESSAGE") + private String messageField; @Override public void doSubmit(String requestId, String billTable, int workflowId, User user, RequestInfo requestInfo) { + String xml = ""; + String response = ""; + String url = ""; + String error = ""; + boolean success = true; try { MainRequestConfig config = service.getRequestConfig(uniqueCode, billTable); - String xml = service.convertXml(config, requestId, billTable); - String response = service.sendToSap(); - pool.execute(()->{ - try { - service.logToOA(modelId, config.getRequestUrl(), requestId, xml, response); - }catch (Exception e){ - log.error("日志数据写入建模失败! " + e.getMessage()); - } - }); + url = config.getRequestUrl(); + xml = service.convertXml(config, requestId, billTable); + response = service.sendToSap(config.getRequestUrl(), xml); + service.parseResponse(response, successField, successVal, messageField); }catch (Exception e){ log.error("流程数据推送SAP error : " + e.getMessage()); + error = e.getMessage(); + success = false; + } + try { + service.logToOA(modelId, url, requestId, xml, response, error); + }catch (Exception e){ + log.error("日志数据写入建模失败! " + e.getMessage()); + } + if(!success){ + throw new CustomerException("WorkflowToSap Action execute error : " + error); } - } } diff --git a/src/main/java/weaver/xuanran/wang/eighty_five_degreec/sap/entity/eneity/DetailRequestConfig.java b/src/main/java/weaver/xuanran/wang/eighty_five_degreec/sap/entity/eneity/DetailRequestConfig.java index 5509ef1..ea5798f 100644 --- a/src/main/java/weaver/xuanran/wang/eighty_five_degreec/sap/entity/eneity/DetailRequestConfig.java +++ b/src/main/java/weaver/xuanran/wang/eighty_five_degreec/sap/entity/eneity/DetailRequestConfig.java @@ -11,6 +11,9 @@ import lombok.Data; */ @Data public class DetailRequestConfig { + @SqlDbFieldAnn("nodeType") + @SqlOracleDbFieldAnn("NODETYPE") + private String nodeType; @SqlDbFieldAnn("paramName") @SqlOracleDbFieldAnn("PARAMNAME") private String paramName; diff --git a/src/main/java/weaver/xuanran/wang/eighty_five_degreec/sap/service/WorkflowToSapService.java b/src/main/java/weaver/xuanran/wang/eighty_five_degreec/sap/service/WorkflowToSapService.java index 0498b63..7e1a14b 100644 --- a/src/main/java/weaver/xuanran/wang/eighty_five_degreec/sap/service/WorkflowToSapService.java +++ b/src/main/java/weaver/xuanran/wang/eighty_five_degreec/sap/service/WorkflowToSapService.java @@ -11,6 +11,7 @@ import weaver.xuanran.wang.eighty_five_degreec.sap.entity.eneity.MainRequestConf public interface WorkflowToSapService { MainRequestConfig getRequestConfig(String uniqueCode, String tableName); String convertXml(MainRequestConfig config, String requestId, String tableName); - String sendToSap(); - void logToOA(String modelId, String url, String requestId, String requestXml, String response); + String sendToSap(String url, String xml); + String parseResponse(String response, String responseField, String successField, String messageField); + void logToOA(String modelId, String url, String requestId, String requestXml, String response, String error); } diff --git a/src/main/java/weaver/xuanran/wang/eighty_five_degreec/sap/service/impl/WorkflowToSapServiceImpl.java b/src/main/java/weaver/xuanran/wang/eighty_five_degreec/sap/service/impl/WorkflowToSapServiceImpl.java index b0aa755..607f0dc 100644 --- a/src/main/java/weaver/xuanran/wang/eighty_five_degreec/sap/service/impl/WorkflowToSapServiceImpl.java +++ b/src/main/java/weaver/xuanran/wang/eighty_five_degreec/sap/service/impl/WorkflowToSapServiceImpl.java @@ -1,6 +1,11 @@ package weaver.xuanran.wang.eighty_five_degreec.sap.service.impl; import aiyh.utils.Util; +import aiyh.utils.excention.CustomerException; +import org.apache.log4j.Logger; +import org.json.JSONObject; +import org.json.XML; +import weaver.xuanran.wang.common.util.CusData2OA; import weaver.xuanran.wang.common.util.CusInfoToOAUtil; import weaver.xuanran.wang.eighty_five_degreec.sap.entity.eneity.MainRequestConfig; import weaver.xuanran.wang.eighty_five_degreec.sap.service.WorkflowToSapService; @@ -8,6 +13,7 @@ import weaver.xuanran.wang.eighty_five_degreec.sap.util.ReadConfigUtil; import java.util.Collections; import java.util.HashMap; +import java.util.Map; /** @@ -18,7 +24,7 @@ import java.util.HashMap; */ public class WorkflowToSapServiceImpl implements WorkflowToSapService { private final ReadConfigUtil configUtil = new ReadConfigUtil(); - + private final Logger log = Util.getLogger(); @Override public MainRequestConfig getRequestConfig(String uniqueCode, String tableName) { return configUtil.getConfigByUniqueCode(uniqueCode, tableName); @@ -30,20 +36,40 @@ public class WorkflowToSapServiceImpl implements WorkflowToSapService { } @Override - public String sendToSap() { - // TODO sap接口调用方式暂时搞不了 - return ""; + public String sendToSap(String url, String xml) { + return configUtil.callSap(url, xml); + } + + @Override + public String parseResponse(String response, String successField, String successVal, String messageField) { + String responseVal; + JSONObject xmlResponseObj; + try { + xmlResponseObj = XML.toJSONObject(response); + }catch (Exception e){ + throw new CustomerException("xml to jsonObj error : " + e.getMessage()); + } + Map responseMap = com.alibaba.fastjson.JSONObject.parseObject(xmlResponseObj.toString(), Map.class); + responseVal = configUtil.parseMap(responseMap, successField); + if(!successVal.equals(responseVal)){ + throw new CustomerException("successVal not equals responseVal! current responseVal is : " + + responseVal + ", the successVal is " + successVal + ", responseMsg is " + configUtil.parseMap(responseMap, messageField)); + } + return responseVal; } @Override public void logToOA(String modelId, String url, String requestId, - String requestXml, String response) { + String requestXml, String response, String error) { HashMap params = new HashMap<>(); - params.put("requestUrlAndFunName", url); + params.put("requestUrl", url); params.put("reqId", requestId); params.put("requestXml", requestXml); params.put("responseCode",""); - params.put("erpResponse", response); - CusInfoToOAUtil.getDataId(Util.getIntValue(modelId, -1), params, "select id from #{tableName} where reqId = ?", Collections.singletonList(requestId)); + params.put("sapResponse", response); + params.put("error", error); + log.info("写入日志参数 : " + com.alibaba.fastjson.JSONObject.toJSONString(params)); + CusData2OA.writeToModel(modelId, "select id from #{tableName} where reqId = " + requestId, params); } + } diff --git a/src/main/java/weaver/xuanran/wang/eighty_five_degreec/sap/util/ReadConfigUtil.java b/src/main/java/weaver/xuanran/wang/eighty_five_degreec/sap/util/ReadConfigUtil.java index d805dd1..bfe44cc 100644 --- a/src/main/java/weaver/xuanran/wang/eighty_five_degreec/sap/util/ReadConfigUtil.java +++ b/src/main/java/weaver/xuanran/wang/eighty_five_degreec/sap/util/ReadConfigUtil.java @@ -1,5 +1,6 @@ package weaver.xuanran.wang.eighty_five_degreec.sap.util; +import aiyh.utils.excention.CustomerException; import com.google.common.base.Strings; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; @@ -12,11 +13,10 @@ import weaver.xuanran.wang.eighty_five_degreec.sap.entity.eneity.DetailRequestCo import weaver.xuanran.wang.eighty_five_degreec.sap.entity.eneity.MainRequestConfig; import weaver.zwl.common.ToolUtil; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStreamReader; +import java.io.*; import java.lang.reflect.Field; +import java.net.HttpURLConnection; +import java.net.URL; import java.nio.charset.StandardCharsets; import java.security.SecureRandom; import java.text.ParseException; @@ -55,7 +55,7 @@ public class ReadConfigUtil extends ToolUtil { } int mainId = Util.getIntValue(res.getId()); // 配置明细表 - sql = "select paramName,paramType,parentName,getValueType,workflowField,valueContext,fv.tableName," + + sql = "select nodeType,paramName,paramType,parentName,getValueType,workflowField,valueContext,fv.tableName," + " fv.id fieldId,fv.fieldname,fv.indexdesc " + " from uf_memsic_createXml_dt1 config " + " left join workflow_field_table_view fv on config.workflowField = fv.id " + @@ -88,7 +88,7 @@ public class ReadConfigUtil extends ToolUtil { * @return 返回类对象 **/ public static T getInstance(RecordSet queryRs, Class clazz) { - T res = null; + T res; try { res = clazz.newInstance(); Field[] fields = clazz.getDeclaredFields(); @@ -443,15 +443,35 @@ public class ReadConfigUtil extends ToolUtil { // 明细 String[] detailIdArr = detailIndex.split(","); StringBuilder detailSb = new StringBuilder(); + for (String detailId : detailIdArr) { + String nodeName; + List nodeList = requestConfigList.stream() + .filter(item -> "0".equals(item.getNodeType())).collect(Collectors.toList()); + if(CollectionUtils.isNotEmpty(nodeList)){ + nodeName = nodeList.get(0).getParamName(); + } else { + nodeName = ""; + } List detailCollect = requestConfigList.stream() - .filter(item -> "detailRecord".equals(item.getParentName()) - ).collect(Collectors.toList()); + .filter(item -> { + if(StringUtils.isNotBlank(nodeName)){ + return nodeName.equals(item.getParentName()); + }else { + return "detailRecord".equals(item.getParentName()); + } + }).collect(Collectors.toList()); String detailSql = "select * from " + tableName + "_dt" + detailId + " where mainid = ?"; if (detailRs.executeQuery(detailSql, mainId)) { int count = 1; while (detailRs.next()) { + if(StringUtils.isNotBlank(nodeName)){ + detailSb.append("<").append(nodeName).append(">\n"); + } appendXml(detailSb, detailCollect, mainRs, detailRs, count++); + if(StringUtils.isNotBlank(nodeName)){ + detailSb.append("\n"); + } } } } @@ -474,7 +494,7 @@ public class ReadConfigUtil extends ToolUtil { .append(paramName) .append(">") .append(getParamValue(requestConfig, mainRs, detailRs,count)) - .append("<") + .append("") .append("\n"); @@ -544,22 +564,80 @@ public class ReadConfigUtil extends ToolUtil { * @return 响应数据 */ public String parseMap(Map responseMap, String responseField){ - String[] strArr = responseField.split("\\."); - int i = 0; - while (i < strArr.length - 1){ - Object o = responseMap.get(strArr[i]); - if(o instanceof Map){ - responseMap = (Map) o; - }else if(o instanceof List){ - List> list = (List>) o; - if(CollectionUtils.isEmpty(list)){ - return ""; - } - responseMap = list.get(0); - } - i++; - } - return Util.null2String(responseMap.get(strArr[strArr.length - 1])); + try { + String[] strArr = responseField.split("\\."); + int i = 0; + while (i < strArr.length - 1){ + Object o = responseMap.get(strArr[i]); + if(o instanceof Map){ + responseMap = (Map) o; + }else if(o instanceof List){ + List> list = (List>) o; + if(CollectionUtils.isEmpty(list)){ + return ""; + } + responseMap = list.get(0); + } + i++; + } + return Util.null2String(responseMap.get(strArr[strArr.length - 1])); + }catch (Exception e){ + throw new CustomerException("parseMap error : " + e.getMessage()); + } } + /** + *

调用sap接口

+ * @author xuanran.wang + * @dateTime 2023/5/15 14:05 + * @param url 接口地址 + * @param xml 报文xml + * @return 接口响应 + **/ + public String callSap(String url, String xml){ + OutputStreamWriter writer = null; + BufferedReader reader = null; + try { + String userName = aiyh.utils.Util.null2DefaultStr(getSystemParamValue("sapUserName"),""); + String password = aiyh.utils.Util.null2DefaultStr(getSystemParamValue("sapPassword"),""); + log.info("callSap userName : [ " + userName + " ], password : [ " + password + " ]"); + String authString = userName + ":" + password; + byte[] authEncBytes = Base64.getEncoder().encode(authString.getBytes()); + String authStringEnc = new String(authEncBytes); + URL serviceUrl = new URL(url); + HttpURLConnection connection = (HttpURLConnection) serviceUrl.openConnection(); + connection.setRequestMethod("POST"); + connection.setRequestProperty("Content-Type", "text/xml; charset=utf-8"); + connection.setRequestProperty("Authorization", "Basic " + authStringEnc); + connection.setDoOutput(true); + writer = new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8); + writer.write(xml); + writer.close(); + reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8)); + String line; + StringBuilder responseBuilder = new StringBuilder(); + while ((line = reader.readLine()) != null) { + responseBuilder.append(line); + } + reader.close(); + String response = responseBuilder.toString(); + if(StringUtils.isBlank(response)){ + throw new CustomerException("sap response is empty!"); + } + return response; + }catch (Exception e){ + throw new CustomerException("callSap error : " + e.getMessage()); + }finally { + try { + if(writer != null){ + writer.close(); + } + if(reader != null){ + reader.close(); + } + }catch (Exception e){ + log.error("关流异常 : " + e.getMessage()); + } + } + } } diff --git a/src/main/java/weaver/xuanran/wang/sh_bigdata/common/util/ShBigDataUtil.java b/src/main/java/weaver/xuanran/wang/sh_bigdata/common/util/ShBigDataUtil.java index bcf46c6..13de9f8 100644 --- a/src/main/java/weaver/xuanran/wang/sh_bigdata/common/util/ShBigDataUtil.java +++ b/src/main/java/weaver/xuanran/wang/sh_bigdata/common/util/ShBigDataUtil.java @@ -35,6 +35,8 @@ public class ShBigDataUtil { WHILTE_LIST.add("loginErrorSendRedirectUrl"); WHILTE_LIST.add("getUserIdDebug"); WHILTE_LIST.add("getUserIdDebugOutKey"); + WHILTE_LIST.add("ssoInterfaceCompareField"); + WHILTE_LIST.add("ssoOaCompareField"); } /** diff --git a/src/main/java/weaver/youhong/ai/geerde/action/submitfirst/AutoSubmitFirstAction.java b/src/main/java/weaver/youhong/ai/geerde/action/submitfirst/AutoSubmitFirstAction.java new file mode 100644 index 0000000..ded5743 --- /dev/null +++ b/src/main/java/weaver/youhong/ai/geerde/action/submitfirst/AutoSubmitFirstAction.java @@ -0,0 +1,124 @@ +package weaver.youhong.ai.geerde.action.submitfirst; + +import aiyh.utils.Util; +import aiyh.utils.action.SafeCusBaseAction; +import aiyh.utils.annotation.*; +import aiyh.utils.tool.cn.hutool.core.util.StrUtil; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; +import weaver.hrm.User; +import weaver.soa.workflow.request.RequestInfo; +import weaver.youhong.ai.geerde.action.submitfirst.mapper.AutoSubmitFirstMapper; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + *

自动提交第一次经过节点的流程

+ * + *

create: 2023/5/17 18:52

+ * + * @author youHong.ai + */ +@Getter +@Setter +@ToString +@ActionDesc(author = "youhong.ai", value = "自动流程提交,需要挂在需要提交的流程节点的节点前或者前一个节点的节点后或者两个节点的流转出口线上") +public class AutoSubmitFirstAction extends SafeCusBaseAction { + + private final AutoSubmitFirstMapper mapper = Util.getMapper(AutoSubmitFirstMapper.class); + + @RequiredMark(value = "account", desc = "主表流程经过标识字段,整数或单行文本字段名都可以") + @PrintParamMark + @ActionDefaultTestValue("account") + private String accountField; + + @ActionOptionalParam(value = "1", desc = "流程操作人id,默认为1-系统管理员") + @PrintParamMark + private String operator = "1"; + + private static final Map oneRequestLock = new ConcurrentHashMap<>(); + + @Override + @SuppressWarnings("all") + public void doSubmit(String requestId, String billTable, + int workflowId, User user, + RequestInfo requestInfo) { + // 如果存在当前流程id的值,表示当前action属于锁住状态,需要进入线程睡眠等待 + if (oneRequestLock.containsKey(requestId)) { + log.info("流程正在异步提交中,使用线程排队"); + new Thread(() -> { + log.info("开始异步等待上一个节点提交"); + while (oneRequestLock.containsKey(requestId)) { + try { + Thread.sleep(1000L * 60 * oneRequestLock.get(requestId)); + } catch (InterruptedException e) { + log.error("线程休眠失败!"); + throw new RuntimeException(e); + } + } + log.info("开始提交流程!"); + oneRequestLock.put(requestId, 2); + Map mainMap = mapper.selectMainMap(billTable, requestId); + String currentNode = mapper.selectCurrentNodeId(requestId); + if (mainMap.containsKey(accountField)) { + String mark = Util.null2String(mainMap.get(accountField)); + String nodesStr = currentNode; + if (StrUtil.isNotBlank(mark)) { + String[] split = mark.split(","); + List nodes = Arrays.asList(split); + if (nodes.contains(currentNode)) { + return; + } + nodesStr += "," + Util.join(nodes, ","); + } + int creatorId = requestInfo.getRequestManager().getCreater(); + String finalNodesStr = nodesStr; + Util.submitWorkflowThread(Integer.parseInt(requestId), creatorId, + "", 60, flag -> { + oneRequestLock.remove(requestId); + if (flag) { + mapper.updateMark(billTable, accountField, finalNodesStr, + Util.null2String(mainMap.get("id"))); + } + }); + } + }).start(); + return; + } + // 如果没有锁住,异步延时提交,延时3分钟 + log.info("没有锁住流程,开始异步提交流程"); + oneRequestLock.put(requestId, 2); + Map mainTableValue = getMainTableValue(requestInfo); + String currentNode = mapper.selectCurrentNodeId(requestId); + int creatorId = requestInfo.getRequestManager().getCreater(); + // 判断是否存在统计字段 + if (mainTableValue.containsKey(accountField)) { + // 获取统计字段的值 + String mark = mainTableValue.get(accountField); + String nodesStr = currentNode; + if (StrUtil.isNotBlank(mark)) { + String[] split = mark.split(","); + List nodes = Arrays.asList(split); + if (nodes.contains(currentNode)) { + return; + } + nodesStr += "," + Util.join(nodes, ","); + } + String finalNodesStr = nodesStr; + Util.submitWorkflowThread(Integer.parseInt(requestId), creatorId, + "", 60, flag -> { + oneRequestLock.remove(requestId); + if (flag) { + log.info("异步提交流程完成!"); + // 提交成功,更新标识 + mapper.updateMark(billTable, accountField, finalNodesStr, + mainTableValue.get("id")); + } + }); + } + } +} diff --git a/src/main/java/weaver/youhong/ai/geerde/action/submitfirst/mapper/AutoSubmitFirstMapper.java b/src/main/java/weaver/youhong/ai/geerde/action/submitfirst/mapper/AutoSubmitFirstMapper.java new file mode 100644 index 0000000..1878ae0 --- /dev/null +++ b/src/main/java/weaver/youhong/ai/geerde/action/submitfirst/mapper/AutoSubmitFirstMapper.java @@ -0,0 +1,33 @@ +package weaver.youhong.ai.geerde.action.submitfirst.mapper; + +import aiyh.utils.annotation.recordset.ParamMapper; +import aiyh.utils.annotation.recordset.Select; +import aiyh.utils.annotation.recordset.SqlMapper; +import aiyh.utils.annotation.recordset.Update; + +import java.util.Map; + +/** + *

自动提交流程标识更新

+ * + *

create: 2023/5/17 18:56

+ * + * @author youHong.ai + */ +@SqlMapper +public interface AutoSubmitFirstMapper { + + @Update("update $t{tableName} set $t{fieldName} = #{value} where id = #{id}") + boolean updateMark(@ParamMapper("tableName") String tableName, + @ParamMapper("fieldName") String fieldName, + @ParamMapper("value") String value, + @ParamMapper("id") String id); + + + @Select("select * from $t{tableName} where requestid = #{requestId}") + Map selectMainMap(@ParamMapper("tableName") String tableName, @ParamMapper("requestId") String requestId); + + + @Select("select currentnodeid from workflow_requestbase where requestid = #{requestId}") + String selectCurrentNodeId(@ParamMapper("requestId") String requestId); +} diff --git a/src/main/java/weaver/youhong/ai/intellectualproperty/action/CaElectronicSignatureAction.java b/src/main/java/weaver/youhong/ai/intellectualproperty/action/CaElectronicSignatureAction.java index c9d1abb..3bd5223 100644 --- a/src/main/java/weaver/youhong/ai/intellectualproperty/action/CaElectronicSignatureAction.java +++ b/src/main/java/weaver/youhong/ai/intellectualproperty/action/CaElectronicSignatureAction.java @@ -20,8 +20,10 @@ import javax.ws.rs.core.MediaType; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.InputStream; +import java.net.URLDecoder; import java.util.Base64; import java.util.Map; +import java.util.Objects; /** *

知识产权局ca电子签

@@ -87,8 +89,13 @@ public class CaElectronicSignatureAction extends SafeCusBaseAction { throw new CustomerException(responeVo.getCode() + ", fetch ca sign fail! "); } Map responseMap = responeVo.getResponseMap(); - String documentNo = Util.null2String(responseMap.get("document_no")); - String pdf = Util.null2String(responseMap.get("ofd")); + Map data = (Map) responseMap.get("data"); + if (Objects.isNull(data)) { + Util.actionFail(requestInfo.getRequestManager(), URLDecoder.decode(Util.null2String(responseMap.get("ret_msg")), "UTF-8")); + return; + } + String documentNo = Util.null2String(data.get("document_no")); + String pdf = Util.null2String(data.get("ofd")); InputStream inputStream = base64ContentToFile(pdf); String docCategorys = Util.getDocCategorysByTable(String.valueOf(workflowId), signFileField, billTable); String[] docCategoryArr = docCategorys.split(","); diff --git a/src/main/java/weaver/youhong/ai/intellectualproperty/cusgetvalue/GetOfdKeywordPageValue.java b/src/main/java/weaver/youhong/ai/intellectualproperty/cusgetvalue/GetOfdKeywordPageValue.java new file mode 100644 index 0000000..d65c606 --- /dev/null +++ b/src/main/java/weaver/youhong/ai/intellectualproperty/cusgetvalue/GetOfdKeywordPageValue.java @@ -0,0 +1,60 @@ +package weaver.youhong.ai.intellectualproperty.cusgetvalue; + +import aiyh.utils.Util; +import aiyh.utils.entity.DocImageInfo; +import aiyh.utils.excention.CustomerException; +import aiyh.utils.tool.cn.hutool.core.util.StrUtil; +import org.apache.log4j.Logger; +import weaver.file.ImageFileManager; +import weaver.xiao.commons.config.interfacies.CusInterfaceGetValue; +import weaver.youhong.ai.intellectualproperty.util.OFDReader; + +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.List; +import java.util.Map; + +/** + *

获取关键字页码

+ * + *

create: 2023/5/18 16:56

+ * + * @author youHong.ai + */ +public class GetOfdKeywordPageValue implements CusInterfaceGetValue { + private final Logger log = Util.getLogger(); + + @Override + public Object execute(Map mainMap, Map detailMap, String currentValue, Map pathParam) { + try { + DocImageInfo docImageInfo = Util.selectImageInfoByDocId(currentValue); + InputStream inputStream = ImageFileManager.getInputStreamById(docImageInfo.getImageFileId()); + String filePath = Util.createTempFile(inputStream, docImageInfo.getImageFileName(), "ofd"); + String keywordType = pathParam.get("keywordType"); + String keywordValue = ""; + String keyword = pathParam.get("keyword"); + if (StrUtil.isNotBlank(keywordType)) { + if ("1".equals(keywordType)) { + keywordValue = Util.null2String(mainMap.get(keyword)); + } else { + keywordValue = keyword; + } + } else { + keywordValue = keyword; + } + OFDReader reader = new OFDReader(filePath, keywordValue); + List keywordInfos = reader.findKeywords(); + Files.delete(Paths.get(filePath)); + if (keywordInfos.isEmpty()) { + throw new CustomerException("关键字定位异常!未找到关键字"); + } else { + String pageNumber = keywordInfos.get(keywordInfos.size() - 1).getStart().getPageNumber(); + return Integer.parseInt(pageNumber) + 1; + } + } catch (Exception e) { + log.error("关键字定位异常: " + Util.getErrString(e)); + throw new CustomerException("关键字定位异常!", e); + } + } +} diff --git a/src/main/java/weaver/youhong/ai/intellectualproperty/util/OFDReader.java b/src/main/java/weaver/youhong/ai/intellectualproperty/util/OFDReader.java new file mode 100644 index 0000000..09061af --- /dev/null +++ b/src/main/java/weaver/youhong/ai/intellectualproperty/util/OFDReader.java @@ -0,0 +1,185 @@ +package weaver.youhong.ai.intellectualproperty.util; + +import org.w3c.dom.Document; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +import javax.xml.parsers.DocumentBuilderFactory; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; + +/** + *

ofd读区关键字

+ */ +public class OFDReader { + + private final String ofdFilePath; + private final String keyword; + + public OFDReader(String ofdFilePath, String keyword) { + this.ofdFilePath = ofdFilePath; + this.keyword = keyword; + } + + public List findKeywords() throws Exception { + // 解析OFD.xml文件,获取OFD的根目录路径 + String rootDirPath = parseOFDXmlAndGetRootDirPath(); + if (rootDirPath == null) { + throw new Exception("Failed to parse OFD.xml file!"); + } + + // 打开OFD文件并获取ZipFile对象 + ZipFile zipFile = new ZipFile(ofdFilePath); + + // 获取Pages目录下的所有页面文件夹 + List pageFolders = getPageFolders(zipFile, rootDirPath); + if (pageFolders == null || pageFolders.isEmpty()) { + throw new Exception("No page found in the OFD file!"); + } + + // 查找所有关键字的位置信息 + List result = new ArrayList<>(); + for (String pageFolder : pageFolders) { + KeywordInfoRange keywordInfo = findKeywordInPage(zipFile, pageFolder); + if (keywordInfo != null) { + result.add(keywordInfo); + } + } + + zipFile.close(); + return result; + } + + // 解析OFD.xml文件并获取OFD的根目录路径 + private String parseOFDXmlAndGetRootDirPath() throws Exception { + ZipFile zipFile = new ZipFile(ofdFilePath); + ZipEntry ofdXmlEntry = zipFile.getEntry("OFD.xml"); + InputStream inputStream = zipFile.getInputStream(ofdXmlEntry); + + Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inputStream); + NodeList docRootNodes = doc.getElementsByTagName("ofd:DocRoot"); + if (docRootNodes.getLength() == 0) { + return null; + } + + String docRootPath = docRootNodes.item(0).getTextContent(); + String[] docRootPathSegments = docRootPath.split("/"); + if (docRootPathSegments.length == 0) { + return null; + } + + return docRootPathSegments[0]; + } + + // 获取Pages目录下的所有页面文件夹 + private List getPageFolders(ZipFile zipFile, String rootDirPath) { + List pageFolders = new ArrayList<>(); + String pagesDirPath = rootDirPath + "/Pages/"; + String pagesPrefix = pagesDirPath + "Page_"; + String pagesSuffix = "Content.xml"; + // 遍历OFD文件中所有的ZipEntry对象,查找所有页面文件夹 + zipFile.stream().forEach(entry -> { + if (entry.getName().startsWith(pagesDirPath) && entry.getName().startsWith(pagesPrefix) && entry.getName().endsWith(pagesSuffix) && !entry.getName().equals(pagesDirPath)) { + pageFolders.add(entry.getName()); + } + }); + + return pageFolders; + } + + // 在指定页面中查找关键字 + private KeywordInfoRange findKeywordInPage(ZipFile zipFile, String pageFolder) throws Exception { + ZipEntry contentXmlEntry = zipFile.getEntry(pageFolder); + InputStream inputStream = zipFile.getInputStream(contentXmlEntry); + + Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inputStream); + NodeList textNodes = doc.getElementsByTagName("ofd:TextObject"); + int startK = 0; + List keywordInfos = new ArrayList<>(); + for (int i = 0; i < textNodes.getLength(); i++) { + Node textNode = textNodes.item(i); + String textContent = textNode.getTextContent(); + char[] chars = textContent.toCharArray(); + char[] keywordChars = keyword.toCharArray(); + for (int j = 0; j < chars.length; j++) { + for (int k = startK; k < keywordChars.length; k++) { + char contentChar = chars[j]; + char keywordChar = keywordChars[k]; + if (contentChar == keywordChar) { + j++; + if (j == chars.length) { + startK = j; + Node boundaryNode = textNode.getAttributes().getNamedItem("Boundary"); + String boundary = boundaryNode.getNodeValue(); + String[] boundarySegments = boundary.split(" "); + double x = Double.parseDouble(boundarySegments[0]); + double y = Double.parseDouble(boundarySegments[1]); + double width = Double.parseDouble(boundarySegments[2]); + double height = Double.parseDouble(boundarySegments[3]); + KeywordInfo keywordInfo = new KeywordInfo(pageFolder, x, y, width, height); + keywordInfos.add(keywordInfo); + break; + } + } else { + startK = 0; + keywordInfos.clear(); + break; + } + } + } + } + + if (keywordInfos.isEmpty()) { + return null; + } + return new KeywordInfoRange(keywordInfos.get(0), keywordInfos.get(keywordInfos.size() - 1)); + } + + public static class KeywordInfoRange { + private final KeywordInfo start; + + private final KeywordInfo end; + + public KeywordInfoRange(KeywordInfo start, KeywordInfo end) { + this.start = start; + this.end = end; + } + + public KeywordInfo getStart() { + return start; + } + + public KeywordInfo getEnd() { + return end; + } + } + + public static class KeywordInfo { + private final String pageFolder; + private final double x; + private final double y; + private final double width; + private final double height; + + + public KeywordInfo(String pageFolder, double x, double y, double width, double height) { + this.pageFolder = pageFolder; + this.x = x; + this.y = y; + this.width = width; + this.height = height; + } + + public String getPageNumber() { + int pageNumber = Integer.parseInt(pageFolder.substring(pageFolder.lastIndexOf('_') + 1, pageFolder.length() - "/Content.xml".length())); + return String.valueOf(pageNumber); + } + + public String getBoundingBox() { + return "(" + x + ", " + y + ", " + width + ", " + height + ")"; + } + } +} diff --git a/src/main/java/weaver/youhong/ai/pcn/actioin/doctoavatar/DocToAvatarAction.java b/src/main/java/weaver/youhong/ai/pcn/actioin/doctoavatar/DocToAvatarAction.java new file mode 100644 index 0000000..cff3aee --- /dev/null +++ b/src/main/java/weaver/youhong/ai/pcn/actioin/doctoavatar/DocToAvatarAction.java @@ -0,0 +1,119 @@ +package weaver.youhong.ai.pcn.actioin.doctoavatar; + +import aiyh.utils.Util; +import aiyh.utils.action.SafeCusBaseAction; +import aiyh.utils.annotation.ActionDesc; +import aiyh.utils.annotation.PrintParamMark; +import aiyh.utils.annotation.RequiredMark; +import aiyh.utils.entity.DocImageInfo; +import aiyh.utils.excention.CustomerException; +import aiyh.utils.tool.cn.hutool.core.util.IdUtil; +import com.weaver.esb.server.cache.ResourceComInfo; +import lombok.Getter; +import lombok.Setter; +import weaver.file.ImageFileManager; +import weaver.general.GCONST; +import weaver.hrm.User; +import weaver.soa.workflow.request.RequestInfo; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.file.Files; +import java.util.Map; +import java.util.Objects; + +/** + *

生成头像

+ * + *

create: 2023/5/29 17:40

+ * + * @author youHong.ai + */ +@ActionDesc(value = "生成头像", author = "youhong.ai") +@Getter +@Setter +public class DocToAvatarAction extends SafeCusBaseAction { + + @PrintParamMark + @RequiredMark(value = "sctxzp", desc = "上传头像的字段名称") + private String iconDocField; + + @RequiredMark(value = "dqyh", desc = "上传头像的字段名称") + @PrintParamMark + private String userField; + + + private final DocToAvatarActionMapper mapper = Util.getMapper(DocToAvatarActionMapper.class); + + + @Override + public void doSubmit(String requestId, String billTable, int workflowId, User user, RequestInfo requestInfo) { + Map mainTable = getMainTableValue(requestInfo); + String docIds = ""; + if (mainTable.containsKey(iconDocField)) { + docIds = mainTable.get(iconDocField); + } + String[] docArr = docIds.split(","); + if (docArr.length == 0) { + return; + } + String avatarDoc = docArr[0]; + DocImageInfo docImageInfo = Util.selectImageInfoByDocId(avatarDoc); + if (Objects.isNull(docImageInfo)) { + return; + } + InputStream inputStreamById = ImageFileManager.getInputStreamById(docImageInfo.getImageFileId()); + String avatarPath = GCONST.getRootPath(); + if (avatarPath.endsWith(File.separator)) { + avatarPath += File.separator; + } + String uuid = IdUtil.randomUUID(); + String imgName = docImageInfo.getImageFileName(); + int dotIndex = imgName.lastIndexOf("."); + if (dotIndex > 0) { + String extension = imgName.substring(dotIndex + 1); + long time = System.currentTimeMillis(); + String imageFileName = "/messager/usericon/" + uuid + "-" + time + "." + extension; + avatarPath += "messager" + File.separator + "usericon" + File.separator; + File imageFile = new File(avatarPath + uuid + "-" + time + "." + extension); + if (!imageFile.getParentFile().exists()) { + imageFile.getParentFile().mkdirs(); + } + OutputStream os = null; + try { + os = Files.newOutputStream(imageFile.toPath()); + byte[] buffer = new byte[4096]; + int bytesRead; + while ((bytesRead = inputStreamById.read(buffer)) != -1) { + os.write(buffer, 0, bytesRead); + } + } catch (IOException e) { + log.info("写入头像文件失败!" + Util.getErrString(e)); + throw new CustomerException("头像生成失败!"); + } finally { + try { + if (inputStreamById != null) { + inputStreamById.close(); + } + if (os != null) { + os.close(); + } + } catch (IOException e) { + log.info("关闭文件流失败!!" + Util.getErrString(e)); + } + } + if (mainTable.containsKey(userField)) { + String currentUser = mainTable.get(userField); + if (!mapper.updateAvatar(currentUser, imageFileName, docImageInfo.getImageFileId())) { + log.info("头像更新失败!sql出错!"); + } else { + ResourceComInfo rsc = new ResourceComInfo(); + rsc.removeCache(); + } + } + } + } + +} \ No newline at end of file diff --git a/src/main/java/weaver/youhong/ai/pcn/actioin/doctoavatar/DocToAvatarActionMapper.java b/src/main/java/weaver/youhong/ai/pcn/actioin/doctoavatar/DocToAvatarActionMapper.java new file mode 100644 index 0000000..91a8139 --- /dev/null +++ b/src/main/java/weaver/youhong/ai/pcn/actioin/doctoavatar/DocToAvatarActionMapper.java @@ -0,0 +1,29 @@ +package weaver.youhong.ai.pcn.actioin.doctoavatar; + +import aiyh.utils.annotation.recordset.ParamMapper; +import aiyh.utils.annotation.recordset.SqlMapper; +import aiyh.utils.annotation.recordset.Update; + +/** + *

更新头像

+ * + *

create: 2023/5/29 18:02

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

更新人员头像信息

+ * + * @param currentUser 当前用户 + * @param avatarImg 更新头像 + * @return 是否更新成功 + */ + @Update("update hrmresource set messagerurl = #{avatarImg},resourceimageid = #{imageId} where id = #{currentUser}") + boolean updateAvatar(@ParamMapper("currentUser") String currentUser, + @ParamMapper("avatarImg") String avatarImg, + @ParamMapper("imageId") Integer imgId); +} diff --git a/src/main/java/weaver/yunjinshan/formmode/action/ContractExpandAction.java b/src/main/java/weaver/yunjinshan/formmode/action/ContractExpandAction.java new file mode 100644 index 0000000..5bf9464 --- /dev/null +++ b/src/main/java/weaver/yunjinshan/formmode/action/ContractExpandAction.java @@ -0,0 +1,109 @@ +package weaver.yunjinshan.formmode.action; + +import weaver.conn.RecordSet; +import weaver.formmode.customjavacode.AbstractModeExpandJavaCodeNew; +import weaver.general.BaseBean; +import weaver.general.Util; +import weaver.soa.workflow.request.MainTableInfo; +import weaver.soa.workflow.request.Property; +import weaver.soa.workflow.request.RequestInfo; + +import java.text.DecimalFormat; +import java.util.HashMap; +import java.util.Map; + +/** + * 云锦山 + * 合同管理模块 新建、编辑保存和导入时,自定义扩展功能 + */ +public class ContractExpandAction extends AbstractModeExpandJavaCodeNew { + + /** + * 模块主表名称 + */ + private final static String modeTableName = "uf_hetongguanli"; + + /** + * 浮点数格式化 + */ + private final DecimalFormat df = new DecimalFormat("##############################0.0000"); + + /** + * 执行模块扩展动作 + * @param param + * param包含(但不限于)以下数据 + * user 当前用户 + * importtype 导入方式(仅在批量导入的接口动作会传输) 1 追加,2覆盖,3更新,获取方式(int)param.get("importtype") + * 导入链接中拼接的特殊参数(仅在批量导入的接口动作会传输),比如a=1,可通过param.get("a")获取参数值 + * 页面链接拼接的参数,比如b=2,可以通过param.get("b")来获取参数 + * @return 返回执行结果 + */ + public Map doModeExpand(Map param) { + Map result = new HashMap<>(); + try { + BaseBean bean = new BaseBean(); + + bean.writeLog("-------------ContractExpandAction Begin----------------"); + + bean.writeLog("param:[" + param.toString() + "]"); + + int billid;//数据id + int modeid;//模块id + RequestInfo requestInfo = (RequestInfo) param.get("RequestInfo"); + if (requestInfo != null) { + billid = Util.getIntValue(requestInfo.getRequestid()); + modeid = Util.getIntValue(requestInfo.getWorkflowid()); + + bean.writeLog("billid:[" + billid + "],modeid:[" + modeid + "]"); + + if (billid > 0 && modeid > 0) { + //String selectData = "select * from " + modeTableName + " where id = ?"; + + //年月 + String yearMonth = ""; + //一级部门 + String superiorDepartment = ""; + //客户 + String customer = ""; + + MainTableInfo mainTableInfo = requestInfo.getMainTableInfo(); + + for(Property p : mainTableInfo.getProperty()){ + if("qdny".equalsIgnoreCase(p.getName())) { + yearMonth = p.getValue(); + } + + if("yjbm".equalsIgnoreCase(p.getName())){ + superiorDepartment = p.getValue(); + } + if("khmc".equalsIgnoreCase(p.getName())){ + customer = p.getValue(); + } + } + + /* + RecordSet rs = new RecordSet(); + if(rs.executeQuery(selectData,billid)){ + if(rs.next()){ + yearMonth = Util.null2String(rs.getString("qdny")); + superiorDepartment = Util.null2String(rs.getString("yjbm")); + customer = Util.null2String(rs.getString("khmc")); + } + } + */ + + CostIncomeUpdate incomeUpdate = new CostIncomeUpdate(); + incomeUpdate.updateByContract(yearMonth,superiorDepartment,customer); + } + } + bean.writeLog("-------------ContractExpandAction End----------------"); + result.put("flag", "true"); + } catch (Exception e) { + result.put("errmsg",e.getMessage()); + result.put("flag", "false"); + e.printStackTrace(); + } + + return result; + } +} diff --git a/src/main/java/weaver/yunjinshan/formmode/action/CostIncomeUpdate.java b/src/main/java/weaver/yunjinshan/formmode/action/CostIncomeUpdate.java new file mode 100644 index 0000000..9c33db7 --- /dev/null +++ b/src/main/java/weaver/yunjinshan/formmode/action/CostIncomeUpdate.java @@ -0,0 +1,101 @@ +package weaver.yunjinshan.formmode.action; + +import weaver.conn.RecordSet; +import weaver.general.BaseBean; +import weaver.general.Util; + +import java.text.DecimalFormat; + +/** + * 云锦山 + * 成本收入更新操作 + */ +public class CostIncomeUpdate { + + private final static String contractModeTableName = "uf_hetongguanli"; + + private final static BaseBean bean = new BaseBean(); + + private final static RecordSet rs = new RecordSet(); + + /** + * 浮点数格式化 + */ + private final DecimalFormat df = new DecimalFormat("##############################0.0000"); + + /** + * 根据合同管理 变更成本收入 + * + * @param yearMonth 年月 + * @param superiorDepartment 一级部门 + * @param customer 客户 + */ + public void updateByContract(String yearMonth, String superiorDepartment, String customer) { + bean.writeLog("yearMonth:[" + yearMonth + "],superiorDepartment:[" + superiorDepartment + "],customer:[" + customer + "]"); + + // 合同金额合计 + double contractAmount = 0.0; + // 收款金额合计 + double receivableAmount = 0.0; + // 开票金额合计 + double invoiceAmount = 0.0; + // 获取该模块相同年月、一级部门、客户的合同金额合计 + String selectData = "select sum(isnull(htje,0.0)) from " + contractModeTableName + " where qdny = ? and yjbm = ? and khmc = ?"; + + if (rs.executeQuery(selectData, yearMonth, superiorDepartment, customer)) { + if (rs.next()) { + contractAmount = Util.getDoubleValue(rs.getString(1), 0.0); + } + } + + + selectData = "select sum(isnull(dt.ysje,0.0)) from " + contractModeTableName + "_dt1 dt inner join " + contractModeTableName + " m on dt.mainId = m.id " + + "where m.yjbm = ? and m.khmc = ? and (dt.skrq is not null and substring(dt.skrq,1,7) = ?)"; + + if (rs.executeQuery(selectData, superiorDepartment, customer, yearMonth) && rs.next()) { + receivableAmount = Util.getDoubleValue(rs.getString(1), 0.0); + } + + selectData = "select sum(isnull(dt.jshjje,0.0)) from " + contractModeTableName + "_dt2 dt inner join " + contractModeTableName + " m on dt.mainId = m.id " + + "where m.yjbm = ? and m.khmc = ? and (dt.kprq is not null and substring(dt.kprq,1,7) = ?)"; + + if (rs.executeQuery(selectData, superiorDepartment, customer, yearMonth) && rs.next()) { + invoiceAmount = Util.getDoubleValue(rs.getString(1), 0.0); + } + + String updateSQL = "update uf_chengbenshouru set yqhtjekkpje = " + df.format(contractAmount) + "," + + "yskje = " + df.format(receivableAmount) + "," + + "ykpjehs = " + df.format(invoiceAmount) + + " where ny = ? and yjbm = ? and kh = ?"; + + boolean isSuccess = rs.executeUpdate(updateSQL, yearMonth, superiorDepartment, customer); + + bean.writeLog("updateSQL:[" + updateSQL + "],执行结果:[" + isSuccess + "]"); + } + + /** + * 根据人力成本更新成本收入 + * + * @param yearMonth 年月 + * @param superiorDepartment 一级部门 + * @param customer 客户名称 + */ + public void updateByHumanCost(String yearMonth, String superiorDepartment, String customer) { + bean.writeLog("yearMonth:[" + yearMonth + "],superiorDepartment:[" + superiorDepartment + "],customer:[" + customer + "]"); + + double totalAmount = 0.0; + String selectData = "select sum(isnull(gszzffy,0.0)) from uf_renlichengben where ny = ? and yjbm = ? and kh = ?"; + + if (rs.executeQuery(selectData, yearMonth, superiorDepartment, customer)) { + if (rs.next()) { + totalAmount = Util.getDoubleValue(rs.getString(1), 0.0); + } + } + + String updateSQL = "update uf_chengbenshouru set rycb = " + df.format(totalAmount) + " where ny = ? and yjbm = ? and kh = ?"; + + boolean isSuccess = rs.executeUpdate(updateSQL, yearMonth, superiorDepartment, customer); + + bean.writeLog("updateSQL:[" + updateSQL + "],执行结果:[" + isSuccess + "]"); + } +} diff --git a/src/main/java/weaver/yunjinshan/formmode/action/HumanCostExpandAction.java b/src/main/java/weaver/yunjinshan/formmode/action/HumanCostExpandAction.java new file mode 100644 index 0000000..56565eb --- /dev/null +++ b/src/main/java/weaver/yunjinshan/formmode/action/HumanCostExpandAction.java @@ -0,0 +1,122 @@ +package weaver.yunjinshan.formmode.action; + +import java.text.DecimalFormat; +import java.util.HashMap; +import java.util.Map; + +import weaver.conn.RecordSet; +import weaver.formmode.customjavacode.AbstractModeExpandJavaCodeNew; +import weaver.general.BaseBean; +import weaver.general.Util; +import weaver.soa.workflow.request.MainTableInfo; +import weaver.soa.workflow.request.Property; +import weaver.soa.workflow.request.RequestInfo; + + +/** + * 云锦山 + * 人力成本建模 新建、编辑保存和导入数据时,自定义扩展操作 + */ +public class HumanCostExpandAction extends AbstractModeExpandJavaCodeNew { + + private final DecimalFormat df = new DecimalFormat("##############################0.0000"); + + /** + * 执行模块扩展动作 + * @param param + * param包含(但不限于)以下数据 + * user 当前用户 + * importtype 导入方式(仅在批量导入的接口动作会传输) 1 追加,2覆盖,3更新,获取方式(int)param.get("importtype") + * 导入链接中拼接的特殊参数(仅在批量导入的接口动作会传输),比如a=1,可通过param.get("a")获取参数值 + * 页面链接拼接的参数,比如b=2,可以通过param.get("b")来获取参数 + * @return + */ + public Map doModeExpand(Map param) { + Map result = new HashMap(); + try { + BaseBean bean = new BaseBean(); + + bean.writeLog("-------------HumanCostExpandAction Begin----------------"); + + bean.writeLog("param:[" + param.toString() + "]"); + + int billid = -1;//数据id + int modeid = -1;//模块id + RequestInfo requestInfo = (RequestInfo)param.get("RequestInfo"); + if(requestInfo!=null){ + billid = Util.getIntValue(requestInfo.getRequestid()); + modeid = Util.getIntValue(requestInfo.getWorkflowid()); + + bean.writeLog("billid:[" + billid + "],modeid:[" + modeid + "]"); + if(billid>0&&modeid>0){ + //年月 + String yearMonth = ""; + //一级部门 + String superiorDepartment = ""; + //客户 + String customer = ""; + + MainTableInfo mainTableInfo = requestInfo.getMainTableInfo(); + + for(Property p : mainTableInfo.getProperty()){ + if("ny".equalsIgnoreCase(p.getName())) { + yearMonth = p.getValue(); + } + + if("yjbm".equalsIgnoreCase(p.getName())){ + superiorDepartment = p.getValue(); + } + if("kh".equalsIgnoreCase(p.getName())){ + customer = p.getValue(); + } + } + + /* + //查询该记录对应的信息 + String selectData = "select * from uf_renlichengben where id = ?"; + + if(rs.executeQuery(selectData,billid)){ + if(rs.next()){ + yearMonth = Util.null2String(rs.getString("ny")); + superiorDepartment = Util.null2String(rs.getString("yjbm")); + customer = Util.null2String(rs.getString("kh")); + } + } + + + bean.writeLog("yearMonth:[" + yearMonth + "],superiorDepartment:[" + superiorDepartment + "],customer:[" + customer + "]"); + + RecordSet rs = new RecordSet(); + + double totalAmount = 0.0; + String selectData = "select sum(isnull(gszzffy,0.0)) from uf_renlichengben where ny = ? and yjbm = ? and kh = ?"; + + if(rs.executeQuery(selectData,yearMonth,superiorDepartment,customer)){ + if(rs.next()){ + totalAmount = Util.getDoubleValue(rs.getString(1),0.0); + } + } + + String updateSQL = "update uf_chengbenshouru set rycb = " + df.format(totalAmount) + " where ny = ? and yjbm = ? and kh = ?"; + + boolean isSuccess = rs.executeUpdate(updateSQL,yearMonth,superiorDepartment,customer); + + bean.writeLog("updateSQL:[" + updateSQL + "],执行结果:[" + isSuccess + "]"); + */ + + CostIncomeUpdate incomeUpdate = new CostIncomeUpdate(); + incomeUpdate.updateByHumanCost(yearMonth,superiorDepartment,customer); + } + } + + result.put("flag", "true"); + + bean.writeLog("-------------HumanCostExpandAction End----------------"); + } catch (Exception e) { + result.put("errmsg","自定义出错信息"); + result.put("flag", "false"); + } + return result; + } + +} \ No newline at end of file diff --git a/src/main/resources/WEB-INF/prop/prop2map/JituMultilingual.properties b/src/main/resources/WEB-INF/prop/prop2map/JituMultilingual.properties index 4d44973..e90c747 100644 --- a/src/main/resources/WEB-INF/prop/prop2map/JituMultilingual.properties +++ b/src/main/resources/WEB-INF/prop/prop2map/JituMultilingual.properties @@ -1,7 +1,7 @@ #修改当前配置文件后需要重启, you must restart service at change the config file after # # 当前需要同步的语言, current active language -cus.multilingual.active=ZHS,IDN +cus.multilingual.active="ZHS,IDN" #中文 cus.multilingual.ZHS=7 #印尼 diff --git a/src/main/resources/WEB-INF/prop/prop2map/PcnYunZhaoSsoRsaKey.properties b/src/main/resources/WEB-INF/prop/prop2map/PcnYunZhaoSsoRsaKey.properties index d693e16..74e15cb 100644 --- a/src/main/resources/WEB-INF/prop/prop2map/PcnYunZhaoSsoRsaKey.properties +++ b/src/main/resources/WEB-INF/prop/prop2map/PcnYunZhaoSsoRsaKey.properties @@ -1 +1 @@ -yunzhao.environment=test \ No newline at end of file +yunzhao.environment=pro \ No newline at end of file diff --git a/src/main/resources/WEB-INF/prop/prop2map/esteeLauderExcelExport.properties b/src/main/resources/WEB-INF/prop/prop2map/esteeLauderExcelExport.properties index 05ab7ad..2b972cf 100644 --- a/src/main/resources/WEB-INF/prop/prop2map/esteeLauderExcelExport.properties +++ b/src/main/resources/WEB-INF/prop/prop2map/esteeLauderExcelExport.properties @@ -18,6 +18,8 @@ export.createType=yyyy-MM-dd export.costCenter=cbzxyh # 条件key export.conditionKey=condition +#附加信息 +export.additional=ddsm #流水号-requestId export.requestId=lcid # bgm字段 @@ -41,72 +43,114 @@ export.sku=sku #导出表头设置 export.head.title[0]=序号 export.head.field[0]=no -export.head.title[1]=分组编号 -export.head.field[1]=groupId -export.head.title[2]=ID -export.head.field[2]=id -export.head.title[3]=条件 -export.head.field[3]=condition -export.head.title[4]=疑似拆单 -export.head.field[4]=openBill -export.head.title[5]=流水号 -export.head.field[5]=lcid -export.head.title[6]=shipTo -export.head.field[6]=shipto -export.head.title[7]=推送时间 -export.head.field[7]=insertTime -export.head.title[8]=审批开始时间 -export.head.field[8]=createdate -export.head.title[9]=申请提交时间 -export.head.field[9]=sqtjrq -export.head.title[10]=审批开始时间 -export.head.field[10]=LASTOPERATEDATE -export.head.title[11]=收方限制 -export.head.field[11]=ddlxms -export.head.title[12]=部门团队 -export.head.field[12]=SPART -export.head.title[13]=品牌部门 -export.head.field[13]=yjpp -export.head.title[14]=订单编号 -export.head.field[14]=ddbh -export.head.title[15]=订单说明 -export.head.field[15]=ddsm -export.head.title[16]=备注 -export.head.field[16]=bz -export.head.title[17]=成本中心-sap -export.head.field[17]=KOSTL -export.head.title[18]=成本中心-用户 -export.head.field[18]=cbzxyh -export.head.title[19]=财务科目 -export.head.field[19]=cwkm -export.head.title[20]=审批开始时间 -export.head.field[20]=LASTOPERATEDATE -export.head.title[21]=活动编号 -export.head.field[21]=hdbh -export.head.title[22]=businessKey -export.head.field[22]=businesskey -export.head.title[23]=申请人 -export.head.field[23]=SQRRLZY -export.head.title[24]=订单类型 -export.head.field[24]=AUART -export.head.title[25]=订单用途 -export.head.field[25]=VKAUS -export.head.title[26]=收货人 -export.head.field[26]=KUNNRSHIPTO -export.head.title[27]=收货人地址 -export.head.field[27]=shdz -export.head.title[28]=收货编号 -export.head.field[28]=hwbh -export.head.title[29]=收货类型 -export.head.field[29]=fl -export.head.title[30]=收货中文名 -export.head.field[30]=ZWMS -export.head.title[31]=数量 -export.head.field[31]=SL -export.head.title[32]=零售总额 -export.head.field[32]=kxpmxzlsj -export.head.title[33]=订单分类 -export.head.field[33]=ddlx -export.head.title[34]=gbm -export.head.field[34]=bgm +#export.head.title[1]=分组编号 +#export.head.field[1]=groupId +#export.head.title[2]=ID +#export.head.field[2]=id +export.head.title[1]=条件 +export.head.field[1]=condition +#export.head.title[4]=疑似拆单 +export.head.title[2]=拆单方式 +export.head.field[2]=openBill +export.head.title[3]=月份 +export.head.field[3]=sqtjrq +export.head.title[4]=SKU +export.head.field[4]=ZWMS +export.head.title[5]=部门 +export.head.field[5]=SPART +export.head.title[6]=订单编号 +export.head.field[6]=ddbh +export.head.title[7]=备注信息 +export.head.field[7]=bz +export.head.title[8]=附加信息 +export.head.field[8]=ddsm +export.head.title[9]=成本中心 +export.head.field[9]=KOSTL +export.head.title[10]=活动编号 +export.head.field[10]=hdbh +export.head.title[11]=流水号 +export.head.field[11]=lcid +export.head.title[12]=用户 +export.head.field[12]=cbzxyh +export.head.title[13]=订单类型 +export.head.field[13]=AUART +export.head.title[14]=订单用途 +export.head.field[14]=ddyt +export.head.title[15]=shipTo +export.head.field[15]=shipto +export.head.title[16]=办公室员工 +export.head.field[16]=KUNNRSHIPTO +export.head.title[17]=提交时间 +export.head.field[17]=LASTOPERATEDATE +export.head.title[18]=总数 +export.head.field[18]=SL +export.head.title[19]=成本总额 +export.head.field[19]=kxpmxzlsj +export.head.title[20]=总税额 +export.head.field[20]= +export.head.title[21]=总价格 +export.head.field[21]= +export.head.title[22]=订单时间 +export.head.field[22]=LASTOPERATEDATE +export.head.title[23]=到货方 +export.head.field[23]= +#export.head.title[5]=流水号 +#export.head.field[5]=lcid +#export.head.title[6]=shipTo +#export.head.field[6]=shipto +#export.head.title[7]=推送时间 +#export.head.field[7]=insertTime +#export.head.title[8]=审批开始时间 +#export.head.field[8]=createdate +#export.head.title[9]=申请提交时间 +#export.head.field[9]=sqtjrq +#export.head.title[10]=审批开始时间 +#export.head.field[10]=LASTOPERATEDATE +#export.head.title[11]=收方限制 +#export.head.field[11]=ddlxms +#export.head.title[12]=部门团队 +#export.head.field[12]=SPART +#export.head.title[13]=品牌部门 +#export.head.field[13]=yjpp +#export.head.title[14]=订单编号 +#export.head.field[14]=ddbh +#export.head.title[15]=订单说明 +#export.head.field[15]=ddsm +#export.head.title[16]=备注 +#export.head.field[16]=bz +#export.head.title[17]=成本中心-sap +#export.head.field[17]=KOSTL +#export.head.title[18]=成本中心-用户 +#export.head.field[18]=cbzxyh +#export.head.title[19]=财务科目 +#export.head.field[19]=cwkm +#export.head.title[20]=审批开始时间 +#export.head.field[20]=LASTOPERATEDATE +#export.head.title[21]=活动编号 +#export.head.field[21]=hdbh +#export.head.title[22]=businessKey +#export.head.field[22]=businesskey +#export.head.title[23]=申请人 +#export.head.field[23]=SQRRLZY +#export.head.title[24]=订单类型 +#export.head.field[24]=AUART +#export.head.title[25]=订单用途 +#export.head.field[25]=VKAUS +#export.head.title[26]=收货人 +#export.head.field[26]=KUNNRSHIPTO +#export.head.title[27]=收货人地址 +#export.head.field[27]=shdz +#export.head.title[28]=收货编号 +#export.head.field[28]=hwbh +#export.head.title[29]=收货类型 +#export.head.field[29]=fl +#export.head.title[30]=收货中文名 +#export.head.field[30]=ZWMS +#export.head.title[31]=数量 +#export.head.field[31]=SL +#export.head.title[32]=零售总额 +#export.head.field[32]=kxpmxzlsj +#export.head.title[33]=订单分类 +##xport.head.title[34]=gbm +#export.head.field[34]=bgm diff --git a/src/main/resources/cus_getlog/css/index.css b/src/main/resources/cus_getlog/css/index.css new file mode 100755 index 0000000..676061b --- /dev/null +++ b/src/main/resources/cus_getlog/css/index.css @@ -0,0 +1,91 @@ +body{ + background-color: rgb(241, 241, 241); + font-family: PingFangSC-Regular; + color: #333333 ; + } + .box{ + width: 1000px; + margin:0 auto; + margin-top: 100px; + background-color: #ffffff; + font-size: 14px; + + } + .mytitle{ + width: 100%; + background-color: #F6F6F6 ; + height: 40px; + font-size: 14px; + background: #F6F6F6; + border: 1px solid #E2E2E2; + + } + .clusterIp{ + display: inline-block; + width: 120px; + + } + input[type='checkbox']{ + } + + .cluster{ + border-bottom: 1px solid #E2E2E2; + width: 80%; + margin-left: 39px; + height: 100px; + padding-top: 26px; + } + .Button{ + color: #fff; + background-color: #2DB7F5; + border-color: #4cae4c; + + display: inline-block; + margin-bottom: 0; + font-size: 14px; + font-weight: 300; + line-height: 1.42857143; + text-align: center; + white-space: nowrap; + vertical-align: middle; + -ms-touch-action: manipulation; + touch-action: manipulation; + cursor: pointer; + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; + background-image: none; + border: 1px solid transparent; + width:70px; + height:30px; + border-radius: 3px; + } + + .Wdate{ + width: 150px; + height: 30px !important; + padding-left: 5px; + padding-right: 5px; + } + + .clusterPlan{ + margin-top: 20px; + margin-left:30px; + font-size: 12px; + } + + .contend{ + background: #FFFFFF; + border-left: 1px solid #E2E2E2; + border-right: 1px solid #E2E2E2; + border-bottom: 1px solid #E2E2E2; + width: 100%; + } + .messages{ + color:red; + } + + #start[disabled]{ + background-color: #A9A9A9; + } diff --git a/src/main/resources/cus_getlog/downlog.jsp b/src/main/resources/cus_getlog/downlog.jsp new file mode 100755 index 0000000..aa682b8 --- /dev/null +++ b/src/main/resources/cus_getlog/downlog.jsp @@ -0,0 +1,138 @@ +<%@ page language="java" %> +<%@ page import="org.apache.commons.httpclient.HttpClient" %> +<%@ page import="org.apache.commons.httpclient.methods.GetMethod" %> +<%@ page import="javax.servlet.http.HttpServletRequest" %> +<%@ page import="javax.servlet.http.HttpServletResponse" %> +<%@ page import="java.io.File" %> +<%@ page import="java.io.FileInputStream" %> +<%@ page import="java.io.InputStream" %> +<%@ page import="java.io.OutputStream" %> +<%@ page import="java.util.regex.Matcher" %> +<%@ page import="java.util.regex.Pattern" %> +<% + + String logName = request.getParameter("logName"); + String otherIp = request.getParameter("otherIp"); + + weaver.hrm.User user = (weaver.hrm.User) request.getSession(true).getAttribute("weaver_user@bean"); + String ip = getIpAddress(request); + if (user == null || !"sysadmin".equals(user.getLoginid())) { + return; + } + + if (otherIp != null) { + otherIp = otherIp.replace("-", ":"); + downotherlog(logName, otherIp, response); + } else { + deal(request, response); + } +%><%! + public static boolean innerIP(String ip) { + String pattern = "((192\\.168|172\\.([1][6-9]|[2]\\d|3[01]))" + + "(\\.([2][0-4]\\d|[2][5][0-5]|[01]?\\d?\\d)){2}|" + + "^(\\D)*10(\\.([2][0-4]\\d|[2][5][0-5]|[01]?\\d?\\d)){3})"; + Pattern reg = Pattern.compile(pattern); + Matcher match = reg.matcher(ip); + return match.find() || ip.equals("127.0.0.1"); + + } + + public String getIpAddress(HttpServletRequest request) { + String ip = request.getHeader("x-forwarded-for"); + if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { + ip = request.getHeader("Proxy-Client-IP"); + } + if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { + ip = request.getHeader("WL-Proxy-Client-IP"); + } + if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { + ip = request.getRemoteAddr(); + } + if (ip.contains(",")) { + return ip.split(",")[0]; + } else { + return ip; + } + } + + private void deal(HttpServletRequest request, HttpServletResponse response) { + response.reset(); + String logName = request.getParameter("logName"); + if (!logName.endsWith(".zip") || logName.indexOf("/") != -1 || logName.indexOf("\\") != -1 || logName.indexOf("..") != -1) { + + return; + } + FileInputStream in = null; + OutputStream outs = null; + try { + response.setContentType("application/octet-stream"); + response.setHeader("content-disposition", "attachment;filename=" + logName); + response.setCharacterEncoding("ISO8859-1"); + String ecologyPathtmp = request.getRealPath("/"); + if (!ecologyPathtmp.endsWith(File.separator)) { + ecologyPathtmp = ecologyPathtmp + File.separator; + } + if (logName.indexOf("..") != -1 || logName.indexOf("\0") != -1) { + return; + } + in = new FileInputStream(ecologyPathtmp + "cus_getlog" + File.separator + "log" + File.separator + logName); + outs = response.getOutputStream(); + outs.flush(); + byte[] buffer = new byte[1024]; + int len = 0; + while ((len = in.read(buffer)) > 0) { + outs.write(buffer, 0, len); + } + } catch (Exception e) { + e.printStackTrace(); + } finally { + try { + if (in != null) { + in.close(); + } + if (outs != null) { + outs.flush(); + outs.close(); + } + } catch (Exception e) { + } + } + } + + private void downotherlog(String logName, String otherIp, HttpServletResponse response) { + response.reset(); + + InputStream in = null; + OutputStream outs = null; + try { + response.setContentType("application/octet-stream"); + response.setHeader("content-disposition", "attachment;filename=" + logName); + response.setCharacterEncoding("ISO8859-1"); + HttpClient client = new HttpClient(); + GetMethod httpget = new GetMethod("http://" + otherIp + "/cus_getlog/downlog.jsp?logName=" + logName); + client.executeMethod(httpget); + in = httpget.getResponseBodyAsStream(); + outs = response.getOutputStream(); + outs.flush(); + byte[] buffer = new byte[1024]; + int len = 0; + while ((len = in.read(buffer)) > 0) { + outs.write(buffer, 0, len); + } + } catch (Exception e) { + e.printStackTrace(); + } finally { + try { + if (in != null) { + in.close(); + } + if (outs != null) { + outs.flush(); + outs.close(); + } + } catch (Exception e) { + } + } + } + +%> \ No newline at end of file diff --git a/src/main/resources/cus_getlog/getlog.jsp b/src/main/resources/cus_getlog/getlog.jsp new file mode 100755 index 0000000..c4a1be6 --- /dev/null +++ b/src/main/resources/cus_getlog/getlog.jsp @@ -0,0 +1,481 @@ +<%@ page language="java" contentType="text/html; charset=utf-8" %> +<%@ page import="java.io.*" %> +<%@ page import="java.math.BigDecimal" %> +<%@ page import="java.math.RoundingMode" %> +<%@ page import="java.net.InetAddress" %> +<%@ page import="java.net.NetworkInterface" %> +<%@ page import="java.text.SimpleDateFormat" %> +<%@ page import="java.util.*" %> +<%@ page import="java.util.regex.Matcher" %> +<%@ page import="java.util.regex.Pattern" %> +<%@ page import="java.util.zip.ZipEntry" %> +<%@ page import="java.util.zip.ZipOutputStream" %> + +<% + + weaver.hrm.User user = (weaver.hrm.User) request.getSession(true).getAttribute("weaver_user@bean"); + String ip = getIpAddress(request); + if (user == null || !"sysadmin".equals(user.getLoginid())) { + return; + } + + + String startStr = request.getParameter("startDate"); + String endStr = request.getParameter("endDate"); + String logTypeStr = request.getParameter("loytype"); + messageStr = new StringBuilder(); + + + String ecologyPathtmp = request.getRealPath("/"); + if (!ecologyPathtmp.endsWith(File.separator)) { + ecologyPathtmp = ecologyPathtmp + File.separator; + } + final String ecologyPath = ecologyPathtmp; + final String ResinPath = System.getProperty("user.dir") + File.separator; + //out.println(ResinPath+"
"); + String outPath = ecologyPath + File.separator + "getlog" + File.separator + "log"; // 日志输出目录 + List dates = getDateList(startStr, endStr); + File outFile = null; + try { + outFile = new File(outPath); + if (!outFile.exists()) { + outFile.mkdirs(); + } + } catch (Exception e) { + e.printStackTrace(); + } + String outLogPath = outFile + File.separator + getInnerIp() + "downLog.zip"; + Map logtype = new HashMap() { // 日志类型路径 + { + put("thread", ecologyPath + "log" + File.separator + "thread"); + put("mem", ecologyPath + "log" + File.separator + "mem"); + put("ecology", ecologyPath + "log"); + put("sql", ecologyPath + "log" + File.separator + "sql"); + + put("sqllog", ecologyPath + "sqllog"); + + put("security", ecologyPath + "WEB-INF" + File.separator + "securitylog"); + put("Resin", ResinPath + "log"); + put("integration", ecologyPath + "log" + File.separator + "integration"); + + put("monitorevent", ResinPath + "monitor" + File.separator + "resin" + File.separator + "app" + File.separator + "data" + File.separator + "event"); //运维平台的事件日志 + put("monitorPool", ResinPath + "monitor" + File.separator + "resin" + File.separator + "app" + File.separator + "data" + File.separator + "pool"); + put("monitorcpu", ResinPath + "monitor" + File.separator + "resin" + File.separator + "app" + File.separator + "data" + File.separator + "cpu"); + put("resinconf", ResinPath + "conf" + File.separator + "resin.conf"); + put("ecoloyweaver", ecologyPath + "WEB-INF" + File.separator + "prop" + File.separator); + put("monitorlog", ResinPath + "monitor" + File.separator + "resin" + File.separator + "log"); + put("monitorconcurrent", ResinPath + "monitor" + File.separator + "resin" + File.separator + "app" + File.separator + "data" + File.separator + "concurrent"); + + put("cus", ecologyPath + "log" + File.separator + "cus"); + put("util_cus", ecologyPath + "log" + File.separator + "cus" + File.separator + "util_cus"); + put("sql_log", ecologyPath + "log" + File.separator + "cus" + File.separator + "sql_log"); + put("http_util", ecologyPath + "log" + File.separator + "cus" + File.separator + "http_util"); + + } + }; + + + Map logMap = getLogType(logTypeStr, logtype); + Set keys = logMap.keySet(); + FileOutputStream fos = null; + try { + fos = new FileOutputStream(outLogPath); + ZipOutputStream zos = new ZipOutputStream(fos); + zos.setLevel(1); + Iterator it = keys.iterator(); + + while (it.hasNext()) { + String key = (String) it.next(); + for (int i = 0; i < dates.size(); i++) { + String date = (String) dates.get(i); + boolean isToDay = isToDay(date); + List fileNames = transition(key, (String) logtype.get(key), date, isToDay); + for (int j = 0; j < fileNames.size(); j++) { + String fileName = (String) fileNames.get(j); + //out.println(fileName+"
"); + String basePath = date + File.separator; + if ("sqllog".equals(key)) { + basePath += ("sqllog" + File.separator); + } + if ("monitorevent".equals(key)) { + basePath += ("event" + File.separator); + } + if ("monitorlog".equals(key)) { + basePath += ("monitorlog" + File.separator); + } + if (key.equals("cus")) { + basePath += ("cus" + File.separator); + } + if (key.equals("util_cus")) { + basePath += ("util_cus" + File.separator); + } + if (key.equals("sql_log")) { + basePath += ("sql_log" + File.separator); + } + if (key.equals("http_util")) { + basePath += ("http_util" + File.separator); + } + compressbyType(fileName, zos, basePath); + } + } + } + + try { + zos.close(); + } catch (Exception es) { + } + if (fos != null) + fos.close(); + File outLog = new File(outLogPath); + String fileSize = getFileSize(outLog); + out.println(fileSize + "," + messageStr); + } catch (Exception e) { + e.printStackTrace(); + } + long end = System.currentTimeMillis(); + // out.println(end - start); +%> +<%! + + public static boolean innerIP(String ip) { + String pattern = "((192\\.168|172\\.([1][6-9]|[2]\\d|3[01]))" + + "(\\.([2][0-4]\\d|[2][5][0-5]|[01]?\\d?\\d)){2}|" + + "^(\\D)*10(\\.([2][0-4]\\d|[2][5][0-5]|[01]?\\d?\\d)){3})"; + Pattern reg = Pattern.compile(pattern); + Matcher match = reg.matcher(ip); + return match.find() || ip.equals("127.0.0.1"); + } + + public String getIpAddress(HttpServletRequest request) { + String ip = request.getHeader("x-forwarded-for"); + if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { + ip = request.getHeader("Proxy-Client-IP"); + } + if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { + ip = request.getHeader("WL-Proxy-Client-IP"); + } + if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { + ip = request.getRemoteAddr(); + } + if (ip.contains(",")) { + return ip.split(",")[0]; + } else { + return ip; + } + } + + + private StringBuilder messageStr = new StringBuilder(); + + private Map getLogType(String logTypeStr, Map logtype) { + Map resultmap = new HashMap(); + String[] strs = logTypeStr.split(","); + for (int i = 0; i < strs.length; i++) { + String str = strs[i]; + if (str.equals("monitor")) { + resultmap.put("thread", logtype.get("thread")); + resultmap.put("mem", logtype.get("mem")); + resultmap.put("sql", logtype.get("sql")); + resultmap.put("monitorevent", logtype.get("monitorevent")); + resultmap.put("monitorPool", logtype.get("monitorPool")); + resultmap.put("monitorcpu", logtype.get("monitorcpu")); + resultmap.put("resinconf", logtype.get("resinconf")); + resultmap.put("ecoloyweaver", logtype.get("ecoloyweaver")); + resultmap.put("monitorconcurrent", logtype.get("monitorconcurrent")); + resultmap.put("monitorlog", logtype.get("monitorlog")); + } + if (str.equals("Resin")) { + resultmap.put("Resin", logtype.get("Resin")); + } + if (str.equals("security")) { + resultmap.put("security", logtype.get("security")); + } + if (str.equals("ecology")) { + resultmap.put("ecology", logtype.get("ecology")); + } + if (str.equals("sql")) { + resultmap.put("sql", logtype.get("sql")); + } + if (str.equals("integration")) { + resultmap.put("integration", logtype.get("integration")); + } + if (str.equals("cus")) { + resultmap.put("cus", logtype.get("cus")); + } + if (str.equals("util_cus")) { + resultmap.put("util_cus", logtype.get("util_cus")); + } + if (str.equals("sql_log")) { + resultmap.put("sql_log", logtype.get("sql_log")); + } + if (str.equals("http_util")) { + resultmap.put("http_util", logtype.get("http_util")); + } + } + return resultmap; + } + + private List getDateList(String startDate, String endDate) { + ArrayList list = new ArrayList(); + try { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + Date start = sdf.parse(startDate); + Date end = sdf.parse(endDate); + Calendar tempStart = Calendar.getInstance(); + tempStart.setTime(start); + while (start.getTime() <= end.getTime()) { + list.add(sdf.format(tempStart.getTime())); + tempStart.add(Calendar.DAY_OF_YEAR, 1); + start = tempStart.getTime(); + } + } catch (Exception e) { + e.printStackTrace(); + } + return list; + } + + private boolean isToDay(String date) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + String toDay = sdf.format(new Date()); + return date.equals(toDay); + } + + public List transition(String key, String path, String date, boolean isToDay) {//转换真实的日志文件 + List list = new ArrayList(); + if ("thread".equals(key)) { + list.add(path + File.separator + date); + } else if ("mem".equals(key)) { + list.add(path + File.separator + "memory_" + date + ".log"); + } else if ("ecology".equals(key)) { + if (isToDay) { + list.add(path + File.separator + "ecology"); + } else { + list.add(path + File.separator + "ecology_" + getDateStr(date) + ".log"); + } + } else if ("sql".equals(key)) { + list.add(path + File.separator + "sqlcount_" + date + ".log"); + list.add(path + File.separator + "sqltime_" + date + ".log"); + } else if ("integration".equals(key)) { + if (isToDay) { + list.add(path + File.separator + "integration.log"); + } else { + list.add(path + File.separator + "integration.log_" + getDateStr(date) + ".log"); + } + } else if ("security".equals(key)) { + list.add(path + File.separator + "systemRunInfo" + date + ".log"); + list.add(path + File.separator + "systemSecurity" + date + ".log"); + } else if ("Resin".equals(key)) { + if (isToDay) { + list.add(path + File.separator + "stdout.log"); + list.add(path + File.separator + "stderr.log"); + } else { + list.add(path + File.separator + "stdout-" + getDateStr(date) + ".log.gz"); + list.add(path + File.separator + "stderr-" + getDateStr(date) + ".log.gz"); + } + list.add(path + File.separator + "watchdog-manager.log"); + list.add(path + File.separator + "jvm-default.log"); + } else if ("sqllog".equals(key)) { + list.add(path + File.separator + getSqlPathByDate(date)); + list.add(path + File.separator); + } else if ("monitorevent".equals(key)) { + list.addAll(eventLog(path, date)); + } else if ("monitorPool".equals(key)) { + list.add(path + File.separator + "pool_" + getDateStr(date) + "_ecology.log"); + list.add(path + File.separator + "pool_" + getDateStr(date) + "_ecology.zip"); + } else if ("monitorlog".equals(key)) { + if (isToDay) { + list.add(path + File.separator + "stdout.log"); + list.add(path + File.separator + "stderr-log"); + } else { + list.add(path + File.separator + "stdout-" + getDateStr(date) + ".log.gz"); + list.add(path + File.separator + "stderr-" + getDateStr(date) + ".log.gz"); + } + } else if ("monitorconcurrent".equals(key)) { + list.add(path + File.separator + "concurrent_" + getDateStr(date) + ".log"); + list.add(path + File.separator + "concurrent_" + getDateStr(date) + ".zip"); + } else if ("monitorcpu".equals(key)) { + list.add(path + File.separator + "cpu_" + getDateStr(date) + ".log"); + list.add(path + File.separator + "cpu_" + getDateStr(date) + ".zip"); + } else if ("resinconf".equals(key)) { + list.add(path); + } else if ("ecoloyweaver".equals(key)) { + dealWidthWeaverProp(path + "weaver.properties", new File(path + "weaversecurity.properties")); + list.add(path + "weaversecurity.properties"); + } else if ("cus".equals(key) || "util_cus".equals(key) || "sql_log".equals(key) || "http_util".equals(key)) { + if (isToDay) { + list.add(path + File.separator + "cus.log"); + } else { + list.add(path + File.separator + "cus.log_" + getDateStr(date) + ".log"); + } + } + return list; + } + + private void dealWidthWeaverProp(String path, File outFile) {//处理weaver.prop密码问题 + File file = new File(path); + if (!file.exists()) { + return; + } + InputStreamReader reader = null; + java.io.Writer outWriter = null; + try { + if (!file.exists()) { + file.createNewFile(); + } + Properties registerProp = new Properties(); + reader = new InputStreamReader(new FileInputStream(file)); + registerProp.load(reader); + reader.close(); + outWriter = new FileWriter(outFile); + registerProp.put("ecology.password", "***********"); + registerProp.store(outWriter, ""); + outWriter.close(); + } catch (Exception e) { + e.printStackTrace(); + } finally { + try { + if (reader != null) { + reader.close(); + } + if (outWriter != null) { + outWriter.close(); + } + } catch (Exception e) { + } + } + } + + + private List eventLog(String path, String date) { + List list = new ArrayList(); + File file = new File(path); + if (!file.exists()) { + return list; + } + File[] filelists = new File(path).listFiles(); + date = getDateStr(date); + for (int i = 0; i < filelists.length; i++) { + File filelist = filelists[i]; + if (filelist.getName().indexOf(date) != -1) { + list.add(filelist.getAbsolutePath()); + } + } + return list; + } + + private String getSqlPathByDate(String date) { + return date.replace("-", File.separator); + } + + public String getFileSize(File file) { + if (!file.exists()) { + return "0KB"; + } + long length = file.length(); + + BigDecimal b1 = new BigDecimal(Double.toString(length)); + BigDecimal b2 = new BigDecimal(Double.toString(1024)); + BigDecimal b3 = b1.divide(b2, 2, RoundingMode.HALF_UP); + b3.floatValue(); + if (b3.floatValue() > 1024) { + return b3.divide(b2, 2, RoundingMode.HALF_UP).floatValue() + "M"; + } else { + return b3.floatValue() + "KB"; + } + } + + private String getInnerIp() { + try { + Enumeration netInterfaces = NetworkInterface.getNetworkInterfaces(); + while (netInterfaces.hasMoreElements()) { + NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement(); + Enumeration nii = ni.getInetAddresses(); + while (nii.hasMoreElements()) { + InetAddress inetAddress = (InetAddress) nii.nextElement(); + if (inetAddress.getHostAddress().indexOf(":") == -1) { + String ip = inetAddress.getHostAddress(); + if (ip.startsWith("10.") || ip.startsWith("192.168.")) {// || + return ip; + } else { + if (ip.startsWith("172.")) { + + return ip; + + } + } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + return "127.0.0.1"; + } + + private String getDateStr(String date) { + date = date.replaceAll("-", ""); + return date; + } + + /** + * 按照原路径的类型就行压缩。文件路径直接把文件压缩 + * @param src + * @param zos + * @param baseDir + */ + private void compressbyType(String src, ZipOutputStream zos, String baseDir) { + File srcFile = new File(src); + if (!srcFile.exists()) { + return; + } + //判断文件是否是文件,如果是文件调用compressFile方法,如果是路径,则调用compressDir方法; + if (srcFile.isFile()) { + //src是文件,调用此方法 + compressFile(srcFile, zos, baseDir); + } else if (srcFile.isDirectory()) { + compressDir(srcFile, zos, baseDir); + } + } + + /** + * 压缩文件,取后面的80M内容 + */ + private void compressFile(File file, ZipOutputStream zos, String baseDir) { + if (!file.exists()) + return; + try { + RandomAccessFile fileRead = new RandomAccessFile(file, "r"); //用读模式 + long fileLength = fileRead.length();//获得文件长度 + if (file.getName().endsWith(".log") && fileLength > 1073741820) {//如果文件超过80M,则只取文件倒数80M内容 + messageStr.append("、").append(file.getName()); + fileRead.seek(fileLength - 1073741820); + } else { + fileRead.seek(0); + } + ZipEntry entry = new ZipEntry(baseDir + file.getName()); + zos.putNextEntry(entry); + int hasRead; + byte[] buf = new byte[1024]; + while ((hasRead = fileRead.read(buf)) != -1) { + zos.write(buf, 0, hasRead); + } + fileRead.close(); + } catch (Exception e) { + + } + } + + /** + * 压缩文件夹 + */ + private void compressDir(File dir, ZipOutputStream zos, String baseDir) { + if (!dir.exists()) + return; + File[] files = dir.listFiles(); + for (int i = 0; i < files.length; i++) { + File file = files[i]; + compressFile(file, zos, baseDir + dir.getName() + File.separator); + } + } + +%> \ No newline at end of file diff --git a/src/main/resources/cus_getlog/img/loading.gif b/src/main/resources/cus_getlog/img/loading.gif new file mode 100755 index 0000000..5bb90fd Binary files /dev/null and b/src/main/resources/cus_getlog/img/loading.gif differ diff --git a/src/main/resources/cus_getlog/index.jsp b/src/main/resources/cus_getlog/index.jsp new file mode 100755 index 0000000..175d1bf --- /dev/null +++ b/src/main/resources/cus_getlog/index.jsp @@ -0,0 +1,469 @@ +<%@ page language="java" contentType="text/html; charset=utf-8" %> +<%@ page import="org.apache.commons.io.IOUtils" %> +<%@ page import="java.io.*" %> +<%@ page import="java.net.InetAddress" %> +<%@ page import="java.net.NetworkInterface" %> +<%@ page import="java.util.Enumeration" %> +<%@ page import="java.util.HashSet" %> +<%@ page import="java.util.Properties" %> +<%@ page import="java.util.Set" %> +<% + + final String ecologyPath = request.getRealPath("/"); + weaver.hrm.User user = (weaver.hrm.User) request.getSession(true).getAttribute("weaver_user@bean"); + if (user == null || !"sysadmin".equals(user.getLoginid())) { + response.sendRedirect("/"); + return; + } + final String ResinPath = System.getProperty("user.dir") + File.separator; + boolean isResin = ResinPath.toLowerCase().indexOf("resin") != -1; + String ecologyWeaverPath = ""; + if (ecologyPath.endsWith(File.separator)) { + ecologyWeaverPath = ecologyPath + "WEB-INF" + File.separator + "prop" + File.separator + "weaver.properties"; + } else { + ecologyWeaverPath = ecologyPath + File.separator + "WEB-INF" + File.separator + "prop" + File.separator + "weaver.properties"; + } + + File ecolpogyProp = new File(ecologyWeaverPath); + File resinProp = new File(ResinPath + "bin" + File.separator + "startresin.sh"); + + Set ipList = readEcologyProp(ecolpogyProp); + String localIp = getInnerIp(); + if (ipList.size() == 0) { + ipList.addAll(readResinProp(resinProp)); + } + boolean isCluster = true; + if (ipList.size() == 0) {//没有集群的时候 + //ipList.add(localIp); + isCluster = false; + } else { + boolean status = false; + java.util.Iterator it = ipList.iterator(); + while (it.hasNext()) { + String ip = (String) it.next(); + if (ip.indexOf(localIp) != -1 || "127.0.0.1".equals(ip) || "127.0.0.1".equals(localIp)) { + status = true; + } + } + if (!status) { + ipList.add(localIp); + } + } + + +%> + +<%! + /** + * 当前机器内网ip + * + * @return + */ + private String getInnerIp() { + try { + Enumeration netInterfaces = NetworkInterface.getNetworkInterfaces(); + while (netInterfaces.hasMoreElements()) { + NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement(); + Enumeration nii = ni.getInetAddresses(); + while (nii.hasMoreElements()) { + InetAddress inetAddress = (InetAddress) nii.nextElement(); + if (inetAddress.getHostAddress().indexOf(":") == -1) { + String ip = inetAddress.getHostAddress(); + if (ip.startsWith("10.") || ip.startsWith("192.168.")) {// || + return ip; + } else { + if (ip.startsWith("172.")) { + return ip; + } + } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + return "127.0.0.1"; + } + + private Set readResinProp(File startResinFile) { + Set liststr = new HashSet(); + if (!startResinFile.exists()) { + return liststr; + } + if (startResinFile.isFile() && startResinFile.length() > 0) { + FileInputStream fileInput = null; + BufferedReader bufferedReader = null; + try { + fileInput = new FileInputStream(startResinFile); + bufferedReader = new BufferedReader(new InputStreamReader(fileInput)); + String str = null; + while ((str = bufferedReader.readLine()) != null) { + if (str.indexOf("-Dinitial_hosts") != -1 || str.indexOf("-J-Dinitial_hosts") != -1) { + if (str.indexOf("-J-Dinitial_hosts") != -1) { + str = str.substring(str.indexOf("-J-Dinitial_hosts") + 17); + } + if (str.indexOf("-Dinitial_hosts") != -1) { + str = str.substring(str.indexOf("-Dinitial_hosts") + 15); + } + str = str.indexOf("=") != -1 ? str.substring(str.indexOf("=") + 1) : str; + str = str.indexOf("-") != -1 ? str.substring(0, str.indexOf("-")) : str; + str = str.indexOf(" ") != -1 ? str.substring(0, str.indexOf(" ")) : str; + String[] ips = str.split(","); + for (int i = 0; i < ips.length; i++) { + String ip = ips[i]; + try { + String tmpip = ip.replace(".", "").replace(":", ""); + Long.parseLong(tmpip.trim()); + liststr.add(ip.trim()); + } catch (Exception e) { + } + } + } + } + } catch (Throwable t) { + t.printStackTrace(); + } finally { + IOUtils.closeQuietly(fileInput); + IOUtils.closeQuietly(bufferedReader); + } + } + return liststr; + } + + + private Set readEcologyProp(File file) { + Set liststr = new HashSet(); + try { + if (!file.exists()) { + return liststr; + } + Properties registerProp = new Properties(); + InputStreamReader reader = new InputStreamReader(new FileInputStream(file)); + registerProp.load(reader); + String initial_host = registerProp.getProperty("initial_hosts"); + if (initial_host != null && !"".equals(initial_host)) { + String[] initial_hosts = initial_host.split(","); + for (int i = 0; i < initial_hosts.length; i++) { + String initial_hostStr = initial_hosts[i]; + if (!initial_hostStr.isEmpty()) { + liststr.add(initial_hostStr); + } + } + } + IOUtils.closeQuietly(reader); + } catch (IOException e) { + e.printStackTrace(); + } + return liststr; + } +%> + + + + + + + + + + + +
+
+
+ ecology日志下载 +
+
+ +
+ <%if (isCluster) { %> +
+
服务器节点
+
+ <% + java.util.Iterator it = ipList.iterator(); + while (it.hasNext()) { + String ip = (String) it.next(); + %> +
+ +
+ <%}%> +
+
+ <%}%> + + +
+
日志类型
+
+
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ + +
+ +
+ +
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+
+
+ + +
+
时间范围
+
+
+ 开始时间 + + - + 结束时间 + + + +
+
+
+ +
+
下载列表
+
+ <% + java.util.Iterator it = ipList.iterator(); + while (it.hasNext()) { + String ip = (String) it.next(); + ip = ip.replaceAll("\\.", ""); + ip = ip.replaceAll(":", ""); + %> +
+
+
+ <%}%> + + <%if (!isCluster) { %> +
+
+ <%} %> + +
+
+ + +
+ +
+ + \ No newline at end of file diff --git a/src/main/resources/cus_getlog/js/My97DatePicker/WdatePicker.js b/src/main/resources/cus_getlog/js/My97DatePicker/WdatePicker.js new file mode 100755 index 0000000..eef6cdc --- /dev/null +++ b/src/main/resources/cus_getlog/js/My97DatePicker/WdatePicker.js @@ -0,0 +1,56 @@ +/* + * My97 DatePicker 4.8 + * License: http://www.my97.net/dp/license.asp + */ +var $dp,WdatePicker;(function(){var l={ +$langList:[{name:"en",charset:"UTF-8"}, +{name:"zh-cn",charset:"gb2312"}, +{name:"zh-tw",charset:"GBK"}], +$skinList:[{name:"default",charset:"gb2312"}, +{name:"whyGreen",charset:"gb2312"}, +{name:"blue",charset:"gb2312"}, +{name:"green",charset:"gb2312"}, +{name:"simple",charset:"gb2312"}, +{name:"ext",charset:"gb2312"}, +{name:"blueFresh",charset:"gb2312"}, +{name:"twoer",charset:"gb2312"}, +{name:"YcloudRed",charset:"gb2312"}], +$wdate:true, +$crossFrame:false, +$preLoad:false, +$dpPath:"", +doubleCalendar:false, +enableKeyboard:true, +enableInputMask:true, +autoUpdateOnChanged:null, +weekMethod:"MSExcel", +position:{}, +lang:"auto", +skin:"default", +dateFmt:"yyyy-MM-dd", +realDateFmt:"yyyy-MM-dd", +realTimeFmt:"HH:mm:ss", +realFullFmt:"%Date %Time", +minDate:"0001-01-01 00:00:00", +maxDate:"9999-12-31 23:59:59", +minTime:"00:00:00", +maxTime:"23:59:59", +startDate:"", +alwaysUseStartDate:false, +yearOffset:1911, +firstDayOfWeek:0, +isShowWeek:false, +highLineWeekDay:true, +isShowClear:true, +isShowToday:true, +isShowOK:true, +isShowOthers:true, +readOnly:false, +errDealMode:0, +autoPickDate:null, +qsEnabled:true, +autoShowQS:false, +hmsMenuCfg:{H:[1,6],m:[5,6],s:[15,4]}, +opposite:false, + +specialDates:null,specialDays:null,disabledDates:null,disabledDays:null,onpicking:null,onpicked:null,onclearing:null,oncleared:null,ychanging:null,ychanged:null,Mchanging:null,Mchanged:null,dchanging:null,dchanged:null,Hchanging:null,Hchanged:null,mchanging:null,mchanged:null,schanging:null,schanged:null,eCont:null,vel:null,elProp:"",errMsg:"",quickSel:[],has:{},getRealLang:function(){var d=l.$langList;for(var e=0;e0?1:0;var K=new Date(this.dt.y,this.dt.M,0).getDate();this.dt.d=Math.min(K+M,this.dt.d)}}}}if(this.dt.refresh()){return this.dt}}return""},show:function(){var K=E[z].getElementsByTagName("div"),J=100000;for(var e=0;eJ){J=L}}this.dd.style.zIndex=J+2;r(this.dd,"block");r(this.dd.firstChild,"")},unbind:function(e){e=this.$(e);if(e.initcfg){t(e,"onclick",function(){g(e.initcfg)});t(e,"onfocus",function(){g(e.initcfg)})}},hide:function(){r(this.dd,"none")},attachEvent:k};for(var d in w){E.$dp[d]=w[d]}$dp=E.$dp}function k(I,J,w,d){if(I.addEventListener){var e=J.replace(/on/,"");w._ieEmuEventHandler=function(K){return w(K)};I.addEventListener(e,w._ieEmuEventHandler,d)}else{I.attachEvent(J,w)}}function t(w,I,e){if(w.removeEventListener){var d=I.replace(/on/,"");e._ieEmuEventHandler=function(J){return e(J)};w.removeEventListener(d,e._ieEmuEventHandler,false)}else{w.detachEvent(I,e)}}function C(w,e,d){if(typeof w!=typeof e){return false}if(typeof w=="object"){if(!d){for(var I in w){if(typeof e[I]=="undefined"){return false}if(!C(w[I],e[I],true)){return false}}}return true}else{if(typeof w=="function"&&typeof e=="function"){return w.toString()==e.toString()}else{return w==e}}}function q(){var I,w,d=n[z][H]("script");for(var e=0;e0){I=I.substring(0,w+1)}if(I){break}}return I}function m(w,I,J){var d=n[z][H]("HEAD").item(0),e=n[z].createElement("link");if(d){e.href=w;e.rel="stylesheet";e.type="text/css";if(I){e.title=I}if(J){e.charset=J}d.appendChild(e)}}function p(I){I=I||E;var L=0,d=0;while(I!=E){var N=I.parent[z][H]("iframe");for(var J=0;JI.scrollTop||d.scrollLeft>I.scrollLeft))?d:I;return{top:J.scrollTop,left:J.scrollLeft}}function s(d){try{var w=d?(d.srcElement||d.target):null;if($dp.cal&&!$dp.eCont&&$dp.dd&&w!=$dp.el&&$dp.dd.style.display=="block"){$dp.cal.close()}}catch(d){}}function A(){$dp.status=2}var G,j;function g(M,d){if(!$dp){return}b();var J={};for(var L in M){J[L]=M[L]}for(var L in l){if(L.substring(0,1)!="$"&&J[L]===undefined){J[L]=l[L]}}if(d){if(!w()){j=j||setInterval(function(){if(E[z].readyState=="complete"){clearInterval(j)}g(null,true)},50);return}if($dp.status==0){$dp.status=1;J.el=i;a(J,true)}else{return}}else{if(J.eCont){J.eCont=$dp.$(J.eCont);J.el=i;J.autoPickDate=true;J.qsEnabled=false;a(J)}else{if(l.$preLoad&&$dp.status!=2){return}var I=N();if(n.event===I||I){J.srcEl=I.srcElement||I.target;I.cancelBubble=true}J.el=J.el=$dp.$(J.el||J.srcEl);if(J.el==null){alert("WdatePicker:el is null")}try{if(!J.el||J.el.My97Mark===true||J.el.disabled||($dp.dd&&r($dp.dd)!="none"&&$dp.dd.style.left!="-970px")){if(J.el.My97Mark){J.el.My97Mark=false}return}}catch(K){}if(I&&J.el.nodeType==1&&!C(J.el.initcfg,M)){$dp.unbind(J.el);J.el.initcfg=M}a(J)}}function w(){if(h&&E!=n&&E[z].readyState!="complete"){return false}return true}function N(){if(f){try{func=N.caller;while(func!=null){var O=func.arguments[0];if(O&&(O+"").indexOf("Event")>=0){return O}func=func.caller}}catch(P){}return null}return event}}function c(e,d){return e.currentStyle?e.currentStyle[d]:document.defaultView.getComputedStyle(e,false)[d]}function r(e,d){if(e){if(d!=null){e.style.display=d}else{return c(e,"display")}}}function a(e,d){var K=e.el?e.el.nodeName:"INPUT";if(d||e.eCont||new RegExp(/input|textarea|div|span|p|a/ig).test(K)){e.elProp=K=="INPUT"?"value":"innerHTML"}else{return}if(e.lang=="auto"){e.lang=h?navigator.browserLanguage.toLowerCase():navigator.language.toLowerCase()}if(!e.eCont){for(var J in e){$dp[J]=e[J]}}if(!$dp.dd||e.eCont||($dp.dd&&(e.getRealLang().name!=$dp.dd.lang||e.skin!=$dp.dd.skin))){if(e.eCont){w(e.eCont,e)}else{$dp.dd=E[z].createElement("DIV");$dp.dd.style.cssText="position:absolute";E[z].body.appendChild($dp.dd);w($dp.dd,e);if(d){$dp.dd.style.left=$dp.dd.style.top="-970px"}else{$dp.show();I($dp)}}}else{if($dp.cal){$dp.show();$dp.cal.init();if(!$dp.eCont){I($dp)}}}function w(V,P){var O=E[z].domain,S=false,M='';V.innerHTML=M;var L=l.$langList,U=l.$skinList,T;try{T=V.lastChild.contentWindow[z]}catch(Q){S=true;V.removeChild(V.lastChild);var N=E[z].createElement("iframe");N.hideFocus=true;N.frameBorder=0;N.scrolling="no";N.src="javascript:(function(){var d=document;d.open();d.domain='"+O+"';})()";V.appendChild(N);setTimeout(function(){T=V.lastChild.contentWindow[z];R()},97);return}R();function R(){var Y=P.getRealLang();V.lang=Y.name;V.skin=P.skin;var X=["